Permalink
Browse files

Added a mapWithKey function, and used it to define map.

  • Loading branch information...
felixll committed Nov 14, 2012
1 parent 4879e97 commit f94a031116afe46eb5578bcd04a9019167ca7b98
Showing with 16 additions and 8 deletions.
  1. +8 −4 Data/HashMap/Base.hs
  2. +8 −4 Data/HashMap/Strict.hs
View
@@ -701,15 +701,19 @@ unions = L.foldl' union empty
-- * Transformations
-- | /O(n)/ Transform this map by applying a function to every value.
-map :: (v1 -> v2) -> HashMap k v1 -> HashMap k v2
-map f = go
+mapWithKey :: (k -> v1 -> v2) -> HashMap k v1 -> HashMap k v2
+mapWithKey f = go
where
go Empty = Empty
- go (Leaf h (L k v)) = Leaf h $ L k (f v)
+ go (Leaf h (L k v)) = Leaf h $ L k (f k v)
go (BitmapIndexed b ary) = BitmapIndexed b $ A.map' go ary
go (Full ary) = Full $ A.map' go ary
go (Collision h ary) = Collision h $
- A.map' (\ (L k v) -> L k (f v)) ary
+ A.map' (\ (L k v) -> L k (f k v)) ary
+{-# INLINE mapWithKey #-}
+
+map :: (v1 -> v2) -> HashMap k v1 -> HashMap k v2
+map f = mapWithKey (const f)
{-# INLINE map #-}
-- TODO: We should be able to use mutation to create the new
View
@@ -326,15 +326,19 @@ unionWith f = go 0
-- * Transformations
-- | /O(n)/ Transform this map by applying a function to every value.
-map :: (v1 -> v2) -> HashMap k v1 -> HashMap k v2
-map f = go
+mapWithKey :: (k -> v1 -> v2) -> HashMap k v1 -> HashMap k v2
+mapWithKey f = go
where
go Empty = Empty
- go (Leaf h (L k v)) = let !v' = f v in Leaf h $ L k v'
+ go (Leaf h (L k v)) = let !v' = f k v in Leaf h $ L k v'
go (BitmapIndexed b ary) = BitmapIndexed b $ A.map' go ary
go (Full ary) = Full $ A.map' go ary
go (Collision h ary) =
- Collision h $ A.map' (\ (L k v) -> let !v' = f v in L k v') ary
+ Collision h $ A.map' (\ (L k v) -> let !v' = f k v in L k v') ary
+{-# INLINE mapWithKey #-}
+
+map :: (v1 -> v2) -> HashMap k v1 -> HashMap k v2
+map f = mapWithKey (const f)
{-# INLINE map #-}
-- TODO: Should we add a strict traverseWithKey?

0 comments on commit f94a031

Please sign in to comment.