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


' FB 1.05.0 Win64
 
Type IntFunc As Function(As Integer, As Integer) As Integer  
 
Function reduce(a() As Integer, f As IntFunc) As Integer
   '' if array is empty or function pointer is null, return 0 say
   If UBound(a) = -1 OrElse f = 0 Then Return 0 
   Dim result As Integer = a(LBound(a))
   For i As Integer = LBound(a) + 1 To UBound(a)
     result = f(result, a(i)) 
   Next
   Return result
End Function
 
Function add(x As Integer, y As Integer) As Integer
  Return x + y
End Function
 
Function subtract(x As Integer, y As Integer) As Integer
  Return x - y
End Function
 
Function multiply(x As Integer, y As Integer) As Integer
  Return x * y
End Function
 
Function max(x As Integer, y As Integer) As Integer
  Return IIf(x > y, x, y)
End Function
 
Function min(x As Integer, y As Integer) As Integer
  Return IIf(x < y, x, y)
End Function
 
Dim a(4) As Integer = {1, 2, 3, 4, 5}
Print "Sum is        :"; reduce(a(), @add)
Print "Difference is :"; reduce(a(), @subtract)
Print "Product is    :"; reduce(a(), @multiply)
Print "Maximum is    :"; reduce(a(), @max)
Print "Minimum is    :"; reduce(a(), @min)
Print "No op is      :"; reduce(a(), 0)
Print
Print "Press any key to quit"
Sleep
 