• Home
  • Textbooks
  • Programming in Haskell
  • Foldables and friends

Programming in Haskell

Graham Hutton

Chapter 14

Foldables and friends - all with Video Answers

Educators


Chapter Questions

Problem 1

Complete the following instance declaration from Data.Monoid to make a pair type into a monoid provided the two component types are monoids:
instance (Monoid a, Monoid b) => Monoid (a,b)
where
— mempty :: (a,b)
mempty = …
— mappend :: (a,b) -> (a,b) -> (a,b)
(x1,y1) ‘mappend‘ (x2,y2) = …

Check back soon!

Problem 2

In a similar manner, show how a function type $a \rightarrow b$ can be made into a monoid provided that the result type $\mathrm{b}$ is a monoid.

Check back soon!

Problem 3

Show how the Maybe type can be made foldable and traversable, by giving explicit definitions for fold, foldmap, foldr, foldl and traverse.

Check back soon!

Problem 4

In a similar manner, show how the following type of binary trees with data in their nodes can be made into a foldable and traversable type:
data Tree a = Leaf | Node (Tree a) a (Tree a)
deriving Show

Check back soon!

Problem 5

Using foldMap, define a generic version of the higherorder function filter on lists that can be used with any foldable type:
filterF :: Foldable t => (a -> Bool) -> t a ->
[a]
Solutions to exercises 1 and 2 are given in appendix A.

Check back soon!