是否可以通过编程方式进行模式匹配?
Pattern = {error, '_'},
IsError =
case {error, "foo"} of
Pattern -> true;
_ -> false
end.
我知道我可以使用宏来做到这一点,但我有一个我想要匹配的动态模式列表,这些模式是提前未知的。
最佳答案
也许您能得到的最接近的是使用编译的 match specification ,通过调用函数 ets:match_spec_compile
和 ets:match_spec_run
:
MS = ets:match_spec_compile([{{error, '_'}, [], ['$_']}]).
Items = [ok, {error, foo}, {error, bar}].
ets:match_spec_run(Items, MS).
这将返回 Items
列表中匹配的两个项目:
[{error,foo},{error,bar}]
关于erlang - 以编程方式使用模式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72913706/