Permalink
Browse files

Added `foldMapWithKey`.

  • Loading branch information...
1 parent 14eb7c2 commit 40187f32a43689ff02ca2b97465aa4fcd9f9d150 @ekmett committed Dec 25, 2012
Showing with 37 additions and 0 deletions.
  1. +15 −0 Data/IntMap/Base.hs
  2. +2 −0 Data/IntMap/Lazy.hs
  3. +2 −0 Data/IntMap/Strict.hs
  4. +14 −0 Data/Map/Base.hs
  5. +2 −0 Data/Map/Lazy.hs
  6. +2 −0 Data/Map/Strict.hs
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'

0 comments on commit 40187f3

Please sign in to comment.