[erlang-questions] solved: Pattern-matching function?
Francois De Serres
fdeserres@REDACTED
Thu Oct 30 17:25:55 CET 2008
I'll investigate further both of these options:
A) Match Specifications with ets:match_spec_run/2 (thanks to Michael Radford):
slightly awkward to use (match spec syntax), but straightforward to implement.
<http://www.erlang.org/doc/apps/erts/match_spec.html>
B) ad-hoc matching functions generated with erl_eval (thanks to Richard Carlsson):
metaprogramming magic, but the resulting API is lean.
8<--------
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())).
F = make_match_fun("{X,Y}")
F({1,2}) ==> {matched, {1,2}}
F({}) ==> fail
8<--------
Thanks to all for your precious help,
--
François
> Hi there.
>
> I need a function that actually does pattern matching: pm(Tuple,
> Pattern)->MatchedPattern|error
> > pm({a,b,c}, {a,X,Y}).
> {a,b,c}
> >X.
> b
> > pm({a,b,c}, {b,X,Y}).
> {error, badmatch}
> > pm({a,b,c}, {a,X}).
> {error, badmatch}
> etc.
>
> This trivial code works only with the empty tuple/pattern :
> pm(T,P) ->
> P = T, P.
> because pattern variables (X, Y) are unbound at function call.
>
> I tried to find a hint in the libs with no avail.
> If anyone has a lead, can you please put me on track?
>
> Thanks,
> --
> Francois
>
> --
> "Feel free" - 10 GB Mailbox, 100 FreeSMS/Monat ...
> Jetzt GMX TopMail testen: http://www.gmx.net/de/go/topmail
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://www.erlang.org/mailman/listinfo/erlang-questions
--
"Feel free" - 10 GB Mailbox, 100 FreeSMS/Monat ...
Jetzt GMX TopMail testen: http://www.gmx.net/de/go/topmail
--
GMX Download-Spiele: Preizsturz! Alle Puzzle-Spiele Deluxe über 60% billiger.
http://games.entertainment.gmx.net/de/entertainment/games/download/puzzle/index.html
More information about the erlang-questions
mailing list