1 ## Copyright (C) 2007 Muthiah Annamalai <muthiah.annamalai@mavs.uta.edu>
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
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
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/>.
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.
30 ## reduce(@@add,[1:10])
32 ## reduce(@@(x,y)(x*y),[1:7])
33 ## @result{} 5040 (actually, 7!)
37 ## Parts of documentation copied from the "Python Library Reference, v2.5"
39 function rv = reduce (func, lst, init)
40 if (nargin < 2) || nargin > 3 || (class(func)!='function_handle') || (nargin == 2 && length(lst)<2)
59 rv=func(lst(1),lst(2));
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)