Skip to content

Sets

Store unique hashable values, test membership, and compose set algebra.

Set[T] is a hash set: an unordered collection in which each value appears at most once. Membership, insertion, and removal are average constant time.

fn main() void {
    mut tags: Set[string] = Set.new()
    tags.put("stable")
    tags.put("documented")
    tags.put("stable")            // already present — no second member

    println("${tags.len()} tags")
    println("stable? ${tags.contains("stable")}")
}

As with Map, the binding must be mut (because put takes &mut self), and the annotation fixes the element type for Set.new(), or the first put does: Set[T] is Map[T, void], and a put of a key alone is the set’s.

Construction

Set.new(capacity) allocates an empty set; the capacity is only an allocation hint. Set.copy(other, capacity) gives independent storage.

fn main() void {
    // Element type from the annotation.
    mut a: Set[int] = Set.new()
    a.put(1)

    // Element type from an explicit type argument, with a capacity hint.
    mut b := Set.new[int](128)
    b.put(2)

    // Independent table — adding to `c` leaves `a` alone.
    mut c := Set.copy(a)
    c.put(3)

    println("${a.len()} ${b.len()} ${c.len()}")
}

List.to_set() is the shortest way to build a set from known values, and doubles as a deduplicator:

fn main() void {
    words := ["fig", "date", "fig", "kiwi", "date"]

    unique := words.to_set()
    println("${words.len()} values, ${unique.len()} distinct")

    // Sorted, so the output is deterministic.
    for word in unique.items().sorted() {
        println(word)
    }
}

Set[T] is a handle to heap storage. Passing it or binding it to another name shares the same table; Set.copy is what isolates later mutation.

fn marked_count(target &Set[string]) int {
    mut local := Set.copy(target)
    local.put("marker")
    return local.len()
}

fn main() void {
    mut tags: Set[string] = Set.new()
    tags.put("stable")
    copied := marked_count(tags)
    println("copy has ${copied}")
    println("original still has ${tags.len()}")
}

Membership and mutation

put answers whether the value was new; discard answers whether it was present.

fn main() void {
    mut roles: Set[string] = Set.new()
    roles.put("admin")
    roles.put("auditor")

    println("${roles.contains("admin")}")
    println("${roles.is_empty()} ${roles.is_not_empty()}")
    println("${roles.len()} ${roles.len()}")   // len() is an alias for size()

    if roles.discard("auditor") {
        println("auditor revoked")
    }
    if !roles.discard("auditor") {
        println("already gone")
    }

    roles.clear()
    println("${roles.len()}")
}

remove is the map spelling and answers V?, which on a set is void? — present or absent is the whole of what it can say, and that shape says it in a way nothing can read. discard is the same removal with a bool.

put answers true the first time a value goes in and false when it was already there, in which case the set is left as it was, as Rust’s HashSet::insert does. One probe of the table, where contains and then a second insertion are two. A put whose answer nothing reads costs what an insertion that answers nothing would: the answer is a register the caller drops. (add and insert are retired names; a call by either is ATOLL2114, which names put.)

fn main() void {
    mut seen: Set[string] = Set.new()
    for word in ["fig", "date", "fig", "kiwi", "date"] {
        if seen.put(word.clone()) {
            println("first ${word}")
        }
    }
    println("${seen.len()} distinct")
}

A set’s put takes the key alone, and a map’s takes the key and the value: the two are one name chosen by the value type (where V == void, see Traits), so a set handed a value is refused:

fn main() void {
    mut roles: Set[string] = Set.new()
    roles.put("admin", ())
}

Relationships

Four predicates answer containment questions without allocating.

fn main() void {
    mut granted: Set[string] = Set.new()
    granted.put("read")
    granted.put("write")
    granted.put("admin")

    mut required: Set[string] = Set.new()
    required.put("read")
    required.put("write")

    println("${required.is_subset_of(granted)}")   // every required is granted
}
Call Question
left.contains_all(right) Does left hold 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 two share no members?

Each is decided by keys alone, which is what lets a Set[T] and the Map[T, void] it is spelled as answer the same question.

fn main() int {
    mut a: Set[int]
    a.put(1)
    a.put(2)

    mut b: Set[int]
    b.put(2)

    mut c: Set[int]
    c.put(9)

    if a.is_superset_of(b) && a.contains_all(b) && a.is_disjoint(c) {
        return 42
    }
    return 7
}

Algebra

The four algebra operations each allocate a new set and leave both operands untouched.

fn main() void {
    mut left: Set[int] = Set.new()
    left.put(1)
    left.put(2)
    left.put(3)

    mut right: Set[int] = Set.new()
    right.put(3)
    right.put(4)

    either := left.union(right)                     // 1 2 3 4
    both := left.intersection(right)                // 3
    only_left := left.difference(right)             // 1 2
    one_side := left.symmetric_difference(right)    // 1 2 4

    println("${either.len()} ${both.len()} ${only_left.len()} ${one_side.len()}")
    println("operands unchanged: ${left.len()} ${right.len()}")
}

