用于将匹配模式作为地图中的键时,变量未绑定 [英] Variable is unbound when used to pattern match as a key in a map
问题描述
当第二个参数是具有 name
的值与第一个参数地图中的键相同的地图时,我想对一个键上的图进行模式匹配。
I want to pattern match a map on a key when the second argument is a map with name
's value being the same as the key in the first argument's map.
相反,我得到这个:
8> c(room).
room.erl:23: variable 'PlayerName' is unbound
error
status({_Players, _Tables, ChallengerName}, #{name := ChallengerName}) ->
#{status => challenging};
status({#{PlayerName := PlayerStatus}, _, _}, #{name := PlayerName}) ->
PlayerStatus;
status(_, _) ->
#{status => null}.
奇怪的是,第一个函数声明工作正常,我将模式匹配一个元组中的元素到一个值一张地图。
Oddly, the first function declaration works fine where I pattern match an element in a tuple to a value in a map.
我发现 erlang地图中的模式匹配键 - 是否有办法在一个关键字上进行模式匹配?什么是最有效的解决方法?
I found Pattern matching key in erlang maps - is there no way to pattern match on a key? What's the most efficient workaround?
推荐答案
我希望只是更改参数顺序会起作用,但显然不是。所以你需要在身体内进行模式匹配,在名称
绑定后:
I've hoped just changing the parameter order would work, but apparently not. So you need to pattern-match inside the body, after Name
is bound:
status(Triple, #{name := Name}) ->
case Triple of
{_Players, _Tables, Name} -> #{status => challenging};
{#{Name := PlayerStatus}, _, _} -> PlayerStatus;
_ -> #{status => null}
end.
这篇关于用于将匹配模式作为地图中的键时,变量未绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!