LEVIATHAN vd52e79c4 · d52e79c486

Standard Library

class Set<T>

A collection of distinct values of type T, with value semantics.

since 0.1.0-alpha.1linuxwindowswasm

bases
IIterable<T>

Overview

A set holds each value at most once. Like Array and Map, a set is never changed in place: with, without, union, intersect, except and where all return a new set. Elements are listed in the order they were first added, and a for loop visits them in that order.

Elements are compared the same way Map keys are: by value for numbers, strings and bool, field by field for structs (a struct's own (==) is not used), by content for sets, and by identity for class instances. Two sets are == when they hold the same elements, in any order, and a set can itself be a Map key or a Set element. Printing a set with console.writeln shows it as {a, b, c}.

Create one with Set() for an empty set, or Set(items) to collect the distinct values of an array. Set<T> s; with no initializer is the empty set.

Description

Set<T> holds distinct values of type T. It is a built-in value collection, like Array and Map: add, remove and clear mutate the place they are called on and return nothing, while with and without are pure and return a new set. This changes behaviour for existing programs: s = s.with(x) still works, but the idiom for change is the statement s.add(x);. Create one with Set() (or a declaration with no initializer, Set<int> s;), or collect the distinct values of an array with Set(items) or items.toSet(), which drop duplicates and keep the first occurrence.

A set remembers insertion order. A for loop, toArray() and printing list the elements in that order, and union puts the elements of the receiver first, followed by the new elements of the argument. console.writeln(s) prints text such as {3, 1, 2}.

Elements are compared the way Map compares keys: primitives by value (floats canonically, so 0.0 and -0.0 are one element and every NaN is one element), structs field by field, arrays in order, maps and sets by content, and class instances by identity. A struct's own (==) is not consulted. Two sets are == when they hold the same elements, whatever the order, and a set can be a Map key or an element of another set.

has(x) tests membership, length() counts elements, and isEmpty() is true for an empty set. The set algebra methods union, intersect, except and where return a new set; isSubsetOf, isSupersetOf and isDisjointFrom compare two sets. A set is also an IIterable<T>, so it can be passed where one is expected.

Building and combining sets

use io::console;

Set<int> s = Set([3, 1, 3, 2]);
console.writeln(s);
console.writeln(s.length());
console.writeln(s.has(2));
Set<int> bigger = s.with(9);
console.writeln(bigger);
console.writeln(s);
console.writeln(s.without(3));
console.writeln(s.without(77));
Set<int> t = Set([2, 5]);
console.writeln(s.union(t));
console.writeln(s.intersect(t));
console.writeln(s.except(t));
console.writeln(s.toArray());
console.writeln(Set([2, 1, 3]) == s);
{3, 1, 2}
3
true
{3, 1, 2, 9}
{3, 1, 2}
{1, 2}
{3, 1, 2}
{3, 1, 2, 5}
{2}
{3, 1}
[3, 1, 2]
true

Rules

  • with(x) and without(x) return a new set; the receiver is unchanged. Adding an element that is already present, or removing one that is absent, gives back the same set.
  • To change a set, call the verb: seen.add(x); or seen.remove(x);. To keep the original, use the pure form (bigger = s.with(x)) or copy first.
  • Removing an element and adding it again moves it to the end of the order.
  • for (T x in s) visits the elements in insertion order. The loop variable is a copy, and a loop that rebinds s inside its body still visits the set as it was when the loop started.
  • console.writeln(s), toString() and string interpolation print {a, b}; an empty set prints {}.
  • == and != compare contents regardless of order. A set never equals a value of another type.
  • Elements compare by the key relation (see Description): struct elements are equal when all their fields are, class elements only when they are the same object.

Examples

Rebinding, iteration and struct elements

use io::console;

struct Pt { int x; int y; }
Set<int> grown = Set();
grown.add(4); grown.add(4); grown.add(5);
console.writeln(grown);
for (int x in grown) {
    console.writeln(x * 2);
}
Set<Pt> pts = Set();
pts.add(Pt(1, 1)); pts.add(Pt(1, 1)); pts.add(Pt(2, 2));
console.writeln(pts.length());
Set<string> none;
console.writeln(none.isEmpty());
{4, 5}
8
10
2
true

Sets as keys and set relations

use io::console;

Set<int> a = Set([1, 2]);
Set<Set<int>> family = Set([a, Set([2, 1]), Set([3])]);
console.writeln(family.length());
Map<Set<int>, string> names = Map();
names[a] = "low";
console.writeln(names[Set([2, 1])]);
console.writeln(a.isSubsetOf(Set([1, 2, 3])));
console.writeln(a.isDisjointFrom(Set([3, 4])));
console.writeln(Set([1, 2, 3, 4]).where((int x) => x % 2 == 0));
2
low
true
true
{2, 4}

Notes

  • has is O(1) expected on every engine. On LLVM and on the IR interpreter (--ir), s = s.with(x) and s = s.without(x) on a set that only a local variable holds are amortized O(1); a set that something else also holds is copied first. A set in a field or a top-level variable can be copied by an update even when nothing else holds it — g = g.with(x) on a top-level variable always is. The reference interpreter (--run) copies the set on every update. The set algebra methods are linear in the sizes of their inputs on LLVM.

Examples

Distinct values and set algebra

use io::console;

Set<int> a = Set([1, 2, 2, 3]);
Set<int> b = Set([3, 4]);
console.writeln(a);
console.writeln(a.union(b));
console.writeln(a.intersect(b));
console.writeln(a.except(b));
console.writeln(a.has(2));
console.writeln(Set([3, 2, 1]) == a);
for (int x in a) {
    console.writeln(x * 10);
}
{1, 2, 3}
{1, 2, 3, 4}
{3}
{1, 2}
true
true
10
20
30

Constructors

new

new()

Create an empty set.

Set<string> s; with no initializer is the same empty set.

Examples

An empty set

use io::console;

Set<string> s = Set();
console.writeln(s.length());
console.writeln(s.with("a").length());
console.writeln(s.length());
0
1
0
new(Array<T> items)

Create a set holding the distinct values of items.

Duplicates are collapsed to their first occurrence, which also decides the order.

Parameters

items
The values to collect.

Examples

From an array with duplicates

use io::console;

Set<string> s = Set(["b", "a", "b", "c", "a"]);
console.writeln(s.length());
console.writeln(s.toArray());
3
[b, a, c]

Methods

add

mutating add(T v) -> void

Add v to this set, in place. A value already present changes nothing.

add is a verb: an imperative name changes the set and returns nothing. Its pure twin is with, which returns the new set and leaves the receiver alone.

Parameters

v
The value to add.

Examples

Adding values

use io::console;

Set<int> s = Set([1, 2]);
s.add(3);
s.add(1);
console.writeln(s);
{1, 2, 3}

See also: with

clear

mutating clear() -> void

Remove every value of this set, in place.

Examples

Emptying a set

use io::console;

Set<int> s = Set([1, 2]);
s.clear();
console.writeln(s.length());
0

except

except(Set<T> o) -> Set<T>

Return a new set of the values that are in this set but not in o.

The values keep the order they have in this set. Neither input is changed.

Parameters

o
The set of values to leave out.

Returns

The difference of the two sets.

Examples

Difference

use io::console;

Set<int> a = Set([1, 2, 3]);
Set<int> b = Set([3, 4]);
console.writeln(a.except(b));
console.writeln(b.except(a));
{1, 2}
{4}

See also: union, intersect

has

@Pure
has(T v) -> bool

Whether v is in the set.

Parameters

v
The value to test.

Returns

true if the set holds a value equal to v.

Examples

Membership

use io::console;

Set<string> s = Set(["a", "b"]);
console.writeln(s.has("a"));
console.writeln(s.has("z"));
true
false

intersect

intersect(Set<T> o) -> Set<T>

Return a new set of the values that are in both this set and o.

The values keep the order they have in this set. Neither input is changed.

Parameters

o
The other set.

Returns

The intersection of the two sets.

Examples

Intersection

use io::console;

Set<int> a = Set([1, 2, 3]);
Set<int> b = Set([3, 2, 9]);
console.writeln(a.intersect(b));
{2, 3}

See also: union, except

isDisjointFrom

isDisjointFrom(Set<T> o) -> bool

Whether this set and o have no value in common.

The empty set is disjoint from every set.

Parameters

o
The other set.

Returns

true when no value is in both sets.

Examples

Disjoint sets

use io::console;

Set<int> odd = Set([1, 3, 5]);
Set<int> even = Set([2, 4]);
console.writeln(odd.isDisjointFrom(even));
console.writeln(odd.isDisjointFrom(Set([5, 6])));
true
false

See also: intersect

isEmpty

@Pure
isEmpty() -> bool

Whether the set has no values.

Returns

true when length() is 0.

Examples

Emptiness

use io::console;

Set<int> e = Set();
console.writeln(e.isEmpty());
console.writeln(e.with(1).isEmpty());
true
false

isSubsetOf

isSubsetOf(Set<T> o) -> bool

Whether every value of this set is also in o.

The empty set is a subset of every set, and every set is a subset of itself.

Parameters

o
The other set.

Returns

true when no value of this set is missing from o.

Examples

Subsets

use io::console;

Set<int> small = Set([1, 2]);
Set<int> big = Set([3, 2, 1]);
Set<int> none = Set();
console.writeln(small.isSubsetOf(big));
console.writeln(big.isSubsetOf(small));
console.writeln(none.isSubsetOf(small));
true
false
true

See also: isSupersetOf

isSupersetOf

isSupersetOf(Set<T> o) -> bool

Whether every value of o is also in this set.

a.isSupersetOf(b) is b.isSubsetOf(a).

Parameters

o
The other set.

Returns

true when no value of o is missing from this set.

Examples

Supersets

use io::console;

Set<string> all = Set(["a", "b", "c"]);
console.writeln(all.isSupersetOf(Set(["c", "a"])));
console.writeln(all.isSupersetOf(Set(["z"])));
true
false

See also: isSubsetOf

iterator

iterator() -> IIterator<T>

Return an iterator over the values, in the order they were first added.

This is what lets a set be passed where an IIterable<T> is expected. A for loop over a set does not need it. The iterator walks a snapshot of the set as it was when the iterator was created.

Returns

An iterator positioned before the first value.

Examples

Walking a set by hand

use io::console;

Set<string> s = Set(["a", "b"]);
IIterator<string> it = s.iterator();
while (it.hasNext()) {
    console.writeln(it.next());
}
a
b

length

@Pure
length() -> int

The number of distinct values in the set.

Returns

The element count.

Examples

Counting

use io::console;

Set<int> s = Set([1, 1, 2]);
console.writeln(s.length());
2

remove

mutating remove(T v) -> void

Remove v from this set, in place. A value not in the set changes nothing.

The verb twin of without, which returns the new set and leaves the receiver alone.

Parameters

v
The value to remove.

Examples

Removing a value

use io::console;

Set<int> s = Set([1, 2, 3]);
s.remove(2);
s.remove(9);
console.writeln(s);
{1, 3}

See also: without

toArray

toArray() -> Array<T>

The values as an array, in the order they were first added.

Returns

A new array of the distinct values.

Examples

A set as an array

use io::console;

Set<string> s = Set(["x", "y", "x"]);
Array<string> a = s.toArray();
console.writeln(a);
console.writeln(a.length());
[x, y]
2

toString

toString() -> string

The set as text, such as {a, b, c}.

The elements appear in the order they were first added, separated by a comma and a space; an empty set is {}. console.writeln(set) and string interpolation print the same text.

Returns

The text form of the set.

Examples

Printing a set

use io::console;

Set<int> s = Set([3, 1, 2]);
console.writeln(s.toString());
console.writeln("set: ${s}");
Set<int> empty = Set();
console.writeln(empty);
{3, 1, 2}
set: {3, 1, 2}
{}

union

union(Set<T> o) -> Set<T>

Return a new set of the values that are in this set, in o, or in both.

The values of this set come first, followed by the values only in o. Neither input is changed.

Parameters

o
The other set.

Returns

The union of the two sets.

Examples

Union

use io::console;

Set<int> a = Set([1, 2, 3]);
Set<int> b = Set([3, 4]);
console.writeln(a.union(b));
{1, 2, 3, 4}

See also: intersect, except

where

where((T) => bool pred) -> Set<T>

Return a new set of the values for which pred is true.

The values keep their order. The receiver is not changed.

Parameters

pred
The test each value must pass.

Returns

The values that pass.

Examples

Keeping some values

use io::console;

Set<int> s = Set([1, 2, 3, 4, 5, 6]);
console.writeln(s.where((int x) => x % 2 == 0));
{2, 4, 6}

with

with(T v) -> Set<T>

Return a new set that also contains v.

If v is already in the set the result is the same set. The receiver is not changed: with is pure; its verb twin add changes the set in place.

Parameters

v
The value to add.

Returns

A set including v.

Examples

Adding a value

use io::console;

Set<int> a = Set([1, 2]);
Set<int> b = a.with(3);
console.writeln(a);
console.writeln(b);
console.writeln(b.with(3).length());
{1, 2}
{1, 2, 3}
3

See also: without

without

without(T v) -> Set<T>

Return a new set that does not contain v.

If v is not in the set the result is the same set. The receiver is not changed: without is pure; its verb twin remove changes the set in place. Removing a value and adding it again moves it to the end of the order.

Parameters

v
The value to remove.

Returns

A set without v.

Examples

Removing a value

use io::console;

Set<int> a = Set([1, 2, 3]);
console.writeln(a.without(2));
console.writeln(a.without(9));
console.writeln(a.without(1).with(1));
console.writeln(a);
{1, 3}
{1, 2, 3}
{2, 3, 1}
{1, 2, 3}

See also: with

See also

  • Map — An associative collection from keys of type K to values of type V, with value semantics.
  • Collections are values — Array, Map and Set are values; the in-place verbs (add, set, remove, ...) change the variable you call them on, the prepositional forms (with, without, concat) return a new value.
  • Array — An ordered sequence of values of one type, Array<T>, with value semantics.