Set
The Set module provides functions for working with immutable collections of unique values. Sets are useful when you need to store distinct elements and perform set operations like union and intersection.
Creating Sets
Set.empty
Set a
Returns an empty set.
s = Set.empty
println (Set.is-empty? s)
# => true
Set.from-list
List a -> Set a
Creates a set from a list, removing duplicates.
s = Set.from-list [1, 2, 2, 3, 3, 3]
println (Set.size s)
# => 3
Modifying Sets
Set.insert
Set a -> a -> Set a
Returns a new set with the element added. If the element already exists, returns the same set.
s1 = Set.from-list [1, 2]
s2 = Set.insert s1 3
println (Set.to-list s2)
# => [1, 2, 3]
Set.delete
Set a -> a -> Set a
Returns a new set with the element removed.
s1 = Set.from-list [1, 2, 3]
s2 = Set.delete s1 2
println (Set.to-list s2)
# => [1, 3]
Set Operations
Set.union
Set a -> Set a -> Set a
Returns a new set containing all elements from both sets.
s1 = Set.from-list [1, 2, 3]
s2 = Set.from-list [3, 4, 5]
s3 = Set.union s1 s2
println (Set.to-list s3)
# => [1, 2, 3, 4, 5]
Set.intersection
Set a -> Set a -> Set a
Returns a new set containing only elements present in both sets.
s1 = Set.from-list [1, 2, 3]
s2 = Set.from-list [2, 3, 4]
s3 = Set.intersection s1 s2
println (Set.to-list s3)
# => [2, 3]
Set.difference
Set a -> Set a -> Set a
Returns a new set containing elements in the first set but not in the second.
s1 = Set.from-list [1, 2, 3]
s2 = Set.from-list [2, 3, 4]
s3 = Set.difference s1 s2
println (Set.to-list s3)
# => [1]
Querying
Set.contains?
Set a -> a -> Bool
Returns
true if the set contains the element.
s = Set.from-list [1, 2, 3]
println (Set.contains? s 2) # => true
println (Set.contains? s 5) # => false
Set.is-empty?
Set a -> Bool
Returns
true if the set has no elements.
println (Set.is-empty? Set.empty) # => true
println (Set.is-empty? (Set.from-list [1])) # => false
Set.size
Set a -> Int
Returns the number of elements in the set.
s = Set.from-list [1, 2, 3]
println (Set.size s)
# => 3
Conversion
Set.to-list
Set a -> List a
Converts a set to a list.
s = Set.from-list [3, 1, 2]
println (Set.to-list s)
# => [1, 2, 3]