ets查詢接口match、select說明


ets:match/2
用法:
match(Tab, Pattern) -> [Match]
返回和模式Pattern匹配的對象。
一個匹配模式可能包含:綁定部分、'_'匹配任何Erlang項和匹配變量。

示例

1>ets:match(test, '$1'). %% 匹配Tab里所有變量
[{1,2,3,4}, {5,6,7,8}]
2>ets:match(test, {'_','_',3,'$1'}).
[[4]]

 

避免過多'_'通配符出現,可以使用記錄record

示例

3>ets:match(test, #test{c=3,_='_',d='$1'}).
[[4]]

ps:如果要得到整個對象,可以使用ets:match_object/2。


ets:select/2
用法:
select(Tab, MatchSpec) -> [Match]
使用一個匹配描述match_spec匹配對象。該函數比ets:match/2和ets:match_object/2更常用,一個簡單的格式如下:
MatchSpec = [MatchFunction]
MatchFunction = {MatchHead, [Guard], [Result]}
MatchHead = "Pattern as in ets:match"
Guard = {"Guardtest name", ...}
Result = "Term construct"
一個匹配描述含有一個以上元組列表,元組有三個元素,第一個元素和ets:match/2中的匹配模式一致,第二個元素是一個斷言列表,可空,第三個元素是返回值描述。
返回值結構為MatchHead所綁定的匹配變量,或者特殊的匹配值'$_'(整個匹配對象)和'$$(包含所有匹配值)'。

示例

4>ets:select(test, [{#test{c=3,_='_',a='$2',d='$1'}, [], ['$_']}]).
[#test{a = 1,b = 2,c = 3,d = 4}]
5>ets:select(test, [{#test{c=3,_='_',a='$1',d='$2'}, [], ['$$']}]).
[[1,4]]
6>ets:select(test, [{#test{c=3,_='_',a='$1',d='$2'}, [], ['$2']}]).
[4]

 

如果需要表達復雜的匹配條件,就需要使用Match specifications

7> MS = ets:fun2ms(fun(#test{a=A, b=B}) when A > 1 -> B end).
[{#test{a = '$1',b = '$2',c = '_',d = '_'},
[{'>','$1',1}],
['$2']}]
8> ets:select(test, MS).
[6]

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM