foldMap
maps each element of the Foldable structure to a Monoid
, and then combines them into a single value.
foldMap
and foldr
can be defined in terms of one another, which means that instances of Foldable
need only give a definition for one of them.
class Foldable t where
foldMap :: Monoid m => (a -> m) -> t a -> m
foldMap f = foldr (mappend . f) mempty
Example usage with the Product
monoid:
product :: (Num n, Foldable t) => t n -> n
product = getProduct . foldMap Product