view sequences/+seq/unfold_finite.m @ 61:eff6bddf82e3 tip

Finally implemented perceptual brightness thing.
author samer
date Sun, 11 Oct 2015 10:20:42 +0100
parents ae596261e75f
children
line wrap: on
line source
% unfold_finite - sequence obtained by iterating fn over state
%
% unfold_finite :: 
%    (S->pair(A,S))	~'unfolding function',
%    S         ~ initial state,
% -> unfold_finite(S,A) < seq(A).
%
% NB. The empty array [] is a special value for the state
% meaning there are no more elements in the sequence. You
% cannot use [] as a normal state value.
classdef unfold_finite < seq
	properties (GetAccess=private, SetAccess=immutable)
		fn
	end
	properties (GetAccess=private, SetAccess=private)
		value
		state
	end
	methods (Static)
		function d=make(f,s0)
			xs=f(s0);
			if isempty(xs), d=nil; else d=seq.unfold_finite(f,xs{2},xs{1}); end
		end
	end
	methods
		function d=unfold_finite(f,s,x)
			d.value=x;
			d.state=s;
			d.fn=f; 	% function to apply 
		end

		function s=elsize(o), s=size(o.value); end
		function s=tostring(o), s=sprintf('unfold_finite(%s,%s)',tostring(o.fn),tostring(o.state)); end
		function x=head(o), x=o.value; end
		function o=next(o) 
			xs=o.fn(o.state);
			if isempty(xs), o=nil;
			else o.value=xs{1}; o.state=xs{2};
			end
		end
	end
end