@@ -44,6 +44,8 @@ module Data.HashMap.Strict.Refined
45 , Common.fromHashMap
45 , Common.fromHashMap
46 , Common.verifyHashMap
46 , Common.verifyHashMap
48+ , fromTraversableWith
47 , fromTraversableWithKey
49 , fromTraversableWithKey
48 , FromTraversableProof(..)
50 , FromTraversableProof(..)
49 -- * Insertion
51 -- * Insertion
@@ -145,14 +147,49 @@ fromSet :: forall s k a. KnownHashSet s k => (Key s k -> a) -> HashMap s k a
145fromSet f = HashMap $ HashMap.mapWithKey (\k _ -> f $ unsafeKey k)
147fromSet f = HashMap $ HashMap.mapWithKey (\k _ -> f $ unsafeKey k)
146 $ HashSet.toMap (reflect $ Proxy @s)
148 $ HashSet.toMap (reflect $ Proxy @s)
148−-- | Create a map from an arbitrary traversable of key-value pairs.
150+-- | Create a map from an arbitrary traversable of key-value pairs. If a key is
151+-- repeated, the retained value is the last one in traversal order. If you're
152+-- looking for @fromList@, this is the function you want.
154+ :: forall t k a. (Traversable t, Hashable k)
155+ => t (k, a) -> SomeHashMapWith (FromTraversableProof 'Hashed t k) k a
156+fromTraversable xs = SomeHashMapWith (HashMap m) $ FromTraversableProof proof
158+ (m, proof) = mapAccumL
159+ (\s (k, v) -> let !s' = HashMap.insert k v s in (s', unsafeKey k))
163+-- | Create a map from an arbitrary traversable of key-value pairs, with a
164+-- function for combining values for repeated keys. The function is called as if
165+-- by 'foldl1', but flipped:
168+-- 'fromTraversableWith' f [(k, x1), (k, x2), (k, x3)]
169+-- = 'singleton' k (f x3 (f x2 x1))
172+ :: forall t k a. (Traversable t, Hashable k)
175+ -> SomeHashMapWith (FromTraversableProof 'Hashed t k) k a
176+fromTraversableWith f xs
177+ = SomeHashMapWith (HashMap m) $ FromTraversableProof proof
179+ (m, proof) = mapAccumL
180+ (\s (k, v) -> let !s' = HashMap.insertWith f k v s in (s', unsafeKey k))
184+-- | Create a map from an arbitrary traversable of key-value pairs. Like
185+-- 'fromTraversableWith', but the combining function has access to the key.
149fromTraversableWithKey
186fromTraversableWithKey
150 :: forall t k a. (Traversable t, Hashable k)
187 :: forall t k a. (Traversable t, Hashable k)
151 => (k -> a -> a -> a)
188 => (k -> a -> a -> a)
152 -> t (k, a)
189 -> t (k, a)
153 -> SomeHashMapWith (FromTraversableProof 'Hashed t k) k a
190 -> SomeHashMapWith (FromTraversableProof 'Hashed t k) k a
154−fromTraversableWithKey f xs = SomeHashMapWith (HashMap m)
191+fromTraversableWithKey f xs
155− $ FromTraversableProof proof
192+ = SomeHashMapWith (HashMap m) $ FromTraversableProof proof
157 (m, proof) = mapAccumL
194 (m, proof) = mapAccumL
158 (\s (k, v)
195 (\s (k, v)