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


arraybase 1
global n
dim n = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
 
print "  +: "; " "; cat(10, "+")
print "  -: "; " "; cat(10, "-")
print "  *: "; " "; cat(10, "*")
print "  /: "; " "; cat(10, "/")
print "  ^: "; " "; cat(10, "^")
print "max: "; " "; cat(10, "max")
print "min: "; " "; cat(10, "min")
print "avg: "; " "; cat(10, "avg")
print "cat: "; " "; cat(10, "cat")
end
 
function min(a, b)
    if a < b then return a else return b
end function
function max(a, b)
    if a > b then return a else return b
end function
 
function cat(cont, op$)
    temp = n[1]
    temp$ = ""
    for i = 2 to cont
        if op$ = "+" then temp += n[i]
        if op$ = "-" then temp -= n[i]
        if op$ = "*" then temp *= n[i]
        if op$ = "/" then temp /= n[i]
        if op$ = "^" then temp = temp ^ n[i]
        if op$ = "max" then temp = max(temp, n[i])
        if op$ = "min" then temp = min(temp, n[i])
        if op$ = "avg" then temp += n[i]
        if op$ = "cat" then temp$ += string(n[i])
    next i
    if op$ = "avg" then temp /= cont
    if op$ = "cat" then temp = int(string(n[1]) + temp$)
    return temp
end function