on 294fdfd help sign in
elk/libraries/Set.elm
64 lines 1.8 kB history raw
2module Set (empty,singleton,insert,remove
3 ,member
4 ,foldl,foldr,map
5 ,union,intersect,diff
6 ,toList,fromList
7 ) where
9import Dict as Dict
10import List as List
12type Set t = Dict t ()
14-- Create an empty set.
15empty : Set t
16empty = Dict.empty
18-- Create a set with one value.
19singleton : t -> Set t
20singleton k = Dict.singleton k ()
22-- Insert a value into a set.
23insert : t -> Set t -> Set t
24insert k = Dict.insert k ()
26-- Remove a value from a set. If the value is not found, no changes are made.
27remove : t -> Set t -> Set t
28remove = Dict.remove
30-- Determine if a value is in a set.
31member : t -> Set t -> Bool
32member = Dict.member
34-- Get the union of two sets. Keep all values.
35union : Set t -> Set t -> Set t
36union = Dict.union
38-- Get the intersection of two sets. Keeps values that appear in both sets.
39intersect : Set t -> Set t -> Set t
40intersect = Dict.intersect
42-- Get the difference between the first set and the second. Keeps values that do not appear in the second set.
43diff : Set t -> Set t -> Set t
44diff = Dict.diff
46-- Convert a set into a list.
47toList : Set t -> [t]
48toList = Dict.keys
50-- Convert a list into a set, removing any duplicates.
51fromList : [t] -> Set t
52fromList xs = List.foldl (\k t -> Dict.insert k () t) empty xs
54-- Fold over the values in a set, in order from lowest to highest.
55foldl : (a -> b -> b) -> b -> Set a -> b
56foldl f b s = Dict.foldl (\k _ b -> f k b) b s
58-- Fold over the values in a set, in order from highest to lowest.
59foldr : (a -> b -> b) -> b -> Set a -> b
60foldr f b s = Dict.foldr (\k _ b -> f k b) b s
62-- Map a function onto a set, creating a new set with no duplicates.
63map : (a -> b) -> Set a -> Set b
64map f s = fromList (List.map f (toList s))