plus_item, plus_all, and minus are the single-value counterparts, also non-mutating:

fn main() void {
    mut base: Set[string] = Set.new()
    base.put("a")

    mut extra: Set[string] = Set.new()
    extra.put("b")
    extra.put("c")

    println("${base.plus_item("z").len()}")  // 2
    println("${base.plus_all(extra).len()}") // 3
    println("${base.minus("a").len()}")      // 0
    println("${base.len()}")                 // still 1
}

plus is the map spelling and takes a key and a value; plus_item is the one that adds a member. minus needs no such pair and is shared.

A permission check reads naturally with the algebra operators — compute what is missing rather than looping:

fn missing_permissions(granted Set[string], required Set[string]) []string {
    return required.difference(granted).items().sorted().cloned()
}

fn main() void {
    mut granted: Set[string] = Set.new()
    granted.put("read")

    mut required: Set[string] = Set.new()
    required.put("read")
    required.put("write")
    required.put("delete")

    missing := missing_permissions(granted, required)
    if missing.is_empty() {
        println("authorised")
    } else {
        for name in missing {
            println("missing: ${name}")
        }
    }
}

Iteration

for value in set walks the members. Order is a property of the hash table and is not specified — sort before presenting anything.

fn main() void {
    mut tags: Set[string] = Set.new()
    tags.put("runtime")
    tags.put("memory")
    tags.put("types")

    // Fine: order does not affect the result.
    mut total := 0
    for tag in tags {
        total = total + tag.len()
    }
    println("${total}")

    // Presentation: sort first.
    for tag in tags.items().sorted() {
        println("- ${tag}")
    }
}

for_each_item takes a callback, and try_for_each_item stops as soon as the callback returns false:

fn main() void {
    mut ids: Set[int] = Set.new()
    ids.put(1)
    ids.put(2)

    ids.for_each_item(id => println("id ${id}"))

    all_positive := ids.try_for_each_item(id => id > 0)
    println("${all_positive}")
}

A set has no positions and no keyed retrieval — contains is the only lookup. There is no get:

fn main() void {
    mut ids: Set[int] = Set.new()
    ids.put(1)
    println("${ids.get(0) ?? 0}")
}

When you need to retrieve a stored value rather than merely test for it, you want a Map keyed by the identifying part.

Transformation

map_items and flat_map_items return sets, so they can shrink: several inputs mapping to one output collapse to a single member. The _item suffix is what separates them from Map’s pair-shaped map and filter, which hand the callback a (key, value) — and a set has no second half to hand over.

fn main() void {
    mut tags: Set[string] = Set.new()
    tags.put("Runtime")
    tags.put("RUNTIME")
    tags.put("Memory")

    normalized := tags.map_items(tag => tag.trim())
    println("${tags.len()} in, ${normalized.len()} out")   // 3 in, 2 out

    public_tags := normalized.filter_items(tag => !tag.starts_with("_"))
    println("${public_tags.len()}")
}

flat_map_items has a signature worth reading twice: its callback returns a Set[R], not a []R. That is the opposite of List.flat_map and of Map.flat_map, both of which take a list-returning callback — and it is what makes the result a set without a second pass.

fn digits_of(n int) Set[int] {
    mut out: Set[int] = Set.new()
    mut v := n
    if v == 0 { out.put(0) }
    for v > 0 {
        out.put(v % 10)
        v = v / 10
    }
    return out
}

fn main() void {
    mut numbers: Set[int] = Set.new()
    numbers.put(121)
    numbers.put(35)

    digits := numbers.flat_map_items(n => digits_of(n))
    for d in digits.items().sorted() { println("${d}") }
}

Returning a list from that callback is a type error:

fn main() void {
    mut numbers: Set[int] = Set.new()
    numbers.put(3)
    pairs := numbers.flat_map_items(n => [n, n + 1])
    println("${pairs.len()}")
}

Predicates and searches mirror the Map surface:

fn main() void {
    mut sizes: Set[int] = Set.new()
    sizes.put(1)
    sizes.put(8)
    sizes.put(64)

    println("${sizes.any_item(n => n > 32)}")    // short-circuits
    println("${sizes.all_items(n => n > 0)}")    // short-circuits
    println("${sizes.no_items(n => n < 0)}")     // short-circuits
    println("${sizes.count_items(n => n > 4)}")  // visits every member

    match sizes.find_item(n => n > 4) {
        Some(n) => println("found ${n}")
        None => println("none above 4")
    }
}

find_item returns an arbitrary match under hash order. When several members qualify and you care which one you get, sort a list instead:

fn main() void {
    mut sizes: Set[int] = Set.new()
    sizes.put(64)
    sizes.put(8)
    sizes.put(16)

    // Deterministic: the smallest member above 4.
    first_big := sizes.items().sorted().find(n => n > 4)
    println("${first_big ?? 0}")
}

