% limit - Get the limit of an infinite sequence if it exists
%
% limit :: 
%    (A,A->nonneg) ~ 'metric',
%    seq(A),        ~ 'sequence of converging values',
%    options {
%       maxit :: natural/10e6 ~ 'maximum iterations';
%       tol   :: nonneg/1e-5  ~ 'convergence tolerance'
%    }
% -> A, natural.

function [y,its]=limit(d,X,varargin)
	opts=options('maxit',10e6,'tol',1e-5,varargin{:});

	tol=opts.tol;
	S.x=head(X);
	S.X=next(X);
	S.f=false;
	S.its=0;
	S=iterate(@converger,S,'its',opts.maxit);
	y=S.x;
	its=S.its;

	function S=converger(S)
		[xx,S.X]=decons(S.X); 
		S.its=S.its+1;
		if d(S.x,xx)<tol, S=[]; else S.x=xx; end
	end
end
