make Set/Dict mostly work

This commit is contained in:
Folkert 2022-07-13 11:15:57 +02:00
parent 4d33e32078
commit 79f8ae4e69
No known key found for this signature in database
GPG key ID: 1F17F6FFD112B97C
6 changed files with 107 additions and 57 deletions

View file

@ -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

View file

@ -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