Set
import "std/collections" (included in import "std") · namespace std.collections
Set<T> holds each value once and keeps insertion order. Membership is checked with ==, so it works for any element type, but contains is O(n). For large sets of numbers or strings, use HashSet.
grav
import "std"
fn main() {
let tags = new Set<string>()
for (t in ["red", "blue", "red", "green", "blue"]) { tags.add(t) }
print(tags)
print(tags.size())
print(tags.get(0))
let warm = new Set<string>()
warm.add("red")
warm.add("orange")
print(tags.intersect(warm))
print(tags.union(warm))
}{"red", "blue", "green"}
3
red
{"red"}
{"red", "blue", "green", "orange"}API
class Set<T>
Constructors
new Set()
Methods
fn add(item: T) -> bool— Addsitemunless present; reports whether it was added.fn contains(item: T) -> bool— Whether the set hasitem(==).fn remove(item: T) -> bool— Removesitem; whether it was there.fn size() -> int— The number of elements.fn length() -> int— The number of elements (same as size()).fn isEmpty() -> bool— Whether the set is empty.fn clear()— Removes every element.fn get(index: int) -> T— Elements in insertion order (index-based access for iteration).fn at(index: int) -> T— The element at index (insertion order).fn forEach(f: fn(T))— Calls f on each element, in insertion order.fn toString() -> string— As text: {1, 2, 3} (strings in quotes).fn toArray() -> Array<T>— The elements as a new Array, in insertion order.fn union(other: Set<T>) -> Set<T>— A new set with the elements of both sets.fn intersect(other: Set<T>) -> Set<T>— A new set with the elements in both sets.fn difference(other: Set<T>) -> Set<T>— A new set with the elements of this set that are not inother.fn isSubsetOf(other: Set<T>) -> bool— Whether every element of this set is inother.