Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.



Task

Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language.



See also

 Wikipedia article:   Fold
 Wikipedia article:   Catamorphism


 
Module CheckIt {
      Function Reduce (a, f) {
            if len(a)=0 then Error "Nothing to reduce"
            if len(a)=1 then  =Array(a) : Exit
            k=each(a, 2, -1)
            m=Array(a)
            While k {
                  m=f(m, array(k))
            }
            =m
      }
      a=(1, 2, 3, 4, 5)
      Print "Array", a
      Print "Sum", Reduce(a, lambda (x,y)->x+y)
      Print "Difference", Reduce(a, lambda (x,y)->x-y)
      Print "Product", Reduce(a, lambda (x,y)->x*y)
      Print "Minimum", Reduce(a, lambda (x,y)->if(x<y->x, y))
      Print "Maximum", Reduce(a, lambda (x,y)->if(x>y->x, y))
}
CheckIt
 