Set[T] stores unique values and requires T: Hashable for membership and
mutation.
mut tags: Set[string] = Set.new()
tags.add("stable")
tags.add("documented")Set.new[T](capacity) creates an empty set. Set.copy(other, capacity)
creates independent storage. Capacity is only an allocation hint.
Adding an existing value leaves one member. remove returns whether a value
was present.
Membership
if tags.contains("stable") {
publish()
}contains_all tests a subset. is_subset_of, is_superset_of, and
is_disjoint express set relationships.
| Relationship | Question |
|---|---|
left.contains_all(right) |
Does left contain every member of right? |
left.is_subset_of(right) |
Is every member of left in right? |
left.is_superset_of(right) |
Is every member of right in left? |
left.is_disjoint(right) |
Do the sets share no members? |
Algebra
All primary algebra operations return new sets:
either := left.union(right)
both := left.intersect(right)
only_left := left.subtract(right)
one_side := left.symmetric_difference(right)plus, plus_all, and minus are immutable-style convenience operations.
add, remove, and clear mutate.
union contains either side; intersect contains both sides; subtract
removes all right-hand members; symmetric_difference contains members found
on exactly one side. Each allocates a result and leaves both operands intact.
Transformation
Sets provide map, filter, flat_map, any, all, none, count, and
find. Mapping can reduce cardinality when several source values map to an
equal result.
normalized := tags.map(tag => tag.trim().to_lower_ascii())
public_tags := normalized.filter(tag => !tag.starts_with("_"))find returns an arbitrary matching member under hash iteration order.
any, all, and none short-circuit. Do not use the chosen element or visit
order as a stable tie-breaker.
to_list() does not promise a stable hash iteration order. Sort afterward when
deterministic presentation matters.
Sorted sets
SortedSet[T] adds ordered first/last, range views, and nearest-value queries:
head_set,tail_set, andsub_set;floorandceiling;- ordered variants of the main algebra operations.
The installed ordered surface is less deeply runtime-backed than Set[T].
Treat it as provisional and retain an end-to-end test when using it. For stable
ordered output today, converting a hash set to a list and sorting it is the
better-supported path.
Hash stability
Set membership depends on equals and hash_code. A value’s participating
fields must not change while stored. Derived hashing is appropriate for
immutable value types whose fields already satisfy the same contract.
Set equality and hashing are based on membership, not visit order. Adding the same value twice does not change equality, size, or the set’s logical hash.