Public feed #376837

Miscellany

public text v1 · immutable
Raw Edit
·published 2007-03-01 09:22 UTC
rendered paste body
-module (ts).
-export ([match/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.


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, Tuple} ->
			A = lists:all(fun(x) -> match(Tuple, x) end,ts),
			case length(A) == 0 of  
				true -> 	tsLoop(ts,append(ins,[{ReplyId,Tuple}]));
				false -> 	ReplyId!{inrep, head(A)},
							tsLoop(delete(head(A),ts), ins)
			end
	end.


tuple_nth(n, x) -> nth(n,tuple_to_list(x)).