如何在Map包含具有传入值的键的函数中进行模式匹配? [英] How can I pattern match in a function where a Map has a key with the passed in value?
本文介绍了如何在Map包含具有传入值的键的函数中进行模式匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
因此,我正在创建IRC服务器,并且具有将用户从地图中删除的功能。这个想法是使用模式匹配,因此如果用户在地图上,则将调用一个函数的一个版本,否则将调用另一个函数。
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)}.
但是,此操作无法编译,错误为变量'User'未绑定
。
However, this fails to compile with the error variable 'User' is unbound
.
有什么方法可以通过功能级别模式匹配来做到这一点?
Is there any way to accomplish this with function level pattern matching?
推荐答案
您不能在函数头中对映射键进行模式匹配,但可以在情况下进行
:
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.
这篇关于如何在Map包含具有传入值的键的函数中进行模式匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文