Skip to content

Commit

Permalink
[#17] Add foldMapA and foldMapM functions
Browse files Browse the repository at this point in the history
  • Loading branch information
vrom911 committed Jul 20, 2018
1 parent 0e110e8 commit b902829
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Expand Up @@ -29,6 +29,8 @@ Change log
* [#18](https://github.com/kowainik/universum/issues/18):
Add `LazyStrict` type class for conversions.
* `map` is not `fmap` anymore. Reexport `map` from `Data.List`
* [#17](https://github.com/kowainik/universum/issues/17):
Add `foldMapA` and `foldMapM` functions.


`universum` uses [PVP Versioning][1].
Expand Down
20 changes: 18 additions & 2 deletions src/Universum/Foldable/Fold.hs
Expand Up @@ -11,6 +11,8 @@

module Universum.Foldable.Fold
( flipfoldl'
, foldMapA
, foldMapM
, safeHead
, sum
, product
Expand All @@ -26,13 +28,15 @@ module Universum.Foldable.Fold

import GHC.TypeLits (ErrorMessage (..), TypeError)

import Universum.Applicative (pure)
import Universum.Base (Constraint, Eq, IO, Num (..), Type)
import Universum.Applicative (Applicative (..), pure)
import Universum.Base (Constraint, Eq, IO, Num (..), Type, ($!))
import Universum.Bool (Bool (..))
import Universum.Container.Reexport (HashSet, Set)
import Universum.Foldable.Reexport (Foldable (..))
import Universum.Function (flip, (.))
import Universum.Functor ((<$>))
import Universum.Monad.Reexport (Maybe (..), Monad (..))
import Universum.Monoid (Monoid (..))

import qualified Data.Foldable as F

Expand All @@ -59,6 +63,18 @@ flipfoldl' :: Foldable f => (a -> b -> b) -> b -> f a -> b
flipfoldl' f = foldl' (flip f)
{-# INLINE flipfoldl' #-}

foldMapA :: (Monoid b, Applicative m, Foldable f) => (a -> m b) -> f a -> m b
foldMapA f = foldr step (pure mempty)
where
step a mb = mappend <$> f a <*> mb
{-# INLINE foldMapA #-}

foldMapM :: (Monoid b, Monad m, Foldable f) => (a -> m b) -> f a -> m b
foldMapM f xs = foldr step return xs mempty
where
step x r z = f x >>= \y -> r $! z `mappend` y
{-# INLINE foldMapM #-}

{- | Stricter version of 'F.sum'.
>>> sum [1..10]
Expand Down

0 comments on commit b902829

Please sign in to comment.