Vectors, bounds and tablesSlide 22 of 86
22sortVectors, bounds and tables
Walking and sorting
Four builtins walk a vector with a function, calling it once per element, in order, on the calling thread. map, filter and filterMap take a func or a proc, but never one that takes its element mut; sort takes a func:
map(values, transform)answers with every element transformed, at the vector's length. A transform that answers with nothing is refused: a walk that only acts is afor each.filter(values, keep)answers with the elementskeepsaystrueto.filterMap(values, transform)does both:transformanswers with aResult, and theOkpayloads are kept.sort(values)answers with the elements in their own order, below, andsort(values, first)in the order afunc(a, b): Boolgives,truewhenacomes first. Equal elements keep the order they had.
Without a comparator, sort uses the elements' own order:
- numbers by value, and
falsebeforetrue; - a
Strby its bytes, so"B"comes before"a"; - an atom by where it was first mentioned;
- a vector element by element, and a declared type field by field, in declaration order;
- a union by the order its variants were declared in, and a
Resultwith itsErrors before itsOks.
A map, an address and a function value have no order, nor does a type holding one, so sorting them takes a comparator. Written as a statement on a mut vector, sort sorts it in place.
map, filter and filterMap
func isLong(fruit: Str): Bool {
return len(fruit) > 4
}
func shout(fruit: Str): Str {
return fruit + "!"
}
func evenHalf(n: Int): Result<Int, Bool> {
if n % 2 == 0 {
return Result.Ok(n / 2)
}
return Result.Error(false)
}
proc main(): void {
fruit := ["pear", "apple", "kiwi"]
echo map(fruit, shout) // ["pear!", "apple!", "kiwi!"]
echo filter(fruit, isLong) // ["apple"]
echo filterMap([1, 2, 3, 4], evenHalf) // [1, 2]
}You can edit this program and run it here.Tab indents, Escape leaves the program, and Ctrl+Enter runs it.
Sorting
func longerFirst(a: Str, b: Str): Bool {
return len(a) > len(b)
}
proc main(): void {
echo sort(["pear", "Apple", "kiwi"]) // ["Apple", "kiwi", "pear"] — by bytes
echo sort([true, false]) // [false, true]
echo sort([[2, 1], [1, 9], [1, 2]]) // [[1, 2], [1, 9], [2, 1]]
echo sort(["fig", "banana", "kiwi"], longerFirst)
mut ranks := [3, 1, 2]
sort(ranks) // a statement: sorts ranks in place
echo ranks
}You can edit this program and run it here.Tab indents, Escape leaves the program, and Ctrl+Enter runs it.
Output
Run a program to see what it prints here.