Is it a list ?

Luke Gorrie luke@REDACTED
Thu Jul 10 23:33:26 CEST 2003

```Luke Gorrie <luke@REDACTED> writes:

>   match(Pattern, Object) -> match(Pattern, Object, []).
>
>   %% match(Pattern, Object, Bindings) => Bindings' | nomatch
>   match([P|Ps], [X|Xs], Bs) ->            % matching a list..
>       match(Ps, Xs, match(P, X, Bs));
>   match(_, _, nomatch) ->
>       %% This tricky clause is to handle the previous one's recursion --
>       %% it will pass 'nomatch' instead of a bindings list if the first
>       %% element of a list doesn't match!
>       nomatch;
>   match(P, X, Bs) when atom(P) ->         % matching a variable..
>       case lists:keysearch(P, 1, Bs) of   % is it bound?
>           false           -> [{P,X}|Bs];  % no -- create binding
>           {value, {P, X}} -> Bs;          % yes -- existing binding matches
>           {value, {P, _}} -> nomatch      % yes -- incompatible binding!
>       end;
>   match(X, X, Bs) ->                      % successful match of a constant..
>       Bs;
>   match(_, _, _) ->                       % failure!
>       nomatch.

Actually, this one is cuter, if a bit less "software engineered":

match(Pattern, Object) ->
case catch match(Pattern, Object, []) of
{'EXIT', _} -> nomatch;
Bindings    -> lists:reverse(Bindings)
end.

match([P|Ps], [X|Xs], Bs) ->
match(Ps, Xs, match(P, X, Bs));
match(P, X, Bs) when atom(P) ->
case lists:keysearch(P, 1, Bs) of
false           -> [{P,X}|Bs];
{value, {P, X}} -> Bs
end;
match(X, X, Bs) -> Bs.

NB: http://www-csli.stanford.edu/~john/procrastination.html

Cheers,
Luke

```