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
Section titled “HashMap”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")) // 1print(counts.len()) // 2Set (via std::core::set)
Section titled “Set (via std::core::set)”The set module provides an unordered collection of unique elements backed by
HashMap for O(1) lookups.
Importing
Section titled “Importing”from std::core::set use { new, from_array, add, remove, includes, union, intersection, difference, to_array, len}Creating Sets
Section titled “Creating Sets”// Empty setlet s = new()
// From an array (deduplicates automatically)let s = from_array(["a", "b", "c", "b", "a"])print(len(s)) // 3Note: 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.
Modifying Sets
Section titled “Modifying Sets”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"}Querying
Section titled “Querying”let s = from_array(["a", "b", "c"])print(includes(s, "b")) // trueprint(includes(s, "z")) // falseprint(len(s)) // 3Set Operations
Section titled “Set Operations”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"}Converting Back to Array
Section titled “Converting Back to Array”let s = from_array(["c", "a", "b"])let arr = to_array(s)print(arr) // ["c", "a", "b"] (order may vary)Set Function Reference
Section titled “Set Function Reference”| Function | Description |
|---|---|
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 |
See Also
Section titled “See Also”- Objects and Arrays —
Vec<T>andHashMap<K,V>built-in types - Tables —
Table<T>for row-oriented data