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


 
use Collection;
 
class Reducer {
  function : Main(args : String[]) ~ Nil {
    values := IntVector->New([1, 2, 3, 4, 5]);
    values->Reduce(Add(Int, Int) ~ Int)->PrintLine();
    values->Reduce(Mul(Int, Int) ~ Int)->PrintLine();
  }
 
  function : Add(a : Int, b : Int) ~ Int {
    return a + b;
  }
 
  function : Mul(a : Int, b : Int) ~ Int {
    return a * b;
  }
}