After revising this lecture, please read this terrifyingly beautiful review paper: A Tutorial on the Universality and Expressiveness of Fold by Graham Hutton.
But first, meet Ackermann. And go watch 'Mr Robot' later.
-- a fold on a list to get the sum of all elements
foldr (+) 0 [1, 2, 3, 4, 5]
{-# LANGUAGE DeriveFoldable #-}
-- a fold on a tree to get the sum of all elements
data Tree a = Leaf | Node (Tree a) a (Tree a) deriving Foldable
t = Node (Node (Node Leaf 1 Leaf) 2 (Node Leaf 5 Leaf)) 7 (Node Leaf 10 Leaf)
foldr (+) 0 t
markdown
:t foldr
:t (+)
foldr (+) 1 [1, 2, 3]
data List a = Nil | Cons a (List a) deriving Foldable
l = Cons 1 (Cons 2 (Cons 4 Nil))
sum l
1 : 2 : 3 : []
1 + (2 + (3 + 1))
sum [1, 2, 3]
length [1, 2, 3]
id [1, 2, 3]
reverse [1, 2, 3]
map (*3) [1, 2, 3]
filter (>2) [1, 2, 3]
foldr (\x y -> x + y) 0 [1, 2, 3]
foldr (\x y -> 1 + y) 0 [1, 2, 3]
foldr (\x y -> x:y) [] [1, 2, 3]
foldr (\x y -> y ++ [x]) [] [1, 2, 3]
foldr (\x y -> (3*x):y) [] [1, 2, 3]
foldr (\x y -> if x>2 then x:y else y) [] [1, 2, 3]
((+1) . sum) [1, 2, 3]