pub const VECTOR: BuiltinSchema;Expand description
Vector<T>: the growable sequence, and the one builtin with a mutable
graph of its own.
push, set, pop, remove, and freeze are the language’s only
var self methods: one appends, one replaces, two take an element back
out, and the last consumes locally unique storage and hands back an
Array in O(1). toArray is the copying alternative, for a caller that
cannot give the storage up.
§The name of a mutation, and the name of an answer
A method that writes through the receiver is spelled as an imperative
verb — push, set, pop, remove — and a method that answers a new
collection is spelled as a past participle: Map.inserted,
Set.removed, and every sequence’s sorted. That is why removal here is
remove and not removed, which is Set’s non-mutating answer and
would say the opposite of what this does. The parameter is index for
the same reason, because get(index) and set(index, value) already
call it that.
§There is no clear
Emptying a vector is pop in a loop, or — for scratch state that is
rebuilt each time round, which is what the examples write — rebinding
var items = Vector.of(), which costs nothing and hands back storage
nothing else can be holding. What a clear would add over those is a
bulk write through an alias, and a program that empties a vector
somebody else is holding is the case worth making a caller spell out.
It is also the only one of the three shrinking operations with nothing to
answer, so it is the only one that would need a decision of its own —
Unit, or the count it discarded — where pop and remove inherit
get’s answer whole. An operation whose only argument is convenience and
whose only question is new is the one to leave out.
§What a removal costs
push, set, and pop are O(1). remove(index) is O(n - index),
because the elements after index move down one; that is written down
for the reason set being O(1) is.
contains, indexOf, slice, map, filter, fold, and sorted are
the same seven an Array has, and the four that produce a sequence
answer an Array here too: v.sorted(by:) is v.toArray().sorted(by:)
and writes nothing through the handle, so an alias sees no change and no
walk can be disturbed by what happens during it.
Removal is checked against that rather than assumed under it, because a
walk that shrinks its own receiver is the case that would have found it
wrong. The check is written as a for rather than as a callback: a
closure captures a copy of each binding it reads and a captured binding
is a read-only place, so items.pop() inside a filter callback is
refused by the checker, and for, which walks the elements it asked for
once, is where the question can be asked at all.