racket Higher Order Functions Fold


Example

Fold Right successively applies a two-argument function to every element in a list from left to right starting with a base value:

foldr: (a b -> b) b (listof a) -> b

> (foldr + 0 (list 1 2 3 4))
10

> (foldr string-append "" (list "h" "e" "l" "l" "o"))
"hello"

> (foldr cons empty (list 1 2 3 4))
(list 1 2 3 4)

Fold Left performs the same action in the opposite direction:

foldl: (a b -> b) b (listof a) -> b

> (foldl + 0 (list 1 2 3 4)
10

> (foldl string-append "" (list "h" "e" "l" "l" "o"))
"olleh"

> (foldl cons empty (list 1 2 3 4))
(list 4 3 2 1)