Permalink
Browse files

Added two function to map over ranges.

  • Loading branch information...
sebastiaanvisser committed Nov 13, 2011
1 parent 7710d4e commit 0d6be02b9e1313ba11d774f972e524d0eed5f4f5
Showing with 34 additions and 1 deletion.
  1. +33 −0 Data/Map/Strict.hs
  2. +1 −1 strict-containers.cabal
View
@@ -118,6 +118,8 @@ module Data.Map.Strict (
-- ** Map
, map
, mapWithKey
+ , mapMaybeRange
+ , mapMaybeRangeWithKey
, mapAccum
, mapAccumWithKey
, mapAccumRWithKey
@@ -1537,6 +1539,37 @@ mapWithKey f (Bin sx kx x l r) = Bin sx kx (f kx x) (mapWithKey f l) (mapWithKey
{-# INLINABLE mapWithKey #-}
#endif
+-- | /O(n)/. Map a function over a range of values in the map.
+--
+-- > mapMaybeRange (++ "x") (fromList [(5,"a"), (3,"b")]) == fromList [(3, "bx"), (5, "ax")]
+
+mapMaybeRange :: Ord k => (a -> Maybe a) -> (Maybe k, Maybe k) -> Map k a -> Map k a
+mapMaybeRange f rng = mapMaybeRangeWithKey (\_ x -> f x) rng
+#if __GLASGOW_HASKELL__ >= 700
+{-# INLINABLE mapMaybeRange #-}
+#endif
+
+-- | /O(n)/. Map a function over a range of values in the map.
+--
+-- > let f key x = (show key) ++ ":" ++ x
+-- > mapMaybeRangeWithKey f (fromList [(5,"a"), (3,"b")]) == fromList [(3, "3:b"), (5, "5:a")]
+
+mapMaybeRangeWithKey :: Ord k => (k -> a -> Maybe a) -> (Maybe k, Maybe k) -> Map k a -> Map k a
+mapMaybeRangeWithKey _ _ Tip = Tip
+mapMaybeRangeWithKey f rng@(from, to) (Bin sx kx x l r) =
+ let cf = maybe True (kx >=) from
+ ct = maybe True (kx <=) to
+ left = if cf then mapMaybeRangeWithKey f rng l else l
+ right = if ct then mapMaybeRangeWithKey f rng r else r
+ newx = if cf && ct then f kx x else Just x
+ in case newx of
+ Just y -> join kx y left right
+ Nothing -> merge left right
+
+#if __GLASGOW_HASKELL__ >= 700
+{-# INLINABLE mapMaybeRangeWithKey #-}
+#endif
+
-- | /O(n)/. The function 'mapAccum' threads an accumulating
-- argument through the map in ascending order of keys.
--
View
@@ -1,5 +1,5 @@
name: strict-containers
-version: 0.4.2.0
+version: 0.4.2.1
license: BSD3
license-file: LICENSE
maintainer: code@silkapp.com

0 comments on commit 0d6be02

Please sign in to comment.