Skip to content
This repository was archived by the owner on Oct 4, 2020. It is now read-only.

Commit 1be88e0

Browse files
committed
Added fromListWith
1 parent 80f185b commit 1be88e0

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

src/Data/Map.purs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ module Data.Map
1515
lookup,
1616
toList,
1717
fromList,
18+
fromListWith,
1819
delete,
1920
member,
2021
alter,
@@ -228,6 +229,11 @@ toList (Three left k1 v1 mid k2 v2 right) = toList left P.++ [Tuple k1 v1] P.++
228229
fromList :: forall k v. (P.Ord k) => [Tuple k v] -> Map k v
229230
fromList = foldl (\m (Tuple k v) -> insert k v m) empty
230231

232+
fromListWith :: forall k v. (P.Ord k) => (v -> v -> v) -> [Tuple k v] -> Map k v
233+
fromListWith f = foldl (\m (Tuple k v) -> alter (combine v) k m) empty where
234+
combine v (Just v') = Just P.$ f v v'
235+
combine v Nothing = Just v
236+
231237
keys :: forall k v. Map k v -> [k]
232238
keys Leaf = []
233239
keys (Two left k _ right) = keys left P.++ [k] P.++ keys right

src/Data/StrMap.purs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ module Data.StrMap
1414
lookup,
1515
toList,
1616
fromList,
17+
fromListWith,
1718
delete,
1819
member,
1920
alter,
@@ -255,6 +256,21 @@ fromList l = pureST (do
255256
for_ l (\(Tuple k v) -> SM.poke s k v)
256257
P.return s)
257258

259+
foreign import _lookupST
260+
"""
261+
function _lookupST(no, yes, k, m) {
262+
return function() {
263+
return k in m ? yes(m[k]) : no;
264+
}
265+
}
266+
""" :: forall a h r z. Fn4 z (a -> z) String (SM.STStrMap h a) (Eff (st :: ST.ST h | r) z)
267+
268+
fromListWith :: forall a. (a -> a -> a) -> [Tuple String a] -> StrMap a
269+
fromListWith f l = pureST (do
270+
s <- SM.new
271+
for_ l (\(Tuple k v) -> runFn4 _lookupST v (f v) k s P.>>= SM.poke s k)
272+
P.return s)
273+
258274
foreign import _collect
259275
"""
260276
function _collect(f) {

0 commit comments

Comments
 (0)