-module (ts). -export ([match/2, in/2, out/2, new/0]). -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. out(TS,Tuple) -> TS!{out,Tuple}. new() -> spawn_link(fun() -> tsLoop([],[]) end). tsLoop(TS,Ins) -> receive {out, Tuple} -> A = all(fun(X) -> match(element(2,X), Tuple) end, Ins), B = length(A), FA = head(A), if B > 0 -> element(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.