Tern

Builtin functions

Builtins are the functions that are part of the language: they need no import, and their names are reserved. This page lists every one with its signature, what it does, the errors it can cause (at compile time and at run time), and a tested example. It starts with the rule that lets you call any function as a method.

Method calls: x.f(a) is f(x, a)

Any function, builtin or your own, can be called with its first argument in front: s.upper() is upper(s), xs.sort_by(fn(x) x) is sort_by(xs, fn(x) x), and "-".join(parts) is join("-", parts). The two spellings are the same call; use whichever reads better. If the first parameter is mut, the method form passes it with & for you: xs.push(v) is push(&xs, v).

struct Circle:
    r: float

fn area(c: Circle) float:
    return 3.14159 * c.r * c.r

fn grow(c: mut Circle, by: float):
    c.r += by

fn main():
    c = Circle(1.0)
    c.grow(1.0)                   # grow(&c, 1.0)
    print(c.area(), area(c))      # the same call twice
    print("a-b".split("-"), split("a-b", "-"), len("abc"), "abc".len())
Output
12.56636 12.56636
["a", "b"] ["a", "b"] 3 3

For a value whose type comes from a module, x.f also looks in that module: d.exec(sql, params) calls sqlite.exec(d, sql, params) because d is a sqlite.Db.

The signatures below use T, K, and V for "any type" (an element type, a map's key and value types). Your own functions can be generic too: fn first[T](xs: [T]) T (see the reference, §7).

Your functions with builtin names

print len push pop chr copy float int sqrt abs sum min max str join split find contains
starts_with ends_with replace trim upper lower to_int to_float byte repeat get remove
keys values is_null map filter sort_by reversed url_decode json_quote to_bytes to_str reserve
resize_uninit

A function of your own may have one of these names. A call goes to yours when its first parameter fits the first argument (and the argument count matches), and to the builtin otherwise; so find on a string still means the builtin here:

fn find(xs: [int], v: int) int:
    for i, x in xs:
        if x == v:
            return i
    return -1

fn main():
    print(find([1, 2], 2), [5, 6].find(6), "hello".find("l"))
Output
1 1 2

Functions in an extern block and export fn functions can't have a builtin's name: C sees their names.

Output

print

fn print(values...)

Prints its arguments to standard output, separated by single spaces, then a newline. It takes any number of values of any type, including arrays, maps, structs, and enums.

  • Strings print as they are at the top level, and in double quotes inside arrays, maps, and structs.
  • Floats always show a decimal point or an exponent (2.0, 1e+20) and use the shortest text that reads back as the same number (0.1 + 0.2 prints 0.30000000000000004).
  • Structs print as Name{field: value, ...}, enums as Enum.Variant or Enum.Variant(field: value), maps as {key: value, ...}.
  • There is no end= or sep=: build the line as a string, then print it. print() with no arguments prints an empty line.

Output is buffered and flushed when the program ends (also by os.exit). There is no builtin for printing to standard error.

struct Point:
    x, y: int

enum Shape:
    Circle(r: float)
    Empty

fn main():
    print("total", 3, 2.0, 0.1 + 0.2, true)
    print(["a", "b"], {"k": 1}, Point(1, 2), Shape.Circle(1.5), Shape.Empty)
    print()
    print("a" + "," + "b")
Output
total 3 2.0 0.30000000000000004 true
["a", "b"] {"k": 1} Point{x: 1, y: 2} Shape.Circle(r: 1.5) Shape.Empty

a,b

Numbers and conversions

len

fn len(s: str) int
fn len(xs: [T]) int
fn len(m: {K: V}) int

The length of a string in bytes, the number of elements in an array, or the number of entries in a map. It takes constant time. Any other type is a compile error.

fn main():
    print(len("hello"), len("héllo"), len([1, 2, 3]), len({"a": 1}), len(""))
Output
5 6 3 1 0

"héllo" is six bytes because é takes two bytes in UTF-8.

int

fn int(x: float) int

Converts a float to an int by cutting off the fraction (rounding toward zero): int(2.9) is 2 and int(-2.9) is -2. To round instead, use int(math.round(x)) or int(math.floor(x)) (see math). The result for NaN, infinity, or a value outside the int range is unspecified. int(b) of a byte gives its value. int of anything else is a compile error; to parse a string, use to_int.

float

fn float(n: int) float

Converts an int (or a byte or an f32) to a float. Ints above 2<sup>53</sup> (about 9 × 10<sup>15</sup>) may be rounded to the nearest float. float of anything else is a compile error.

fn main():
    n = 7
    avg = float(n) / 2.0
    print(avg, int(avg), int(-2.9), float(3))
Output
3.5 3 -2 3.0

f32

fn f32(x: float) f32
fn f32(n: int) f32

Rounds a float (or an int) to the nearest f32, the 32-bit float: about 7 significant digits, up to about 3.4 × 10<sup>38</sup> (larger is inf). float(x) widens it back exactly.

fn main():
    x = f32(0.1)
    print(x, float(x), f32(16777217), f32(1e39), f32(3) / 2.0)
Output
0.1 0.10000000149011612 16777216.0 inf 1.5

str

fn str(x: int) str
fn str(x: float) str
fn str(x: bool) str
fn str(x: str) str

The text of a number or a bool, written the same way print writes it: str(42) is "42", str(2.0) is "2.0", str(true) is "true". Arrays, maps, structs, and enums are a compile error; use json.encode(x) for text, or print to show them.

fn main():
    n = 42
    print("n=" + str(n), str(2.5) + "!", str(1.0 / 3.0), str(100000000000000000000.0), str(false))
Output
n=42 2.5! 0.3333333333333333 1e+20 false

F-strings convert the same way: f"n={n}" equals "n=" + str(n).

abs

fn abs(x: int) int
fn abs(x: float) float

The absolute value. The result has the argument's type. abs of the most negative int (-9223372036854775808) is itself, since the positive value doesn't fit.

min, max

fn min(a: int, b: int) int
fn min(a: float, b: float) float
fn min(xs: [int]) int
fn min(xs: [float]) float
fn max(...)                     # the same four forms

The smaller or larger of two numbers of the same type (mixing int and float is a compile error), or the smallest or largest element of an array of numbers. An empty array is a runtime error, max() of an empty array: check len(xs) > 0 first. In a float array, NaN elements are skipped.

fn main():
    scores = [70, 95, 82]
    print(max(3, 8), min(2.5, 1.0), max(scores), scores.min(), max(scores.map(fn(s) s / 10)))
Output
8 1.0 95 70 9

sqrt

fn sqrt(x: float) float

The square root, the same as math.sqrt without the import. It takes a float only: write sqrt(float(n)). The square root of a negative number is NaN.

fn main():
    print(abs(-3), abs(-2.5), min(3, 4), max(1.5, 0.5), sqrt(2.0), sqrt(float(16)))
    scores = [72, 95, 88]
    best = scores[0]
    for s in scores:
        best = max(best, s)
    print(best)
Output
3 2.5 3 1.5 1.4142135623730951 4.0
95

chr

fn chr(n: int) str

A one-byte string whose byte value is n: chr(65) is "A". n must be 0 to 255; any other value is a runtime error. Bytes 128 to 255 are not characters on their own in UTF-8: chr(233) is not "é". The reverse is s.byte(i).

fn main():
    word = ""
    for code in [84, 101, 114, 110]:
        word += chr(code)
    print(word, "A".byte(0), chr(97 + 2), chr(0x41) == "A")
Output
Tern 65 c true

copy

fn copy(x: T) T

An explicit copy of any value. Assignment already copies (b = a), so copy is only needed where a value would otherwise be moved: when passing it to a take parameter or to push (below) while still using it afterwards. Copies are lazy, so copy itself is cheap; the real copy happens only if one side is later changed.

Arrays

push

fn push(xs: mut [T], v: T)

Adds v to the end of xs; write xs.push(v). Adding is amortized constant time.

push copies v into the array, the way = does: the copy is lazy (the two share storage until one is written), and when v is a variable that isn't used afterwards, its value moves in without even that.

fn main():
    names: [str] = []
    name = "ada"
    names.push(name)
    name += "!"
    print(name, names)
Output
ada! ["ada"]

Compile errors: pushing a value of the wrong type (argument 2 of push should be int, not str), and pushing onto the array a for loop is iterating over.

pop

fn pop(xs: mut [T]) T

Removes the last element of xs and returns it; write xs.pop(). On an empty array it is a runtime error: pop() from an empty array. Check len(xs) > 0 first. There is no way to remove from the front or the middle in place; slice (xs[1..]) or filter instead.

fn main():
    stack: [str] = []
    stack.push("a")
    stack.push("b")
    word = "c"
    stack.push(word)
    print(stack, word)
    top = stack.pop()
    print(top, stack)
    while len(stack) > 0:
        print("popped", stack.pop())
Output
["a", "b", "c"] c
c ["a", "b"]
popped b
popped a

reserve

fn reserve(xs: mut [T], n: int)
fn reserve(s: mut str, n: int)

Makes room for n more elements (or bytes, for a string) in one block; write xs.reserve(n). Pushing (or +=) that many then doesn't grow and copy the array on the way: like Go's make([]T, 0, n) or Rust's Vec::with_capacity. The contents don't change, and when there is room already it does nothing. Reserving far more than you use costs memory.

fn main():
    squares: [int] = []
    squares.reserve(1000)
    for i in 0..1000:
        squares.push(i * i)
    print(len(squares), squares[999])
Output
1000 998001

Compile errors: reserve() makes room in a str or an array (s.reserve(n)), not int.

resize_uninit

fn resize_uninit(xs: mut [int], n: int)      # also [float], [f32], [byte]

Makes xs exactly n elements long without writing the new ones; write xs.resize_uninit(n). Growing keeps the elements already there; shrinking drops the end. The new elements' contents are undefined until written: they hold whatever the memory held, which may be another array's old data, so write every one before reading it. It is for big arrays that are filled completely right after (by a loop, or by C code), where [0] * n would first clear the memory: one pass over it less, and pages not touched before they're needed. Only arrays of plain numbers: arrays of strings, structs, or other arrays must start with values.

fn squares(n: int) [int]:
    out: [int] = []
    out.resize_uninit(n)            # n elements, not cleared
    for i in 0..n:
        out[i] = i * i              # every one written before it is read
    return out

fn main():
    xs = squares(1000)
    print(len(xs), xs[999])
Output
1000 998001

Compile errors: resize_uninit() works on an array of plain numbers ([int], [float], [f32] or [byte]), not [str]: .... Runtime errors: resize_uninit() to a negative length, array too large (over 4 billion elements).

map

fn map(xs: [T], f: fn(T) U) [U]

A new array with f applied to each element, in order. f must return a value; the result's element type is whatever f returns. xs is not changed.

filter

fn filter(xs: [T], keep: fn(T) bool) [T]

A new array with the elements for which keep returns true, in their original order. keep must return bool.

sort_by

fn sort_by(xs: [T], key: fn(T) K) [T]          # K is int, float, or str

A new array sorted by the key key returns for each element, smallest first. xs itself is not changed. The sort is stable: elements with equal keys keep their original order, so you can sort by one key and then another. Strings compare by bytes, so uppercase sorts before lowercase ("B" < "a"); sort by w.lower() to ignore case. For descending order, negate a number key (fn(x) -x.score). A key of any other type is a compile error.

The function in map, filter, and sort_by is usually a lambda, whose parameter type is inferred from the array; a named function works too.

struct Player:
    name: str
    score: int

fn is_even(n: int) bool:
    return n % 2 == 0

fn main():
    nums = [5, 2, 8, 1]
    print(nums.map(fn(n) n * 10), nums.map(fn(n) f"#{n}"), nums.filter(is_even))
    print(nums.sort_by(fn(n) n), nums.sort_by(fn(n) -n), nums)
    players = [Player("cy", 30), Player("ada", 50), Player("bob", 30)]
    ranked = players.sort_by(fn(p) -p.score)
    print(ranked.map(fn(p) p.name))
    words = ["pear", "Fig", "apple"]
    print(words.sort_by(fn(w) w), words.sort_by(fn(w) w.lower()), words.sort_by(fn(w) len(w)))
    print(players.filter(fn(p) p.score > 40).map(fn(p) p.name))
Output
[50, 20, 80, 10] ["#5", "#2", "#8", "#1"] [2, 8]
[1, 2, 5, 8] [8, 5, 2, 1] [5, 2, 8, 1]
["ada", "cy", "bob"]
["Fig", "apple", "pear"] ["apple", "Fig", "pear"] ["Fig", "pear", "apple"]
["ada"]

sum

fn sum(xs: [int]) int
fn sum(xs: [float]) float

The elements added up, in order; 0 (or 0.0) for an empty array. Int sums wrap on overflow, like +. Any other element type is a compile error: sum() needs an array of numbers ([int], [float] or [f32]), not [str].

sorted, reversed

fn sorted(xs: [T]) [T]          # T is int, float, or str
fn reversed(xs: [T]) [T]

A sorted copy (smallest first) and a copy in reverse order. xs is not changed; to sort in place, write xs = xs.sorted(). For other orders, use sort_by. (sorted comes from the prelude rather than the language, so it isn't in the list of builtin names above; a function of yours named sorted takes its place.)

fn main():
    xs = [3, 1, 2]
    print(sum(xs), xs.sum(), sum([0.5, 1.25]), sum(xs.filter(fn(x) x > 5)))
    print(xs.sorted(), xs.reversed(), xs.sorted().reversed(), xs)
    print(["pear", "fig"].sorted())
Output
6 6 1.75 0
[1, 2, 3] [2, 1, 3] [3, 2, 1] [3, 1, 2]
["fig", "pear"]

Strings

Strings are UTF-8 bytes, and every position and length below counts bytes. For ASCII text that is the same as characters. None of these functions change the string they are called on: strings are values, and each function returns a new one.

find

fn find(s: str, sub: str) int

The byte index of the first occurrence of sub in s, or -1 if there is none. An empty sub is found at 0.

contains

fn contains(s: str, sub: str) bool

Whether sub occurs in s. Same as sub in s.

starts_with, ends_with

fn starts_with(s: str, prefix: str) bool
fn ends_with(s: str, suffix: str) bool

Whether s begins or ends with the given text. Every string starts and ends with "".

fn main():
    s = "report-2024.csv"
    print(s.find("-"), s.find("x"), s.find(""), s.contains("2024"), "csv" in s)
    print(s.starts_with("report"), s.ends_with(".csv"), s.ends_with(".CSV"))
    dot = s.find(".")
    print(s[..dot], s[dot + 1..])
Output
6 -1 0 true true
true true false
report-2024 csv

replace

fn replace(s: str, old: str, new: str) str

s with every non-overlapping occurrence of old replaced by new, scanning left to right. An empty old returns s unchanged.

trim

fn trim(s: str) str

s without leading and trailing spaces, tabs, \n, and \r. There is no left-only or right-only version.

upper, lower

fn upper(s: str) str
fn lower(s: str) str

s with ASCII letters changed to upper or lower case. Other bytes, including non-ASCII letters like é, are unchanged.

repeat

fn repeat(s: str, n: int) str

s repeated n times; "" if n is 0 or negative. s * n is the same.

fn main():
    print("a-b-c".replace("-", ", "), "aaa".replace("aa", "b"), "abc".replace("", "x"))
    print("[" + "  padded\t\n".trim() + "]", "Hello World".upper(), "ÉCOLE Tern".lower())
    print("ab".repeat(3), "-" * 10, "x".repeat(0) == "")
Output
a, b, c ba abc
[padded] HELLO WORLD École tern
ababab ---------- true

split

fn split(s: str, sep: str) [str]

The pieces of s between occurrences of sep. Empty pieces are kept, so len(s.split(sep)) is always one more than the number of separators, and "".split(",") is [""]. An empty sep splits into single bytes. There is no "split on any whitespace"; replace tabs and newlines with spaces first, and skip empty pieces.

join

fn join(sep: str, parts: [str]) str

The strings in parts with sep between them. It is called on the separator, like Python: ", ".join(names). Joining [] gives "".

fn main():
    print("a,b,,c".split(","), "".split(","), "abc".split(""), "no sep".split(","))
    print(" / ".join(["home", "docs"]), "".join(["a", "b"]), ",".join([]) == "")
    words: [str] = []
    for w in "  two   spaces ".split(" "):
        if w != "":
            words.push(w)
    print(words)
Output
["a", "b", "", "c"] [""] ["a", "b", "c"] ["no sep"]
home / docs ab true
["two", "spaces"]

to_int

fn to_int(s: str, default: int) int

s parsed as a whole number, or default if s isn't one. It accepts an optional + or - followed by decimal digits, and nothing else: no spaces (trim first), no _, no decimal point, no hex. Numbers too large for an int are not detected and wrap around, so limit the length of untrusted input.

to_float

fn to_float(s: str, default: float) float

s parsed as a number, or default if it isn't one. It accepts what C's strtod accepts: integers, decimals, exponents (1e3), leading whitespace, and also inf, nan, and hex floats (0x10), so check the result's range if the input is untrusted. Trailing text makes it fail.

fn main():
    print("42".to_int(0), "-7".to_int(0), "+5".to_int(0), " 42".to_int(-1), "4.0".to_int(-1), "1_000".to_int(-1))
    print("2.5".to_float(0.0), "3".to_float(0.0), "1e3".to_float(0.0), "12px".to_float(-1.0), "".to_float(-1.0))
    port = "8080x".to_int(-1)
    if port < 0:
        print("bad port")
Output
42 -7 5 -1 -1 -1
2.5 3.0 1000.0 -1.0 -1.0
bad port

byte

fn byte(n: int) byte
fn byte(s: str, i: int) int

byte(n) makes a byte from an int, keeping its low 8 bits: byte(300) is 44, byte(-1) is 255.

s.byte(i) is the byte at index i, as an int from 0 to 255. An index outside the string is a runtime error, as with s[i] (which gives a one-byte string instead of a number).

fn is_digit(c: int) bool:
    return c >= 48 and c <= 57            # "0" to "9"

fn main():
    s = "a1b22"
    digits = 0
    for i in 0..len(s):
        if is_digit(s.byte(i)):
            digits += 1
    print(digits, s.byte(0), "é".byte(0), "é".byte(1), s[1])
Output
3 97 195 169 1

to_bytes, to_str

fn to_bytes(s: str) [byte]
fn to_str(bs: [byte]) str

A string's bytes as a [byte], and back. Neither copies: a str and a [byte] are stored the same way, so both share the block until one of them is changed. to_str doesn't check that the bytes are valid UTF-8.

fn main():
    bs = "abc".to_bytes()
    for i in 0..len(bs):
        bs[i] = byte(bs[i] - 32)          # ASCII lowercase to uppercase
    print(bs, bs.to_str())
Output
[65, 66, 67] ABC

Maps

get

fn get(m: {K: V}, key: K, default: V) V

The value for key, or default if m has no such key. Reading m[key] for a missing key is a runtime error, so get is the safe way to read. The default is required.

remove

fn remove(m: mut {K: V}, key: K)

Deletes key and its value; write m.remove(key). Removing a key that isn't there does nothing. It returns nothing, so read the value first if you need it.

keys, values

fn keys(m: {K: V}) [K]
fn values(m: {K: V}) [V]

The map's keys, or values, as a new array, in insertion order (the order for k, v in m: uses). A key that is removed and added again moves to the end.

fn main():
    stock = {"apple": 3, "pear": 0}
    stock["fig"] = 12
    print(stock.get("apple", 0), stock.get("kiwi", 0), "kiwi" in stock)
    stock.remove("pear")
    stock.remove("kiwi")
    stock["apple"] = 5
    print(stock.keys(), stock.values(), len(stock))
    counts: {str: int} = {}
    for w in "the cat and the hat".split(" "):
        counts[w] = counts.get(w, 0) + 1
    print(counts)
Output
3 0 false
["apple", "fig"] [5, 12] 2
{"the": 2, "cat": 1, "and": 1, "hat": 1}

Common compile errors: calling these on something that isn't a map (get() works on maps, not [int]), a key or default of the wrong type, and leaving out get's default.

Web helpers

json_quote

fn json_quote(s: str) str

s as a JSON string literal, including the surrounding double quotes: ", \, and control characters are escaped, and other bytes are kept. It is the same as json.encode(s), for building JSON by hand without importing json.

url_decode

fn url_decode(s: str) str

s with URL encoding undone: + becomes a space and %XX (two hex digits) becomes that byte. A % not followed by two hex digits is kept as it is. req.query, req.form and http.match call it for you.

fn main():
    name = "Ada \"the first\"\n"
    print(`{"name": ` + json_quote(name) + "}")
    print(url_decode("caf%C3%A9+au+lait"), url_decode("100%25"), url_decode("50%"))
Output
{"name": "Ada \"the first\"\n"}
café au lait 100% 50%

C pointers

is_null

fn is_null(p: ptr) bool

Whether a C pointer is null. ptr is the opaque pointer type used with extern functions; see Calling C.

fn main():
    p: ptr = null
    print(p.is_null(), is_null(p))
Output
true true

Runtime errors

These builtins can stop a program at run time. The program prints runtime error in f (prog.tn:N): <message> to standard error and exits with status 2 (inside a web request handler, the request gets a 500 instead; see http):

CallMessage
xs.pop() on an empty arraypop() from an empty array
s.byte(i) with i out of rangeindex 5 out of bounds (length 3)
m[key] for a missing key (not a builtin, but common)key not found (use m.get(key, default) or `key in m`)

Everything else on this page either can't fail or reports failure through its result (find gives -1, to_int gives your default, get gives your default).

Source: docs/builtins.md. Every example on this page is compiled and run by tern x test docs.