问题
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