Slide 17 of 74

Builtins

Measuring, growing and shrinking
proc main(): void {
	echo len(["pear", "apple", "kiwi"])   // 3
	echo bytes("café")                     // 5

	mut Str[dyn] basket = ["pear"]
	append(basket, "apple")
	prepend(value: "kiwi", vector: basket) // named, in any order
	echo basket

	// drop's two bounds are proved like an index, which is the next slide:
	// here the guard is that basket has a first element.
	if basket bounds 0 {
		echo drop(basket, 0, 0)            // ["kiwi"]
	}
	echo basket                            // ["pear", "apple"]
}
Joining, splitting, finding and rewriting
proc main(): void {
	fruit := ["pear", "apple", "kiwi"]
	line := join(fruit, ", ")
	echo split(line, ", ")

	if indexOf(fruit, "apple") is Result.Ok(i) {
		echo fruit[i]          // an Ok position needs no guard
	}

	path := "a/b/c"
	echo replaceFirst(path, "/", " > ")   // a > b/c
	echo replaceAll(path, "/", " > ")     // a > b > c
	echo path                             // a/b/c — a Str is a value
}
A declaration of your own wins
// Ours. Its own parameters, its own arity, and it is what every bare
// call to len in this file means from here on.
func len(label: Str, extra: Int): Str {
	return "{label}{extra}"
}

proc main(): void {
	Str[dyn] v = ["a", "b"]

	echo len("x", 2)          // ours: x2
	echo hive.len(v)          // the builtin, by its long name: 2
	echo hive.join(v, "-")    // the long name works whether you shadowed or not
}

These are always in scope, with no import:

  • len counts a vector's elements, a Str's characters or a map's pairs; bytes counts a vector's storage or a Str's UTF-8.
  • append and prepend grow a mut [dyn] vector at either end; drop(v, low, high) removes a range, both ends inclusive, and hands back what it removed.
  • join(vector, sep) puts a Str vector together with a separator; split(str, sep) is its inverse, and split(s, "") is every character.
  • replaceFirst and replaceAll rewrite one occurrence or every one, answering with a new string.
  • indexOf finds the first equal element — or, in a Str, the first occurrence, counted in characters — as a Result, whose Ok position is always safe to index with.
  • map, filter, filterMap and sort walk a vector, on the next slide; row, column and toTable are for tables, and spawn, at and kill for services, and hide, bypass and reveal for secrets, each on its own slide.

A builtin is only ever called: several are overloaded, so a bare len or a partial join(_, ",") is not a value — wrap it in a func of your own. Its arguments may be named like any call's, with the names above — join(sep: ", ", vector: fruit) — where an overloaded position answers to each of its names, so len(str: s) and len(vector: v) are both len.

A declaration of your own — a func, proc, query or type sharing one of these names — wins at every bare call, and the builtin stays reachable as hive.<name>.