Skip to content

Standard Library: Collections

Shape’s core collection types (Vec<T>, HashMap<K,V>) are documented in Objects and Arrays. This page covers the additional collection utilities provided by the standard library.

HashMap<K, V> is imported from std::core::intrinsics. See Objects and Arrays for the full API.

from std::core::intrinsics use { HashMap }
// `let` bindings are immutable. Chain `.set(...)` calls to build up a HashMap,
// or use `let mut counts = HashMap()` + `counts = counts.set(...)` reassignment.
let counts = HashMap().set("a", 1).set("b", 2)
print(counts.get("a")) // 1
print(counts.len()) // 2

The set module provides an unordered collection of unique elements backed by HashMap for O(1) lookups.

from std::core::set use {
new, from_array, add, remove, includes, union,
intersection, difference, to_array, len
}
// Empty set
let s = new()
// From an array (deduplicates automatically)
let s = from_array(["a", "b", "c", "b", "a"])
print(len(s)) // 3

Note: at HEAD, the underlying HashMap only accepts string keys. Sets of int or other non-string elements surface a runtime HashMap key must be a string (got kind ...) error.

Sets are immutable — operations return a new set.

let s = from_array(["a", "b", "c"])
let s2 = add(s, "d") // {"a","b","c","d"}
let s3 = remove(s2, "b") // {"a","c","d"}
let s = from_array(["a", "b", "c"])
print(includes(s, "b")) // true
print(includes(s, "z")) // false
print(len(s)) // 3
let a = from_array(["x", "y", "z"])
let b = from_array(["y", "z", "w"])
let u = union(a, b) // {"x","y","z","w"}
let i = intersection(a, b) // {"y","z"}
let d = difference(a, b) // {"x"}
let s = from_array(["c", "a", "b"])
let arr = to_array(s)
print(arr) // ["c", "a", "b"] (order may vary)
FunctionDescription
new()Create an empty set
from_array(arr)Create a set from an array (deduplicates)
add(s, item)Return a new set with item added
remove(s, item)Return a new set with item removed
includes(s, item)Check if set contains item
union(a, b)Return the union of two sets
intersection(a, b)Return the intersection of two sets
difference(a, b)Return elements in a but not in b
to_array(s)Convert set to array
len(s)Number of elements in the set