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

Commit ba06add

Browse files
committed
More efficient toUnfoldable without the Ord constraint
Keep a List of Maps as the unfold state, instead of a single Map. Unioning Maps was linear time (making the entire function quadratic?). Prepending to a List is constant time and doesn't require an `Ord k` instance.
1 parent 079c2fb commit ba06add

File tree

1 file changed

+9
-7
lines changed

1 file changed

+9
-7
lines changed

src/Data/Map.purs

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -372,13 +372,15 @@ toList (Two left k v right) = toList left <> Tuple k v : toList right
372372
toList (Three left k1 v1 mid k2 v2 right) = toList left <> Tuple k1 v1 : toList mid <> Tuple k2 v2 : toList right
373373

374374
-- | Convert a map to an unfoldable structure of key/value pairs
375-
toUnfoldable :: forall f k v. (Ord k, Unfoldable f) => Map k v -> f (Tuple k v)
376-
toUnfoldable = unfoldr go
377-
where
378-
go :: Map k v -> Maybe (Tuple (Tuple k v) (Map k v))
379-
go Leaf = Nothing
380-
go (Two left k v right) = Just $ Tuple (Tuple k v) (left <> right)
381-
go (Three left k1 v1 mid k2 v2 right) = Just $ Tuple (Tuple k1 v1) (insert k2 v2 (left <> mid <> right))
375+
toUnfoldable :: forall f k v. Unfoldable f => Map k v -> f (Tuple k v)
376+
toUnfoldable m = unfoldr go (m : Nil) where
377+
go Nil = Nothing
378+
go (hd : tl) = case hd of
379+
Leaf -> go tl
380+
Two left k v right ->
381+
Just $ Tuple (Tuple k v) (left : right : tl)
382+
Three left k1 v1 mid k2 v2 right ->
383+
Just $ Tuple (Tuple k1 v1) ((singleton k2 v2) : left : mid : right : tl)
382384

383385
-- | Get a list of the keys contained in a map
384386
keys :: forall k v. Map k v -> List k

0 commit comments

Comments
 (0)