]> Creatis software - CreaPhase.git/blob - octave_packages/miscellaneous-1.1.0/reduce.m
Add a useful package (from Source forge) for octave
[CreaPhase.git] / octave_packages / miscellaneous-1.1.0 / reduce.m
1 ## Copyright (C) 2007 Muthiah Annamalai <muthiah.annamalai@mavs.uta.edu>
2 ##
3 ## This program is free software; you can redistribute it and/or modify it under
4 ## the terms of the GNU General Public License as published by the Free Software
5 ## Foundation; either version 3 of the License, or (at your option) any later
6 ## version.
7 ##
8 ## This program is distributed in the hope that it will be useful, but WITHOUT
9 ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10 ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
11 ## details.
12 ##
13 ## You should have received a copy of the GNU General Public License along with
14 ## this program; if not, see <http://www.gnu.org/licenses/>.
15
16 ## -*- texinfo -*-
17 ## @deftypefn {Function File} {@var{x} =} reduce (@var{function}, @var{sequence},@var{initializer})
18 ## @deftypefnx {Function File} {@var{x} =} reduce (@var{function}, @var{sequence})
19 ## Implements the 'reduce' operator like in Lisp, or Python.
20 ## Apply function of two arguments cumulatively to the items of sequence, 
21 ## from left to right, so as to reduce the sequence to a single value. For example,
22 ## reduce(@@(x,y)(x+y), [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5).
23 ## The left argument, x, is the accumulated value and the right argument, y, is the 
24 ## update value from the sequence. If the optional initializer is present, it is 
25 ## placed before the items of the sequence in the calculation, and serves as
26 ## a default when the sequence is empty. If initializer is not given and sequence
27 ## contains only one item, the first item is returned.
28 ##
29 ## @example
30 ##  reduce(@@add,[1:10])
31 ##  @result{} 55
32 ##      reduce(@@(x,y)(x*y),[1:7]) 
33 ##  @result{} 5040  (actually, 7!)
34 ## @end example
35 ## @end deftypefn
36
37 ## Parts of documentation copied from the "Python Library Reference, v2.5"
38
39 function rv = reduce (func, lst, init)
40   if (nargin < 2) || nargin > 3 || (class(func)!='function_handle') || (nargin == 2 && length(lst)<2)
41     print_usage();
42   end
43
44   l=length(lst);
45
46   if (l<2 && nargin==3)
47     if(l==0)
48       rv=init;
49     elseif (l==1)
50       rv=func(init,lst(1));
51     end
52     return;
53   end
54
55   if(nargin == 3)
56     rv=func(init,lst(1));
57     start=2;
58   else
59     rv=func(lst(1),lst(2));
60     start=3;
61   end
62
63   for i=start:l
64     rv=func(rv,lst(i));
65   end
66 end
67
68 %!assert(reduce(@(x,y)(x+y),[],-1),-1)
69 %!assert(reduce(@(x,y)(x+y),[+1],-1),0)
70 %!assert(reduce(@(x,y)(x+y),[-10:-1]),-55)
71 %!assert(reduce(@(x,y)(x+y),[-10:-1],+55),0)
72 %!assert(reduce(@(x,y)(y*x),[1:4],5),120)