How can I pattern match in a function where a Map has a key with the passed in value?

独自空忆成欢 提交于 2019-12-12 19:24:48

问题


So I am creating an IRC server, and I have a function that removes a user from a Map. The idea is to use pattern matching, so one version of a function gets called if the user is in the map and another function gets called otherwise.

My first idea was to do the following:

remove_user_from_channel(User, Channel=#channel_details{users = UserMap=#{User := _}}) ->
  Channel#channel_details{users = maps:remove(User, UserMap)}.

However, this fails to compile with the error variable 'User' is unbound.

Is there any way to accomplish this with function level pattern matching?


回答1:


You can't do pattern matching for map keys in a function head but you can do in case:

remove_user_from_channel(User, Map) ->
  case Map of
    Channel = #channel_details{users = UserMap = #{User := _}} ->
      Channel#channel_details{users = maps:remove(User, UserMap)};
    _ ->
      other
   end.



回答2:


remove_user_from_channel(User, Channel=#channel_details{users = UserMap}) ->
    case maps:is_key(User, UserMap) of
        true -> Channel#channel_details{users = maps:remove(User, UserMap)};
        false -> ok
    end.

I think you can't use match pattern in function level, but you can use is_key(Key, Map) -> boolean() to check User is in UserMap. Here is the link: http://erlang.org/doc/man/maps.html#is_key-2



来源:https://stackoverflow.com/questions/36416053/how-can-i-pattern-match-in-a-function-where-a-map-has-a-key-with-the-passed-in-v

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!