关于Erlang中ETS的查询与匹配(match, match_object, select)

匿名 (未验证) 提交于 2019-12-02 23:36:01
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_38278878/article/details/90675911

1.ets:match/2

以最常用的match函数为例子

match(Tab, Pattern) -> [Match]    Types:           Tab = tid() | atom()           Pattern = tuple()           Match = [term()] 

Tab是ETS的tid()或ETS的表名;

Pattern是一个匹配模式,是一个tuple()
这个tuple里element的数量与ETS中tuple一致, 比如

Tab = ets:new(ets_tab, [named_table, bag]). ets:insert(Tab, [{apple, 1}, {pear, 2}, {orange, 3}, {grape, 4}, {watermelon, 5}, {apple, 6}]).  

上例中ETS里的tuple的element的数量为2,那Pattern就是{x, y}这样的格式。

match函数根据模式Pattern,匹配表中的tuple()。Pattern可能包含以下三种内容的数据项:

  1. Erlang数据项。这是一种强匹配,如{apple, '$1'}可匹配第一个element为原子apple的
  2. '_' 。可匹配任何项目;
  3. 模式变量'$N',N=0,1,... 如"$0","$1"等,用于返回匹配结果。

下面举一些例子,首先准备有以下数据的ETS表:

Tab = ets:new(ets_tab, [named_table, bag]). ets:insert(Tab, [{apple, 1}, {pear, 2}, {orange, 3}, {grape, 4}, {watermelon, 5}, {apple, 6}]).  

匹配第一个元素为apple的元素,并返回模式变量

> ets:match(Tab, {apple, '$1'}). [[1],[6]]  

匹配第二个元素为3的元素,并返回模式变量

> ets:match(Tab, {'$1', 3}). [[orange]]  

匹配第一个元素为任意的元素,并返回模式变量

> ets:match(Tab, {'_', '$1'}). [[5],[4],[1],[6],[3],[2]]  

2.ets:match_object/2

match_object(Tab, Pattern) -> [Object]   Types:         Tab = tid() | atom()         Pattern = Object = tuple() 

match_object的匹配模式与match相同,只是返回的是整个tuple()

匹配第一个元素为apple的元素,并返回模式变量

> ets:match_object(Tab, {apple, '$1'}). [{apple,1},{apple,6}]  

3.ets:select/2

这个函数要与ets:fun2ms/1配合使用。

ets:fun2ms/1这个函数是语法函数转为匹配规范的伪函数。

在使用它时,必须引入下面的头文件

-include_lib("stdlib/include/ms_transform.hrl"). 

函数返回的值就是一个匹配规范。

下面直接举例:

匹配第一个元素为apple的Object

MS_0 = ets:fun2ms(fun({Key, Value} = Object) when Key =:= apple -> Object end). ets:select(Tab, MS_0). [{apple,1},{apple,6}] 

匹配第一个元素为apple,且第二个元素大于3的Object

MS_1 = ets:fun2ms(fun({Key, Value} = Object) when Key =:= apple andalso Value > 3-> Object end). ets:select(Tab, MS_1). [{apple,6}] 

注:ets:fun2ms/1传入的函数的有很严格的限制条件,它只提供一个的参数(用于匹配的对象,单一的变量或一个元组。而且跟在when后面的条件必须是Erlang的内置函数或逻辑判断。

总结

简单查询可以用ets:match/2和ets:matches/2,复杂条件查询就用ets:select/2。ets:select/2和ets:fun2ms/1配合,就像是函数式编程版本的SQL语句查询。

文章来源: https://blog.csdn.net/weixin_38278878/article/details/90675911
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!