Foldable and Traversable

-- Foldable: things that can be folded to a summary value
-- foldr, foldMap, toList, null, length, elem, sum, product, maximum, minimum, any, all, concatMap, for_, traverse_
import Data.Foldable (toList, foldl', for_, traverse_)

sum (Just 5)                    -- 5
length (Right 3)                -- 1
length (1, 2)                   -- 1 (only the second component: a classic surprise)
maximum (Node (Node Leaf 1 Leaf) 5 Leaf)   -- works on our Tree once it's Foldable
elem 3 (Just 3)                 -- True
for_ [1, 2, 3] print

instance Foldable Tree where
  foldMap _ Leaf = mempty
  foldMap f (Node l x r) = foldMap f l <> f x <> foldMap f r

-- Traversable: traverse a structure with an effect, rebuilding the same shape
-- traverse :: Applicative f => (a -> f b) -> t a -> f (t b)
traverse readMaybe ["1", "2"] :: Maybe [Int]          -- Just [1,2]
traverse readMaybe ["1", "x"] :: Maybe [Int]          -- Nothing
traverse (\x -> [x, x * 10]) [1, 2]                   -- [[1,2],[1,20],[10,2],[10,20]]
sequence [Just 1, Just 2]                             -- Just [1,2]
sequence [[1, 2], [3]]                                -- [[1,3],[2,3]]
traverse print (Just 42)                          
…