Set.of
func Set.of[T](xs: Array[T]): Set[T]Set.of returns a new set holding the first of each == value in xs, in order. Set.of([]) is the empty set, its element type coming from the expected type.
Details
- Returns a new set. Adding to or removing from the set leaves
xsas it was, and pushing to or removing fromxsleaves the set as it was. - A member is hashed when the set is built. Changing an array, map, set, or record after it became a member is a program error: the set may no longer find it.
Set.of([])takes its element type from the expected type (an annotation, a parameter or return type, a record field, or the left side of??), from the other arguments of a generic call, or from the other elements of an array literal. With none of these, it is a compile error.
Basic examples
Build a set from an array. Duplicates go, and the first of each value keeps its place:
Set.of([3, 1, 3, 2, 1]) // Set.of([3, 1, 2])
Set.of(["red", "blue"]) // Set.of(["red", "blue"])Call functions on the result through .:
let tags = Set.of(["ant", "go", "ant"])
tags.size() // 2
tags.has("go") // true
tags.has("zig") // falseScope
An empty array gives the empty set. The annotation supplies the element type:
let seen: Set[int] = Set.of([])
seen // Set.of([])
seen.size() // 0Passed to a call next to another set, Set.of([]) takes its element type from that set, also when it comes before the dot:
Set.isSubset(Set.of([]), Set.of([1, 2])) // true
Set.union(Set.of([]), Set.of(["a"])) // Set.of(["a"])
Set.of([]).isSubset(Set.of([1, 2])) // trueIn an array literal, it takes its element type from the other elements:
[Set.of([1]), Set.of([])] // [Set.of([1]), Set.of([])]Records are members by contents, so two records with the same fields are one member:
type Point = { x: int, y: int }
Set.of([Point{ x: 1, y: 2 }, Point{ x: 1, y: 2 }]) // Set.of([Point{ x: 1, y: 2 }])Members of a tagged union compare by tag and fields, so equal fields under two tags stay two members:
type Circle = { r: int }
type Square = { r: int }
type Shape = Circle | Square
let shapes: Array[Shape] = [Circle{ r: 1 }, Square{ r: 1 }, Circle{ r: 1 }]
Set.of(shapes) // Set.of([Circle{ r: 1 }, Square{ r: 1 }])Arrays compare by their elements in order; maps and sets compare in any order:
Set.of([[1, 2], [2, 1], [1, 2]]) // Set.of([[1, 2], [2, 1]])
Set.of([Map{ a: 1, b: 2 }, Map{ b: 2, a: 1 }]) // Set.of([Map{ "a": 1, "b": 2 }])
Set.of([Set.of(["x", "y"]), Set.of(["y", "x"])]) // Set.of([Set.of(["x", "y"])])An element type that includes null gives a set that can hold null once:
let answers: Array[int | null] = [1, null, null, 1]
Set.of(answers) // Set.of([1, null])An array of mixed values gives a set of their union type:
let mixed = Set.of([1, "a", 1])
mixed // Set.of([1, "a"])A string is not an array. Split it into code points with String.chars first:
Set.of("hello".chars()) // Set.of(["h", "e", "l", "o"])In a pipeline, the array is the argument:
"b a b c a" | String.split(" ") | Set.of() // Set.of(["b", "a", "c"])The parameter is named xs:
Set.of(xs: [2, 2, 7]) // Set.of([2, 7])Applications
Count the distinct words of a sentence:
let words = "the cat and the hat and the bat".split(" ")
Set.of(words).size() // 5Collect the distinct values of a map:
let ages = Map{ ada: 36, linus: 54, alan: 36 }
Set.of(ages.values()) // Set.of([36, 54])Keep a fixed list of allowed values as a set, and check input against it:
let allowed = Set.of(["debug", "info", "warn", "error"])
for level in ["info", "loud"] {
if allowed.has(level) {
println("ok: ${level}")
} else {
println("unknown level: ${level}")
}
}ok: info
unknown level: loudFind the letters two words share, in the order of the first word:
let a = Set.of("listen".chars())
let b = Set.of("pistol".chars())
Set.intersect(a, b).values() // ["l", "i", "s", "t"]Start from a set of known members, then add to it while reading:
let visited = Set.of(["home"])
for page in ["about", "home", "blog", "about"] {
if visited.add(page) {
println("new: ${page}")
}
}
println(visited)new: about
new: blog
Set.of(["home", "about", "blog"])Fall back to an empty set for a missing map key. The right side of ?? takes the map's value type:
let followers: Map[string, Set[string]] = Map{ ada: Set.of(["alan"]) }
for name in ["ada", "linus"] {
let fs = followers[name] ?? Set.of([])
println("${name}: ${fs.size()}")
}ada: 1
linus: 0Properties and relations
The members of Set.of(xs), in order, are what Array.unique returns:
let xs = [4, 2, 4, 9, 2]
assert(Set.of(xs).values() == xs.unique())The set never has more members than xs has elements, and every element of xs is a member:
let xs = ["a", "b", "a"]
let s = Set.of(xs)
assert(s.size() <= len(xs))
assert(xs.every({ s.has(x) }))Order does not matter to ==, so an array and its reverse give equal sets:
let xs = [1, 2, 3, 2]
assert(Set.of(xs) == Set.of(xs.reverse()))
assert(Set.of(xs).values() != Set.of(xs.reverse()).values())Building a set from the values of another gives an equal, separate set:
let s = Set.of([1, 2])
let t = Set.of(s.values())
assert(s == t)
assert(!Set.same(s, t))
t.add(3)
assert(!s.has(3))Possible issues
Set.of([]) with no expected type has no element type to infer:
let s = Set.of([]) // error: cannot infer the element type of an empty array; annotate itThere is no set literal. Set{} is read as a record literal:
let s: Set[int] = Set{} // error: a record literal needs a record type as its headSet.of takes one array, not the members as separate arguments:
let s = Set.of(1, 2) // error: Set.of takes 1 argument, got 2A set has no indexing. Use Set.values for an array to index:
let s = Set.of([10, 20])
println(s[0]) // error: Set[int] cannot be indexedlet s = Set.of([10, 20])
s.values()[0] // 10NaN is not == to itself, so every NaN becomes a member of its own:
Set.of([Math.NaN, Math.NaN]).size() // 2
Set.of([0.0, -0.0]).size() // 1Strings compare by code points, so the two Unicode spellings of "é" are two members. Normalize them with String.normalize first:
let names = ["café", "cafe\u{301}"]
Set.of(names).size() // 2
Set.of(names.map({ x.normalize("NFC") })).size() // 1See also
Set.values · Set.has · Set.add · Set.size · Set.union · Array.unique · Map.fromEntries
