Public feed
#376854
-module (ts).
-export ([match/2, in/2]).
-import (lists,[all/2, append/2, delete/2, head/1, nth/2]).
match(any,_) -> true;
match(P,Q) when tuple(P), tuple(Q)
-> match(tuple_to_list(P),tuple_to_list(Q));
match([P|PS],[L|LS]) -> case match(P,L) of
true -> match(PS,LS);
false -> false
end;
match(P,P) -> true;
match(_,_) -> false.
in(TS,Pattern) -> TS!{in,self(),Pattern},
receive {inrep, x} -> x end.
new() -> spawn_link(fun() -> tsLoop([],[]) end).
tsLoop(TS,Ins) ->
receive
{out, Tuple} ->
A = all(fun(x) -> match(tuple_nth(2,x), Tuple) end, Ins),
B = length(A),
FA = head(A),
if
B > 0 -> tuple_nth(1,FA)!Tuple,
tsLoop(TS, delete(FA,Ins));
B == 0 -> tsLoop(append(TS,[Tuple]), Ins)
end;
{in, ReplyId, Pattern} ->
A = all(fun(x) -> match(Pattern, x) end,TS),
case length(A) == 0 of
true -> tsLoop(TS,append(Ins,[{ReplyId,Pattern}]));
false -> ReplyId!{inrep, head(A)},
tsLoop(delete(head(A),TS), Ins)
end
end.
tuple_nth(n, x) -> nth(n,tuple_to_list(x)).