Haskell Foldable & Traversable
Functions like sum, length, elem and maximum don't only work on lists. Their real types mention Foldable, the class of structures you can reduce to a summary value. Its partner Traversable is the class of structures you can walk through while running an effect at each element, collecting the results in the same shape.
ghci> :type sum
sum :: (Foldable t, Num a) => t a -> a
ghci> :type traverse
traverse :: (Traversable t, Applicative f) => (a -> f b) -> t a -> f (t b)Foldable: one interface, many containers
import qualified Data.Map as Map
import qualified Data.Set as Set
main :: IO ()
main = do
let scores = Map.fromList [("ana", 7), ("bo", 9), ("cy", 4)]
print (sum scores, maximum scores, length scores) -- folds over the values
print (sum (Just 5), length (Just 'x'), length Nothing)
print (elem 3 (Set.fromList [1, 2, 3]))
print (sum (Right 10 :: Either String Int), length (Left "e" :: Either String Int))
print (length (1, 2)) -- a pair holds one foldable value!
print (foldr (:) [] (Set.fromList "banana")) -- toList via foldr(20,9,3)
(5,1,0)
True
(10,0)
1
"abn"
That length (1, 2) is 1 surprises everyone once. For Foldable, a pair (a, b) contains only its second component, the same way fmap only touches the second component. The first is treated as context.
| Foldable method | Meaning |
|---|---|
foldr, foldl', foldMap |
general reductions |
toList (Data.Foldable) |
the elements as a list |
null, length |
emptiness and size |
elem, sum, product, maximum, minimum |
the usual summaries |
any, all, concatMap, and, or |
also generalised to any Foldable |
for_, traverse_, mapM_ |
run an action for each element |
Making your own type Foldable
Implement either foldr or foldMap, and every function in the table works:
import Data.Foldable (toList)
data Tree a = Leaf | Node (Tree a) a (Tree a)
instance Foldable Tree where
foldMap _ Leaf = mempty
foldMap f (Node l x r) = foldMap f l <> f x <> foldMap f r
fromList :: Ord a => [a] -> Tree a
fromList = foldr insert Leaf
where
insert x Leaf = Node Leaf x Leaf
insert x t@(Node l v r)
| x < v = Node (insert x l) v r
| x > v = Node l v (insert x r)
| otherwise = t
main :: IO ()
main = do
let tree = fromList [50, 30, 70, 20, 40, 60]
print (toList tree)
print (sum tree, product (fromList [1, 2, 3, 4]), length tree)
print (maximum tree, elem 40 tree, null tree, null Leaf)
print (concatMap show tree)[20,30,40,50,60,70]
(270,24,6)
(70,True,False,True)
"203040506070"
We wrote five lines of foldMap and got sum, length, maximum, elem, null and more for free.
Traversable: effects over a structure
traverse f xs applies an effectful function f (one returning Maybe, Either, IO, a list...) to every element and rebuilds the structure inside the effect. If any step fails, the whole traversal fails:
import Text.Read (readMaybe)
import qualified Data.Map as Map
parseAge :: String -> Either String Int
parseAge s = case readMaybe s of
Just n | n >= 0 -> Right n
_ -> Left ("bad age: " ++ s)
main :: IO ()
main = do
print (traverse parseAge ["31", "8", "65"])
print (traverse parseAge ["31", "eight", "-1"])
print (traverse parseAge (Just "40"))
let form = Map.fromList [("alice", "29"), ("bob", "41")]
print (traverse parseAge form) -- the Map shape is kept
print (sequenceA [Just 1, Just 2], sequence [Right 'a', Left "no"])Right [31,8,65]
Left "bad age: eight"
Right (Just 40)
Right (fromList [("alice",29),("bob",41)])
(Just [1,2],Left "no")
sequenceA (or sequence for monads) is traverse id: it flips "a structure of effects" into "an effect producing a structure", for example [Maybe Int] into Maybe [Int].
traverse with IO, and for
With IO, traverse runs the actions in order and collects their results. for (from Data.Traversable) is traverse with the arguments flipped, which reads nicely with a lambda:
import Data.Traversable (for)
import Data.Foldable (for_, traverse_)
main :: IO ()
main = do
sizes <- traverse (\w -> do putStrLn ("measuring " ++ w); return (length w)) ["sun", "moon"]
print sizes
doubled <- for (Just 21) $ \n -> do
putStrLn "doubling"
return (n * 2)
print doubled
for_ [1, 2, 3 :: Int] print -- discard results
traverse_ putStrLn (Right "only Right values are visited" :: Either Int String)measuring sun
measuring moon
[3,4]
doubling
Just 42
1
2
3
only Right values are visited
Deriving the instances
Writing Functor, Foldable and Traversable instances by hand is mechanical, so GHC can derive all three (DeriveFunctor, DeriveFoldable and DeriveTraversable are part of GHC2021):
data Pair a = Pair a a
deriving (Show, Functor, Foldable, Traversable)
halve :: Int -> Maybe Int
halve n = if even n then Just (n `div` 2) else Nothing
main :: IO ()
main = do
print (fmap (+ 1) (Pair 1 2))
print (sum (Pair 10 20))
print (traverse halve (Pair 8 6))
print (traverse halve (Pair 8 7))Pair 2 3
30
Just (Pair 4 3)
Nothing
Tip: The hierarchy is: every
Traversableis both aFunctor(you can map) and aFoldable(you can summarise).traverseis the most powerful of the three, sincefmapandfoldMapcan both be defined from it.
Test yourself
What is sum (Just 7)?
Just 770- A type error
What is traverse (\x -> if x > 0 then Just x else Nothing) [3, 0, 5]?
Just [3,5][Just 3, Nothing, Just 5]NothingJust [3,0,5]
What does sequenceA [Just 1, Just 2, Just 3] return?
[1,2,3]Just [1,2,3][Just 1, Just 2, Just 3]Just 6