【问题标题】:How to replace records with maps in MatchHead of Match Specification?如何在 Match Specification 的 MatchHead 中用地图替换记录?
【发布时间】:2014-11-20 11:33:54
【问题描述】:

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

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

这匹配具有field1 == 1 的表中的所有recordName 记录,并且还对field 进行隐式绑定,以便稍后在MatchBody 中使用。

地图有什么类似的吗?

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

% 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

编辑: 可能还不支持。刚看到this的帖子。

【问题讨论】:

    标签: select erlang maps matching ets


    【解决方案1】:
    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> 
    

    【讨论】:

      猜你喜欢
      • 2023-03-12
      • 2022-08-20
      • 2012-02-05
      • 1970-01-01
      • 2020-01-13
      • 1970-01-01
      • 2021-03-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多