[erlang-questions] Pattern-matching function?

Robert Virding <>
Thu Oct 30 16:20:08 CET 2008


2008/10/30 Richard Carlsson <>

> Francois De Serres wrote:
> > Thank you Richard.
> > Any way to overcome this with parsing/binding/eval magic, even cumbersome
> ?
>
> But doing compilation on the fly might not be suitable if you are going
> to do it a million times (unless you can reuse the same module name, you
> will have to generate unique module names for each new compilation, and
> who will then be responsible for deleting unused modules?). If the code
> you are going to run is short and not a bottleneck, it could be better
> to use erl_eval, for example like this:
>
> make_match_fun(Pstr) -> element(2, erl_eval:expr(hd(element(2,
> erl_parse:parse_exprs(element(2,
> erl_scan:string(lists:flatten(io_lib:format("fun (~s=__P) ->
> {matched,__P}; (_) -> fail end.", [Pstr]))))))), erl_eval:new_bindings())).
>
> This will, via erl_eval, produce a fun that can be used like you wanted:
>
> F = make_match_fun("{X,Y}")
>
> F({1,2}) ==> {matched, {1,2}}
>
> F({}) ==> fail


My macro basically does this is easier, at least I think so.

Robert
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20081030/e00c5702/attachment.html>


More information about the erlang-questions mailing list