% merger - Combine several seq sources using a given function
%
% merger :: 
% 	( (A1,...,An)->natural 	~ chooser function,
% 	  n:natural          	~ number of sources to combine,
% 	  seq A1,...,seq An	~ n seq sources,
% 	  ...                 	~ options
% 	) -> seq B
classdef merger < seq
	properties (GetAccess=private, SetAccess=private)
		fn
		sources
		hd
	end
	methods
		function d=merger(c,sources,varargin)
			d.fn=c;
			d.hd=[];
			d.sources=sources;
		end


		function x=head(d), x=d.hd; end
		function d=next(d)
			data=cellmap(@head,d.sources);
			if isempty(data), d=nil
			else
				k=d.fn(data);
				d.hd=data{k};
				nk=next(d.sources{k});
				if isempty(nk), d.sources(k)=[];
				else d.sources{k}=nk; end
			end
		end
					
		function z=elsize(d), z=size(d.hd); end
		function s=tostring(d)
			s=sprintf('{ %s } >> merge(%s)',catsep(',',cellmap(@tostring,d.sources)),tostring(d.fn));
		end
	end
end
