【问题标题】:Can multiple guards be used in an erlang ets match spec?可以在 erlang ets 匹配规范中使用多个警卫吗?
【发布时间】:2015-01-16 07:41:50
【问题描述】:

我想构造一个匹配规范,以便在第二个元素上找到匹配项时从元组中选择第一个元素,或者在第一个元素匹配时选择第二个元素。而不是调用 ets:match 两次,这可以在一个匹配规范中完成吗?

【问题讨论】:

    标签: erlang ets


    【解决方案1】:

    是的。

    在documentation 中有is_integer(X), is_integer(Y), X + Y < 4711 或[{is_integer, '$1'}, {is_integer, '$2'}, {'<', {'+', '$1', '$2'}, 4711}] 的示例。

    如果您使用fun2ms,只需编写带有两个子句的函数。

    fun({X, Y}) when in_integer(X)
                     andalso X > 5 ->
           Y;
    
       ({X, Y}) when is_integer(Y)
                     andalso Y > 5 ->
           X.
    

    但您也可以创建两个MatchFunctions。每个都包含{MatchHead, [Guard], Return}。

    匹配头基本上告诉您数据的外观(它是一个元组,有多少元素...)并分配给每个元素匹配变量$N,其中N 将是某个数字。假设正在使用二元素元组,因此您的匹配头将是 {'$1', '$2'}。

    现在让我们创建守卫:对于第一个函数,我们将假设一些简单的东西,比如第一个参数是大于 10 的整数。所以第一个守卫是{is_integer, '$2'},第二个是{'>', '$2', 5}。在两者中,我们都使用匹配头 '$2' 的第一个元素。第二个匹配函数将具有相同的守卫,但使用'$1'。

    终于回归了。因为我们只想返回一个元素,所以对于第一个函数,它将是 '$1',对于第二个函数是 '$2'(返回元组稍微复杂一点,因为您必须将它包装在额外的元素元组中)。

    所以最后,当放在一起时,它给了我们

    [ _FirstMatchFunction = {_Head1 = {'$1', '$2'},
                             _Guard1 = [{is_integer, '$2},
                                        {'>', '$2', 5}],     % second element matches
                             _Return1 = [ '$1']},            % return first element             
      _SecondMatchFunction = {_Head2 = {'$1', '$2'},
                              _Guard2 = [{is_integer, '$1},
                                         {'>', '$1', 5}],      % second element matches
                              _Return2 = [ '$2']} ]            % return first element
    

    没有太多时间来测试这一切,但它应该可以工作(也许有一些小的调整)。

    【讨论】:

    • 谢谢!虽然使用第一种形式,但我仍然不确定如何根据哪个表达式匹配来选择元组的不同元素?
    • 即用 fun2ms 来表达。
    【解决方案2】:
    -export([main/0]).
    -include_lib("stdlib/include/ms_transform.hrl").
    main() ->
        ets:new(test, [named_table, set]),
        ets:insert(test, {1, a, 3}),
        ets:insert(test, {b, 2, false}),
        ets:insert(test, {3, 3, true}),
        ets:insert(test, {4, 4, "oops"}),
    
        io:format("~p~n", [ets:fun2ms(fun({1, Y, _Z}) -> Y;
                         ({X, 2, _Z}) -> X end)]),
    
        ets:select(test, ets:fun2ms(fun({1, Y, _Z}) -> {first_match, Y};
                       ({X, 2, _Z}) -> {second_match, X}
                    end)).
    

    输出是:

    [{{1,'$1','$2'},[],['$1']},{{'$1',2,'$2'},[],['$1']}]
    [{first_match,a},{second_match,b}]
    

    【讨论】:

      猜你喜欢
      • 2021-06-20
      • 2014-09-03
      • 2016-10-27
      • 2012-09-09
      • 2011-11-27
      • 1970-01-01
      • 2016-09-10
      • 2010-11-23
      • 1970-01-01
      相关资源
      最近更新 更多