Skip to content

Commit da4f3c8

Browse files
committed
Add size-tracking 'fromList, fromListWith' functions
1 parent eb4be61 commit da4f3c8

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

Data/HashMap/Base.hs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1534,12 +1534,38 @@ fromList :: (Eq k, Hashable k) => [(k, v)] -> HashMap k v
15341534
fromList = L.foldl' (\ m (k, v) -> unsafeInsert k v m) empty
15351535
{-# INLINABLE fromList #-}
15361536

1537+
-- | /O(n)/ Construct a map with the supplied mappings. If the list
1538+
-- contains duplicate mappings, the later mappings take precedence.
1539+
-- Returns a tuple with the size of the created hashmap and the hashmap
1540+
-- itself.
1541+
fromListInternal :: (Eq k, Hashable k) => [(k, v)] -> (Int, HashMap k v)
1542+
fromListInternal = L.foldl' (\ (sz, m) (k, v) ->
1543+
let (s, m') = unsafeInsertInternal k v m
1544+
in (sz + s, m'))
1545+
(0, empty)
1546+
{-# INLINABLE fromListInternal #-}
1547+
15371548
-- | /O(n*log n)/ Construct a map from a list of elements. Uses
15381549
-- the provided function to merge duplicate entries.
15391550
fromListWith :: (Eq k, Hashable k) => (v -> v -> v) -> [(k, v)] -> HashMap k v
15401551
fromListWith f = L.foldl' (\ m (k, v) -> unsafeInsertWith f k v m) empty
15411552
{-# INLINE fromListWith #-}
15421553

1554+
-- | /O(n*log n)/ Construct a map from a list of elements. Uses
1555+
-- the provided function to merge duplicate entries.
1556+
-- Returns a tuple with the size of the created hashmap and the hashmap itself.
1557+
fromListWithInternal
1558+
:: (Eq k, Hashable k)
1559+
=> (v -> v -> v)
1560+
-> [(k, v)]
1561+
-> (Int, HashMap k v)
1562+
fromListWithInternal f =
1563+
L.foldl' (\ (sz, m) (k, v) ->
1564+
let (s, m') = unsafeInsertWithInternal f k v m
1565+
in (sz + s, m'))
1566+
(0, empty)
1567+
{-# INLINE fromListWithInternal #-}
1568+
15431569
------------------------------------------------------------------------
15441570
-- Array operations
15451571

0 commit comments

Comments
 (0)