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


Procedure.i reduce(List l(),op$="+")
  If FirstElement(l())
    x=l()
    While NextElement(l())
      Select op$
        Case "+" : x+l()
        Case "-" : x-l()
        Case "*" : x*l()
      EndSelect
    Wend
  EndIf
  ProcedureReturn x
EndProcedure
 
NewList fold()
For i=1 To 5 : AddElement(fold()) : fold()=i : Next
 
Debug reduce(fold())
Debug reduce(fold(),"-")
Debug reduce(fold(),"*")