Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Added `foldMapWithKey`.

  • Loading branch information...
commit 40187f32a43689ff02ca2b97465aa4fcd9f9d150 1 parent 14eb7c2
@ekmett authored
View
15 Data/IntMap/Base.hs
@@ -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
2  Data/IntMap/Lazy.hs
@@ -133,6 +133,8 @@ module Data.IntMap.Lazy (
, IM.foldl
, foldrWithKey
, foldlWithKey
+ , foldMapWithKey
+
-- ** Strict folds
, foldr'
, foldl'
View
2  Data/IntMap/Strict.hs
@@ -139,6 +139,8 @@ module Data.IntMap.Strict (
, foldl
, foldrWithKey
, foldlWithKey
+ , foldMapWithKey
+
-- ** Strict folds
, foldr'
, foldl'
View
14 Data/Map/Base.hs
@@ -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
2  Data/Map/Lazy.hs
@@ -129,6 +129,8 @@ module Data.Map.Lazy (
, M.foldl
, foldrWithKey
, foldlWithKey
+ , foldMapWithKey
+
-- ** Strict folds
, foldr'
, foldl'
View
2  Data/Map/Strict.hs
@@ -136,6 +136,8 @@ module Data.Map.Strict
, foldl
, foldrWithKey
, foldlWithKey
+ , foldMapWithKey
+
-- ** Strict folds
, foldr'
, foldl'
Please sign in to comment.
Something went wrong with that request. Please try again.