Erlang--->>>lists:keyfind VS ets:lookup

来源:互联网 发布:vm centos 桥接模式 编辑:程序博客网 时间:2024/06/06 12:45
lists:keyfind VS ets:lookup
lists:keyfind("hello",2,L)  这里的hello不是Key,ets里面才有Key一说。
返回第一个满足条件的
如果查找结果为空返回false
ets:lookup(etsName,Key)
返回多条记录组成的List。


 ets:new(roomdata, [duplicate_bag, public, named_table, {keypos, 1}]).
ets:insert(roomdata,{"hello",2}).
ets:insert(roomdata,{"hello",2}).
L=ets:lookup(roomdata,"hello").
%% L=[{"hello",2},{"hello",2}].
LL=lists:keyfind("hello",1,L).
%%LL={"hello",2}

ets转换为List

1)ets:match(roomdata,'$1')                          //'$1'表示提取元组

2)ets:match_object(roomdata,{'_','_'}).       // {‘_’,‘_’}这里有两个通配符'_'是因为roomdata中一个元组有两个元素。

两者区别:1)的结果是[  [ {"hello",2} ], [  {"hello",2}   ],...],

                      2)的结果是[     {"hello",2}  ,    { "hello",2 },...]。



问题一:【{1,"a"},{1,"b"},{1,"c"},...】
请问怎样一次性提取出"a","b","c"。我想到循环使用lists:keyfind+ets:delete,这太low
 1)
ets:new(roomdata, [duplicate_bag, public, named_table, {keypos, 1}]).
ets:insert(roomdata,{"hello",2}).
ets:insert(roomdata,{"hello",2}).
ets:insert(roomdata,{"hello",2}).
[K||{_,K}<- ets:lookup(roomdata,"hello")].
%[2,2,2]
 2)
用proplists:get_all_values(key,list)

proplists:get_all_values("hello",L).

%[2,3]



问题二:【{1,"a"},{2,"a"},{3,"a"},...】如何提取出1,2,3

 [A||{A,_}<-ets:match_object(roomdata,{'_',"a"})].

%[1,2,3]

推荐阅读:

http://www.cnblogs.com/me-sa/archive/2011/08/11/erlang0007.html



@doonething@163.com

0 0