8

foldr and foldMap can be used to define each other as I understand. But how is that possible, as the latter uses monoids, while the former does not? Do we have any guarantees that the stuff the foldr works on can have a monoid?

Bakuriu
  • 98,325
  • 22
  • 197
  • 231
The Unfun Cat
  • 29,987
  • 31
  • 114
  • 156
  • 2
    You might want to read [Tom Ellis' "What is `foldr` made of?"](http://web.jaguarpaw.co.uk/~tom/blog/posts/2012-11-04-what-is-foldr-made-of.html) and [Brent Yorgey's response "`foldr` is made of monoids"](https://byorgey.wordpress.com/2012/11/05/foldr-is-made-of-monoids/). – Luis Casillas May 31 '16 at 21:06

1 Answers1

8
foldr :: (a -> b -> b) -> b -> [a] -> b

Note that a -> b -> b is a -> (b -> b). Functions b -> b form a monoid under composition.

Note how this resembles

foldMap :: (..omitted..) => (a -> m) -> f a -> m

The only difference is that foldMap doesn't use the "zero" argument of type b of fold and returns an m, which in terms of foldr would be b->b. Now just apply one to the other and you've recovered foldr from foldMap.

Benjamin Hodgson
  • 42,952
  • 15
  • 108
  • 157
n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243