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


Push 5, 4, 3, 2, 1: s = Used() - 1
For x = 0 To s: @(x) = Pop(): Next
 
Print "Sum is        : "; FUNC(_reduce(0, s, _add))
Print "Difference is : "; FUNC(_reduce(0, s, _subtract))
Print "Product is    : "; FUNC(_reduce(0, s, _multiply))
Print "Maximum is    : "; FUNC(_reduce(0, s, _max))
Print "Minimum is    : "; FUNC(_reduce(0, s, _min))
Print "No op is      : "; FUNC(_reduce(0, s, _noop))
End
 
_reduce
  Param (3)
  Local (2)
 
  If (Line(c@) = 0) + ((b@ - a@) < 1) Then Return (0)
  d@ = @(a@)
  For e@ = a@ + 1 To b@
    d@ = FUNC(c@ (d@, @(e@)))
  Next
Return (d@)
 
_add      Param (2) : Return (a@ + b@)
_subtract Param (2) : Return (a@ - b@)
_multiply Param (2) : Return (a@ * b@)
_max      Param (2) : Return (Max(a@, b@))
_min      Param (2) : Return (Min(a@, b@))