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

Commit 5754a85

Browse files
committed
toAscUnfoldable for keys and values
Rewrite `keys` and `values` to use the stack-safe `toAscUnfoldable` functions.
1 parent e424494 commit 5754a85

File tree

1 file changed

+35
-7
lines changed

1 file changed

+35
-7
lines changed

src/Data/Map.purs

+35-7
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@ module Data.Map
2222
, fromFoldableWith
2323
, toUnfoldable
2424
, toAscUnfoldable
25+
, toAscUnfoldableKeys
26+
, toAscUnfoldableValues
2527
, delete
2628
, pop
2729
, member
@@ -580,17 +582,43 @@ toAscUnfoldable m = unfoldr go (m : Nil) where
580582
Three left k1 v1 mid k2 v2 right ->
581583
go $ left : singleton k1 v1 : mid : singleton k2 v2 : right : tl
582584

585+
-- | Convert a map to an unfoldable structure of keys in ascending order.
586+
toAscUnfoldableKeys :: forall f k v. Unfoldable f => Map k v -> f k
587+
toAscUnfoldableKeys m = unfoldr go (m : Nil) where
588+
go Nil = Nothing
589+
go (hd : tl) = case hd of
590+
Leaf -> go tl
591+
Two Leaf k _ Leaf ->
592+
Just $ Tuple k tl
593+
Two Leaf k _ right ->
594+
Just $ Tuple k (right : tl)
595+
Two left k v right ->
596+
go $ left : singleton k v : right : tl
597+
Three left k1 v1 mid k2 v2 right ->
598+
go $ left : singleton k1 v1 : mid : singleton k2 v2 : right : tl
599+
583600
-- | Get a list of the keys contained in a map
584601
keys :: forall k v. Map k v -> List k
585-
keys Leaf = Nil
586-
keys (Two left k _ right) = keys left <> pure k <> keys right
587-
keys (Three left k1 _ mid k2 _ right) = keys left <> pure k1 <> keys mid <> pure k2 <> keys right
602+
keys = toAscUnfoldableKeys
603+
604+
-- | Convert a map to an unfoldable structure of values in ascending order of their corresponding keys.
605+
toAscUnfoldableValues :: forall f k. Unfoldable f => Map k ~> f
606+
toAscUnfoldableValues m = unfoldr go (m : Nil) where
607+
go Nil = Nothing
608+
go (hd : tl) = case hd of
609+
Leaf -> go tl
610+
Two Leaf _ v Leaf ->
611+
Just $ Tuple v tl
612+
Two Leaf _ v right ->
613+
Just $ Tuple v (right : tl)
614+
Two left k v right ->
615+
go $ left : singleton k v : right : tl
616+
Three left k1 v1 mid k2 v2 right ->
617+
go $ left : singleton k1 v1 : mid : singleton k2 v2 : right : tl
588618

589619
-- | Get a list of the values contained in a map
590-
values :: forall k v. Map k v -> List v
591-
values Leaf = Nil
592-
values (Two left _ v right) = values left <> pure v <> values right
593-
values (Three left _ v1 mid _ v2 right) = values left <> pure v1 <> values mid <> pure v2 <> values right
620+
values :: forall k. Map k ~> List
621+
values = toAscUnfoldableValues
594622

595623
-- | Compute the union of two maps, using the specified function
596624
-- | to combine values for duplicate keys.

0 commit comments

Comments
 (0)