Members

A member type needs Equatable and Hashable. @derive generates both from the fields:

@derive(Equatable, Hashable)
struct Version { major int, minor int }

fn main() void {
    mut seen: Set[Version] = Set.new()
    seen.put(Version { major: 1, minor: 0 })
    seen.put(Version { major: 1, minor: 0 })   // structurally equal — no growth
    seen.put(Version { major: 1, minor: 1 })

    println("${seen.len()}")
    println("${seen.contains(Version { major: 1, minor: 1 })}")
}

Hand-written impls let the identity ignore part of the value — here two records are the same member when their ids match, regardless of the label:

struct Node { id int, label string }

impl Equatable for Node {
    fn equals(&self, other Node) bool { return self.id == other.id }
}

impl Hashable for Node {
    fn hash_code(&self) int { return self.id }
}

fn main() void {
    mut nodes: Set[Node] = Set.new()
    nodes.put(Node { id: 7, label: "first" })
    nodes.put(Node { id: 7, label: "second" })

    println("${nodes.len()}")                                 // 1
    println("${nodes.contains(Node { id: 7, label: "any" })}")  // true
}

Equal values must hash equal, and a stored member’s participating fields must not change while it is in the set — a mutated member stays in its old bucket and becomes unreachable by contains.

Generic helpers

A Hashable bound is all a function needs to build or query sets over any member type:

fn set_of[T: Hashable](items []T) Set[T] where T: Clone {
    mut out: Set[T] = Set.new()
    for item in items { out.put(item.clone()) }
    return out
}

fn shared[T: Hashable](left []T, right []T) int where T: Clone {
    return set_of(left).intersection(set_of(right)).len()
}

fn main() void {
    println("${shared([1, 2, 3, 4], [3, 4, 5])}")
    println("${shared(["a", "b"], ["b", "c"])}")
}

Sorted sets are declaration-only

The stdlib declares SortedSet[T] — boundary queries (first, last), ranges (head_set, tail_set, sub_set), and nearest-value lookup (floor, ceiling) — plus Set.to_sorted_set() to build one. Every one of those methods is a bodyless declaration. Nothing constructs a SortedSet and nothing can run against one; a program that mentions it type-checks and then fails to build:

fn main() void {
    mut ports: Set[int] = Set.new()
    ports.put(443)
    ports.put(22)

    // Refused by `atoll check`:
    //   ATOLL2003: no method `to_sorted_set` on type `Set[int]`
    sorted := ports.to_sorted_set()
    println("lowest ${sorted.first() ?? 0}")
}

Ordered access today means sorting a list of the members. Boundary and nearest-value questions are then a scan over that list:

fn main() void {
    mut ports: Set[int] = Set.new()
    ports.put(443)
    ports.put(22)
    ports.put(80)

    ordered := ports.items().sorted()
    println("lowest ${ordered.first() ?? 0}, highest ${ordered.last() ?? 0}")

    // "At or below 100" — the largest member that is <= 100.
    mut floor := 0
    for p in ordered {
        if p <= 100 { floor = p }
    }
    println("at or below 100: ${floor}")

    below_443 := ordered.filter(p => p < 443).collect()
    println("${below_443.len()} below 443")
}

Equality and hashing of sets

Set equality is membership-based, not insertion-order-based, and the hash folds members commutatively so equivalent sets stay interchangeable as fields of derived hashable values.

fn main() void {
    mut left: Set[string] = Set.new()
    left.put("a")
    left.put("b")

    mut right: Set[string] = Set.new()
    right.put("b")
    right.put("a")
    right.put("a")   // duplicate — changes nothing

    println("${left.len() == right.len()}")
    println("${left.hash_code() == right.hash_code()}")
}

A worked example

Diffing two configuration snapshots: what was added, what was removed, and what stayed — using nothing but set algebra, with sorted output.

struct Snapshot { name string, features Set[string] }

fn snapshot(name string, features []string) Snapshot {
    mut own: Set[string] = Set.new()
    for f in features {
        own.put(f.clone())
    }
    return Snapshot { name: name, features: own }
}

fn diff(before &Snapshot, after &Snapshot) void {
    added := after.features.difference(before.features)
    removed := before.features.difference(after.features)
    kept := before.features.intersection(after.features)
    churn := before.features.symmetric_difference(after.features)

    println("${before.name} -> ${after.name}")
    for feature in added.items().sorted() { println("  + ${feature}") }
    for feature in removed.items().sorted() { println("  - ${feature}") }
    println("  ${kept.len()} unchanged, ${churn.len()} changed")

    if churn.is_empty() {
        println("  identical")
    }
}

fn main() void {
    v1 := snapshot("v1", ["tracing", "metrics", "legacy_auth"])
    v2 := snapshot("v2", ["tracing", "metrics", "oauth"])
    diff(v1, v2)
    diff(v2, v2)
}

Type to search…

↑↓ navigate↵ selectEsc close