Created
March 3, 2011 01:28
-
-
Save archaelus/852140 to your computer and use it in GitHub Desktop.
Tuple space matching
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-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