[erlang-questions] Pattern-matching function?

Robert Virding <>
Wed Oct 29 21:19:40 CET 2008


One solution is to use macros as a wrapper around a fun. So for example you
could define:

-define(pattern(Pat, Ret) , fun (Pat) -> {yes,Ret}; (_) -> no end).

and then use it like:

Match = ?pattern({x,X,y,z}, X),

Match({x,anything,yz}) ==> {yes,anything}.

and use it like:

case Match(Value) of
    {yes,X} -> ... ;
    no -> ...
end

As for Francois request you could probably use macros there as well, but
your question was very general so I can not really give you a suggestion.
What are you after?

As Richard said variables in Erlang don't exist as in Prolog so you can only
"create" them by binding them to a value. They also have to be always bound
so you cannot "return" a variable, only a value which can then be bound to a
variable, as in the macro example above. The X in the macro call never
escapes from the fun it is only used to show which values from the pattern
are returned.

Robert

2008/10/29 anders conbere <>

> On Wed, Oct 29, 2008 at 7:24 AM, Richard Carlsson <>
> wrote:
> > Francois De Serres wrote:
> >> Hi there.
> >>
> >> I need a function that actually does pattern matching: pm(Tuple,
> Pattern)->MatchedPattern|error
> >
> > You cannot pass a pattern with uninstantiated variables to a function.
> > Erlang is a strict functional language, it is not Prolog. Patterns are
> > not run-time values.
>
> That being said, the lack of first class access to Patterns makes
> programmatic access to a few of the most common tools in erlang
> exceptionally difficult. Constructing case statements at runtime is
> impossible with out accessing the preproccessor, building functions at
> runtime that have many different possible patterns, also impossible.
> It seems like there should be some way to gain access to this.
>
> I could for instance imagine delaying access to with a function that
> accepted something like
>
> pattern(x, supplies("X"), y, z)
>
> which would return a function that when applied to a tuple
>
> {x, anything, y, z}
>
> would return
>
> {ok, {match, [{"X", anything}]}}
>
> and in that way you could construct semantics for applying those to
> case statements or function parameters, etc. Maybe that's crazy, but I
> sympathize with Francois, I've been trying to fumble my way through
> erlang metaprogramming and just running into huge walls like this.
>
> ~ Anders
>
>
>
>
> >
> >    /Richard
> > _______________________________________________
> > erlang-questions mailing list
> > 
> > http://www.erlang.org/mailman/listinfo/erlang-questions
> >
> _______________________________________________
> erlang-questions mailing list
> 
> http://www.erlang.org/mailman/listinfo/erlang-questions
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20081029/b81fecab/attachment.html>


More information about the erlang-questions mailing list