xbo*_*ard 6 erlang pattern-matching
如何在Erlang中进行动态模式匹配?
我有功能过滤器/ 2:
filter(Pattern, Array)
Run Code Online (Sandbox Code Playgroud)
其中Pattern是一个字符串,其中包含我想要匹配的模式(例如"{book, _ }"或"{ebook, _ }"),由用户输入,而Array是异构元素的数组(例如{dvd, "The Godfather" } , {book, "The Hitchhiker's Guide to the Galaxy" }, {dvd, "The Lord of Rings"},等等)然后我想上面的filter/2返回Array中的元素数组匹配模式.
我已经尝试了一些erl_eval没有任何成功的想法......
请提前.
通过一点点文档研究:
Eval = fun(S) -> {ok, T, _} = erl_scan:string(S), {ok,[A]} = erl_parse:parse_exprs(T), {value, V, _} = erl_eval:expr(A,[]), V end,
FilterGen = fun(X) -> Eval(lists:flatten(["fun(",X,")->true;(_)->false end."])) end,
filter(FilterGen("{book, _}"), [{dvd, "The Godfather" } , {book, "The Hitchhiker's Guide to the Galaxy" }, {dvd, "The Lord of Rings"}]).
[{book,"The Hitchhiker's Guide to the Galaxy"}]
Run Code Online (Sandbox Code Playgroud)