將可摺疊結構展平為 Monoid
foldMap 將可摺疊結構的每個元素對映到 Monoid ,然後將它們組合成單個值。
foldMap 和 foldr 可以相互定義,這意味著 Foldable 的例項只需要給出其中一個的定義。
class Foldable t where
foldMap::Monoid m => (a -> m) -> t a -> m
foldMap f = foldr (mappend . f) mempty
使用 Product monoid 的示例 :
product :: (Num n, Foldable t) => t n -> n
product = getProduct . foldMap Product