map
and fold
(foldr
and foldl
) are defined and computed. Feel free to re-define any of the functions used in this document in the Function Editor.
map
map
is a function that performs some operation on every element in a list.
map
:: (a -> b) -> [a] -> [b]map
f [] = []map
f (x:xs) = f x :map
f xs
map
takes 2 inputs
(a -> b)
[a]
[b]
map
pattern matches on []
and returns []
.
map
pattern matches on the first list element x
and returns (f x) : map
f xs
.
fold
fold
describes 2 functions that "summarize" the elements in a list.
foldr
- "fold right", applies f
to x
and the result of folding f
over the rest (remember: foldr
moves to the right as it computes with the computation on the outside)foldl
- "fold left", evaluates f x i
immediately and uses that as the new initial value for folding f
over the rest (remember: foldl
stays on the left as it computes with the computation on the inside)foldr
foldr
:: (a -> b -> b) -> b -> [a] -> bfoldr
f i [] = ifoldr
f i (x:xs) = f x (foldr
f i xs)
foldr
takes 3 inputs
(a -> b -> b)
b
[a]
b
foldr
pattern matches on []
and returns i
.
foldr
pattern matches on the first list element x
and returns f x (foldr
f i xs)
.
foldl
foldl
:: (a -> b -> a) -> a -> [b] -> afoldl
f i [] = ifoldl
f i (x:xs) =
foldl
f (f i x) xs
foldl
takes 3 inputs
(a -> b -> a)
a
[b]
a
foldl
pattern matches on []
and returns i
.
foldl
pattern matches on the first list element x
and returns foldl
f (f i x) xs
.