Set.add
func Set.add[T](s: Set[T], x: T): boolSet.add adds x to s and reports whether it was not already a member. It mutates s. Adding an existing member changes nothing, so it keeps its position.
Details
- Every name that shares the set sees the new member. Membership is by
==. - A new member goes to the end of the insertion order, so a member removed and added again moves to the end.
- A
forloop oversvisits members added during the loop. - A member is hashed when it is added. Mutating an array or a record after adding it is a program error: the set may no longer find it.
Basic examples
Add a member, and learn whether it was new:
let s = Set.of([1, 2])
Set.add(s, 3) // true
Set.add(s, 2) // false
s // Set.of([1, 2, 3])Start from an empty set, whose element type comes from the annotation:
let tags: Set[string] = Set.of([])
Set.add(tags, "red") // true
Set.add(tags, "blue") // true
Set.add(tags, "red") // false
tags // Set.of(["red", "blue"])Scope
Records and arrays are members by value, so an equal one is not added again:
type Point = { x: int, y: int }
let points: Set[Point] = Set.of([])
points.add(Point{ x: 1, y: 2 }) // true
points.add(Point{ x: 1, y: 2 }) // false
let rows = Set.of([[1, 2]])
rows.add([1, 2]) // false
rows.add([2, 1]) // truenull is a member like any other in a set that allows it:
let maybe: Set[int | null] = Set.of([1])
maybe.add(null) // true
maybe.add(null) // false
maybe // Set.of([1, null])Floats compare as == compares them, so -0.0 is the member 0.0:
let zeros = Set.of([0.0])
zeros.add(-0.0) // falseA let set can be added to, since the binding stays the same:
let s = Set.of(["a"])
s.add("b") // true
s // Set.of(["a", "b"])Applications
Keep the first of each line, with no separate membership test:
let seen: Set[string] = Set.of([])
for line in ["b", "a", "b", "c", "a"] {
if seen.add(line) {
println(line)
}
}b
a
cFind the values that repeat, each reported once:
func repeated(words: Array[string]): Array[string] {
let seen: Set[string] = Set.of([])
let twice: Set[string] = Set.of([])
for w in words {
if !seen.add(w) {
twice.add(w)
}
}
twice.values()
}
repeated(["to", "be", "or", "not", "to", "be", "to"]) // ["to", "be"]Collect every node reachable from a start. The for loop visits the members added while it runs. A node already in the set is not added again, so a cycle ends. edges[node] ?? [] is an empty array for a node with no edges:
func reachable(edges: Map[string, Array[string]], start: string): Set[string] {
let found = Set.of([start])
for node in found {
for next in edges[node] ?? [] {
found.add(next)
}
}
found
}
let edges = Map{ a: ["b", "c"], b: ["d"], c: ["a"], d: ["b"], e: ["a"] }
reachable(edges, "a") // Set.of(["a", "b", "c", "d"])
reachable(edges, "e") // Set.of(["e", "a", "b", "c", "d"])Count the distinct values of a field in a list of records:
type Order = { customer: string, total: int }
let orders = [
Order{ customer: "ada", total: 30 },
Order{ customer: "linus", total: 12 },
Order{ customer: "ada", total: 7 },
]
let customers: Set[string] = Set.of([])
for o in orders {
customers.add(o.customer)
}
customers.size() // 2Properties and relations
The result is the opposite of Set.has before the call, and x is a member after it:
let s = Set.of([1, 2])
let had = s.has(5)
assert(s.add(5) == !had)
assert(s.has(5))The size grows by one exactly when the result is true:
let s = Set.of(["a"])
let before = s.size()
let added = s.add("b")
assert(s.size() == before + (if added { 1 } else { 0 }))
assert(!s.add("b"))
assert(s.size() == 2)A new member goes last in Set.values:
let s = Set.of([3, 1])
s.add(2)
assert(s.values().last() == 2)It does in place what Set.union with a one-member set does in a new set:
let s = Set.of([1, 2])
let u = s.union(Set.of([3]))
let added = s.add(3)
assert(added)
assert(s == u)
assert(s.values() == u.values())Set.remove undoes the add of a new member:
let s = Set.of([1, 2])
let copy = Set.of(s.values())
s.add(3)
assert(s.remove(3))
assert(s == copy)Every other name for the set sees the add:
let s = Set.of([1])
let alias = s
s.add(2) // true
assert(Set.same(alias, s))
alias // Set.of([1, 2])Possible issues
Set.add returns a bool, not the set, so its result cannot be assigned back:
var s = Set.of([1])
s = s.add(2) // error: cannot use bool where Set[int] is expectedTo get a new set and keep the old one, use Set.union:
let s = Set.of([1])
let t = s.union(Set.of([2]))
s // Set.of([1])
t // Set.of([1, 2])Set.of([]) has no element type to infer, so annotate the variable:
let s = Set.of([]) // error: cannot infer the element type of an empty array; annotate it
s.add(1)x must have the element type:
let s = Set.of([1])
s.add("2") // error: cannot use string where int is expectedA set has no indexing, so add with Set.add, not an assignment as for a map:
let s: Set[int] = Set.of([])
s[1] = true // error: Set[int] cannot be indexedNaN is not == to itself, so each add of it adds a new member:
let s: Set[float64] = Set.of([])
let nan = 0.0 / 0.0
s.add(nan) // true
s.add(nan) // true
s.size() // 2Adding an existing member does not move it. To move a member to the end, remove it first:
let s = Set.of(["a", "b", "c"])
s.add("a") // false
s // Set.of(["a", "b", "c"])
s.remove("a") // true
s.add("a") // true
s // Set.of(["b", "c", "a"])Adding to one set from several goroutines without a lock is a data race. Guard the set with a Mutex:
let seen: Set[int] = Set.of([])
let lock = Mutex.new()
let wg = WaitGroup.new()
for n in [1, 2, 3, 2, 1] {
wg.add(1)
go {
defer { wg.done() }
lock.withLock({ seen.add(n) })
}
}
wg.wait()
println(seen.size())3See also
Set.has, Set.remove, Set.of, Set.union, Set.values, Map.set, Array.push
