A set of unique values. Similar to elm/core Set but allows arbitrary data
given a function for converting to comparable can be provided.
Insert, remove, and query operations all take O(log n) time.
When writing a function for conversion from the type you want to use within a set to comparable it's very important to make sure every distinct member of the type produces different value in the set of comparables.
Take for instance those two examples:
We can use store Bool in Set (No matter how unpractical it might seem)
boolToInt : Bool -> Int
boolToInt bool =
case bool of
False -> 0
True -> 1
empty boolToInt
|> insert True
|> member True
--> Trueor Maybe String.
comparableKey : Maybe String -> (Int, String)
comparableKey maybe =
case maybe of
Nothing -> (0, "")
Just str -> (1, str)
empty comparableKey
|> insert (Just "foo")
|> member (Just "foo")
--> TrueNote that we give Int code to either constructor and in case of Nothing we default to "" (empty string).
There is still a difference between Nothing and Just "" (Int value in the pair is different).
In fact, you can "hardcode" any value as the second member of the pair
in case of Nothing but empty string seems like a reasonable option for this case.
Generally, this is how I would implement toComparable function for most of your custom data types.
Have a look at the longest constructor,
Define tuple where the first key is int (number of the constructor)
and other are types within the constructor and you're good to go.
Create an empty set.
** Note that it's important to make sure every key is turned to different comparable. Otherwise keys would conflict and overwritede each other.**
Create a set with one value.
** Note that it's important to make sure every key is turned to different comparable. Otherwise keys would conflict and overwritede each other.**
Remove a value from a set. If the value is not found, no changes are made.
Get the union of two sets. Keep all values.
Get the intersection of two sets. Keeps values that appear in both sets.
Get the difference between the first set and the second. Keeps values that do not appear in the second set.
Convert a list into a set, removing any duplicates.
Fold over the values in a set, in order from lowest to highest.
Fold over the values in a set, in order from highest to lowest.
Map a function onto a set, creating a new set with no duplicates.
Only keep elements that pass the given test.
Create two new sets. The first contains all the elements that passed the given test, and the second contains all the elements that did not.
Represents a set of unique values.