Skip to content

Instantly share code, notes, and snippets.

@archaelus
Created March 3, 2011 01:28
Show Gist options
  • Save archaelus/852140 to your computer and use it in GitHub Desktop.
Save archaelus/852140 to your computer and use it in GitHub Desktop.
Tuple space matching
-module(tuple_match).
-export([match/2, match2/2,
match_elements/2]).
-include_lib("eunit/include/eunit.hrl").
match(any, T) when is_tuple(T) ->
true;
match(P, Q)
when is_tuple(P), is_tuple(Q) ->
match_elements(tuple_to_list(P),
tuple_to_list(Q)).
match_elements([], []) -> true;
match_elements([any | Ps], [_ | Qs]) -> match_elements(Ps, Qs);
match_elements([P | Ps], [Q | Qs])
when is_tuple(P),
is_tuple(Q) ->
match(P, Q) andalso match_elements(Ps, Qs);
match_elements([P | Ps], [P | Qs]) -> match_elements(Ps, Qs);
match_elements(_, _) -> false.
match2(any,_) -> true;
match2(P,Q) when is_tuple(P), is_tuple(Q)
-> match2(tuple_to_list(P),tuple_to_list(Q));
match2([P|PS],[L|LS]) -> case match2(P,L) of
true -> match2(PS,LS);
false -> false
end;
match2(P,P) -> true;
match2(_,_) -> false.
simple_test_() ->
[ ?_assert(match2(any, {}))
,?_assert(match2({1}, {1}))
,?_assert(not match2({1}, {0}))
].
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment