如何在Match Specification的MatchHead中用映射替换记录



Erlang匹配规范支持以下模式,匹配规范的MatchHead中有记录:

#recordName{field1=1, field='$1', _='_'}

这将匹配具有field1 == 1的表中的所有recordName记录,并执行稍后在MatchBody中使用的field的隐式绑定。

地图上有类似的东西吗?

我尝试了(除了谷歌)以下语法:

% ERROR: * 1: only association operators '=>' are allowed in map construction
#{key:=1, key:='$1', _:='_'}

% ERROR: * 1: illegal use of variable '_' in map
#{key=>1, key=>$1', _=>'_'}

有没有可能做到这一点,并且语法记录在我找不到的地方?或者,这是一种错误的思维方式来看待地图取代记录吗?

TIA-

编辑:也许它还没有得到支持。刚刚看到这个帖子。

1> M = #{k1 => 1, k2 => 2, k3 => 3}.
#{k1 => 1,k2 => 2,k3 => 3}
2> #{k1:=1,k2:=V} = M.
#{k1 => 1,k2 => 2,k3 => 3}
3> V.
2
4> %% but you cannot do
4> ets:fun2ms(fun(#{key1:=V, key2:=R}) when V == 1 -> R end).
Error: ets:fun2ms requires fun with single variable or tuple parameter
{error,transform_error}
5> 
5> %% while it is possible to do
5> ets:fun2ms(fun({V,R}) when V == 1 -> R end).
[{{'$1','$2'},[{'==','$1',1}],['$2']}]
6> %% or
6> rd(foo,{k1,k2}).
foo
7> ets:fun2ms(fun(#foo{k1=V,k2=R}) when V == 1 -> R end).
[{#foo{k1 = '$1',k2 = '$2'},[{'==','$1',1}],['$2']}]
8> %% or even
8> ets:fun2ms(fun(#foo{k1=1,k2=R}) -> R end).            
[{#foo{k1 = 1,k2 = '$1'},[],['$1']}]
9> 

最新更新