Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Already on GitHub? Sign in to your account

Added `foldMapWithKey`. #24

Merged
merged 1 commit into from Jul 2, 2013
Jump to file or symbol
Failed to load files and symbols.
+37 −0
Split
View
@@ -123,6 +123,8 @@ module Data.IntMap.Base (
, foldl
, foldrWithKey
, foldlWithKey
+ , foldMapWithKey
+
-- ** Strict folds
, foldr'
, foldl'
@@ -1670,6 +1672,19 @@ foldlWithKey' f z = \t -> -- Use lambda t to be inlinable with two argument
go z' (Bin _ _ l r) = go (go z' l) r
{-# INLINE foldlWithKey' #-}
+-- | /O(n)/. Fold the keys and values in the map using the given monoid, such that
+--
+-- @'foldMapWithKey' f = 'Prelude.fold' . 'mapWithKey' f@
+--
+-- This can be an asymptotically faster than 'foldrWithKey' or 'foldlWithKey' for some monoids.
+foldMapWithKey :: Monoid m => (Key -> a -> m) -> IntMap a -> m
+foldMapWithKey f = go
+ where
+ go Nil = mempty
+ go (Tip kx x) = f kx x
+ go (Bin _ _ l r) = go l `mappend` go r
+{-# INLINE foldMapWithKey #-}
+
{--------------------------------------------------------------------
List variations
--------------------------------------------------------------------}
View
@@ -133,6 +133,8 @@ module Data.IntMap.Lazy (
, IM.foldl
, foldrWithKey
, foldlWithKey
+ , foldMapWithKey
+
-- ** Strict folds
, foldr'
, foldl'
View
@@ -139,6 +139,8 @@ module Data.IntMap.Strict (
, foldl
, foldrWithKey
, foldlWithKey
+ , foldMapWithKey
+
-- ** Strict folds
, foldr'
, foldl'
View
@@ -169,6 +169,8 @@ module Data.Map.Base (
, foldl
, foldrWithKey
, foldlWithKey
+ , foldMapWithKey
+
-- ** Strict folds
, foldr'
, foldl'
@@ -1873,6 +1875,18 @@ foldlWithKey' f z = go z
go z' (Bin _ kx x l r) = go (f (go z' l) kx x) r
{-# INLINE foldlWithKey' #-}
+-- | /O(n)/. Fold the keys and values in the map using the given monoid, such that
+--
+-- @'foldMapWithKey' f = 'Prelude.fold' . 'mapWithKey' f@
+--
+-- This can be an asymptotically faster than 'foldrWithKey' or 'foldlWithKey' for some monoids.
+foldMapWithKey :: Monoid m => (k -> a -> m) -> Map k a -> m
+foldMapWithKey f = go
+ where
+ go Tip = mempty
+ go (Bin _ k v l r) = go l `mappend` f k v `mappend` go r
+{-# INLINE foldMapWithKey #-}
+
{--------------------------------------------------------------------
List variations
--------------------------------------------------------------------}
View
@@ -129,6 +129,8 @@ module Data.Map.Lazy (
, M.foldl
, foldrWithKey
, foldlWithKey
+ , foldMapWithKey
+
-- ** Strict folds
, foldr'
, foldl'
View
@@ -136,6 +136,8 @@ module Data.Map.Strict
, foldl
, foldrWithKey
, foldlWithKey
+ , foldMapWithKey
+
-- ** Strict folds
, foldr'
, foldl'