mirror of
https://github.com/roc-lang/roc.git
synced 2025-08-03 19:58:18 +00:00
make Set/Dict mostly work
This commit is contained in:
parent
4d33e32078
commit
79f8ae4e69
6 changed files with 107 additions and 57 deletions
|
@ -2,6 +2,7 @@ interface Dict
|
|||
exposes [
|
||||
Dict,
|
||||
empty,
|
||||
withCapacity,
|
||||
single,
|
||||
get,
|
||||
walk,
|
||||
|
@ -18,6 +19,7 @@ interface Dict
|
|||
imports [
|
||||
Bool.{ Bool },
|
||||
Result.{ Result },
|
||||
List,
|
||||
]
|
||||
|
||||
## A [dictionary](https://en.wikipedia.org/wiki/Associative_array) that lets you can associate keys with values.
|
||||
|
@ -74,6 +76,9 @@ Dict k v := List [Pair k v]
|
|||
empty : Dict k v
|
||||
empty = @Dict []
|
||||
|
||||
withCapacity : Nat -> Dict k v
|
||||
withCapacity = \n -> @Dict (List.withCapacity n)
|
||||
|
||||
get : Dict k v, k -> Result v [KeyNotFound]*
|
||||
get = \@Dict list, needle ->
|
||||
when List.find list (\Pair key _ -> key == needle) is
|
||||
|
@ -132,6 +137,7 @@ single : k, v -> Dict k v
|
|||
single = \key, value ->
|
||||
@Dict [Pair key value]
|
||||
|
||||
|
||||
## Returns a [List] of the dictionary's keys.
|
||||
keys : Dict k v -> List k
|
||||
keys = \@Dict list ->
|
||||
|
@ -149,7 +155,7 @@ insertAll = \xs, @Dict ys ->
|
|||
|
||||
# intersection : Dict k v, Dict k v -> Dict k v
|
||||
keepShared : Dict k v, Dict k v -> Dict k v
|
||||
keepShared = \Dict xs, ys ->
|
||||
keepShared = \@Dict xs, ys ->
|
||||
List.keepIf xs (\Pair k _ -> Dict.contains ys k)
|
||||
|> @Dict
|
||||
|
||||
|
|
|
@ -30,7 +30,7 @@ empty = fromDict Dict.empty
|
|||
|
||||
single : k -> Set k
|
||||
single = \key ->
|
||||
Dict.single key {}
|
||||
@Set (Dict.single key {})
|
||||
|
||||
## Make sure never to insert a *NaN* to a [Set]! Because *NaN* is defined to be
|
||||
## unequal to *NaN*, adding a *NaN* results in an entry that can never be
|
||||
|
@ -48,7 +48,7 @@ len = \@Set dict ->
|
|||
## Drops the given element from the set.
|
||||
remove : Set k, k -> Set k
|
||||
remove = \@Set dict, key ->
|
||||
@Set (Dict.remove key dict)
|
||||
@Set (Dict.remove dict key)
|
||||
|
||||
contains : Set k, k -> Bool
|
||||
contains = \set, key ->
|
||||
|
@ -62,7 +62,7 @@ toList = \@Set dict ->
|
|||
|
||||
fromList : List k -> Set k
|
||||
fromList = \list ->
|
||||
initial = List.withCapacity (List.len list)
|
||||
initial = @Set (Dict.withCapacity (List.len list))
|
||||
|
||||
List.walk list initial \set, key -> Set.insert set key
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue