【问题标题】:Erlang search for specific element in list of recordsErlang在记录列表中搜索特定元素
【发布时间】:2020-10-29 05:44:15
【问题描述】:

我定义了 2 条记录:

-record(state, {port = 9921,
                clients = []
               }
        ).

-record (client, {pid,
                  acc}).

我创建了包含端口和 3 条记录的变量:

 State = #state{port = 9921, 
                clients = []},
 NewClient1 = #client{pid = "A", acc = <<85>>},
 NewClient2 = #client{pid = "B", acc = <<73>>},
 NewClient3 = #client{pid = "C", acc = <<56>>},
 NewState = State#state{clients = [NewClient1 , NewClient2, NewClient3]},

NewState 现在包含

#state{port = 9921,
   clients = [#client{pid = "A",acc = <<"U">>},
              #client{pid = "B",acc = <<"I">>},
              #client{pid = "C",acc = <<25>>}]}

我的问题是,我想搜索某个特定 pid 的记录状态,例如:我希望函数 find ("B", NewState) 为 true,函数 find ("Z", NewState) 为 false。最简单的方法是什么?

【问题讨论】:

    标签: erlang


    【解决方案1】:

    您可以使用事实,即#client.pid 在记录元组中包含pid 的索引。

    如此简单和最有效(最多 100 个客户端,那么您应该更改 #state.clients 的数据格式以映射或使用 ets)解决方案是

    lists:keyfind(Pid, #client.pid, State#state.clients) =/= false
    

    1> rd(state, {port, clients}).              
    state
    2> rd(client, {pid, acc}).
    client
    3> State = #state{port=9921, clients=[#client{pid = "A", acc = <<85>>}, #client{pid = "B", acc = <<73>>}, #client{pid = "C", acc = <<56>>}]}.
    #state{port = 9921,
           clients = [#client{pid = "A",acc = <<"U">>},
                      #client{pid = "B",acc = <<"I">>},
                      #client{pid = "C",acc = <<"8">>}]}
    4> #client.pid.         
    2
    5> Find = fun(Pid, State) -> lists:keyfind(Pid, #client.pid, State#state.clients) =/= false end.
    #Fun<erl_eval.12.50752066>
    6> Find("B", State).
    true
    7> Find("Z", State).
    false
    

    【讨论】:

      【解决方案2】:

      记录语法允许您通过以下方式访问客户列表:

      Clients = NewState#state.clients
      

      然后您可以使用函数 lists:any/2 来检查列表中至少一个元素的条件是否为真:

      lists:any(Pred, List)
      

      把所有东西放在一起

      found(Test, NewState) ->
          lists:any(fun(X) -> X#client.pid == Test end, NewState#state.clients).
      

      【讨论】:

        猜你喜欢
        • 2018-12-10
        • 2012-10-17
        • 1970-01-01
        • 1970-01-01
        • 2021-12-06
        • 1970-01-01
        • 1970-01-01
        • 2012-02-13
        相关资源
        最近更新 更多