Sn Tin

Reference

Standard library

Every function and type available without an import, generated from the library source.

Nothing here needs an import. The library is written in Tin and compiled together with your program; only the functions you use end up in the .wasm file. The 137 signatures below are read from the library source when this page is built.

Any function can be called as a method on its first argument: xs.map(f) is map(xs, f), and text.trim() is string.trim(text). A name like string.slice or Array.slice says which type the method belongs to, which is how two types can share a method name.

Built in

These are part of the compiler, because they work on every type or have no ordinary signature.

print(value)

Writes any value, then a line break. print() writes an empty line.

write(value)

Writes any value without a line break.

str(value): string

Any value as text, the same text print and "{value}" produce.

int(x): int

A float truncated toward zero, or a bool as 0 or 1.

float(x): float

An int as a float.

exit(code: int)

Stops the program with this exit status. Like panic it never returns, and a tool or task cannot catch it. Code an agent writes cannot call it.

panic(message: string)

Stops the program with a message. Inside a tool, the message goes back to the model as a failed call.

xs.len, text.len

The number of items in an array, or bytes in a string. A field, not a call.

xs.push(item)

Adds an item to the end of an array. Needs a var.

xs.pop()

Removes and returns the last item. Panics on an empty array. Needs a var.

task.stop()

Stops a task and every task it started. They end at their next pause.

task.done(), task.stopped()

Whether a task has finished or been stopped, and whether it was stopped.

PI

3.141592653589793

var xs = [3, 1, 2]
xs.push(9)
print("{xs.len} items, last was {xs.pop()}")
print(str(1.5) + " " + str(true) + " " + str([Some(1), None]))
print(int(2.9) + int(true))
4 items, last was 9
1.5 true [Some(1), None]
3

Option and Result types

type Option<T> = Some(T) | None

A value that may be missing. Tin has no null.

type Result<T, E> = Ok(T) | Err(E)

The outcome of something that can fail. Tin has no exceptions.

type AgentError = TurnLimit(int) | OverBudget(int) | Refused(string) | Cut | NoAnswer | Failed(string)

Why an agent call gave no answer, from A.try(prompt).

Traits the standard library uses as bounds

trait Ord { fn compare(a: Self, b: Self): int }

Values with an order. `compare(a, b)` is negative when a comes first, 0 when equal, positive after. A type with `compare` gets < > <= >=, sort, min and max.

trait Show { fn show(x: Self): string }

Values that can be shown as text. Every type has a derived `show`; write `fn T.show` to replace it.

trait Eq { fn equals(a: Self, b: Self): bool }

Values that can be compared with ==. Derived from the parts; write `fn T.equals` to replace it.

Strings

Strings are immutable UTF-8. Positions and len count bytes, so a character outside ASCII takes more than one.

fn string.byteAt(s: string, i: int): int

The byte at position i, from 0 to 255. Panics if i is out of range.

fn string.slice(s: string, from: int, to: int): string

The bytes from `from` up to, but not including, `to`. Positions past either end are clamped.

fn string.charAt(s: string, i: int): string

The one-byte string at position i, or "" past the end.

fn string.chars(s: string): char[]

The characters, decoded from UTF-8: "añ".chars() is ['a', 'ñ'].

let line = "  name: Ada Lovelace  "
let parts = line.trim().split(": ")
print(parts[1].upper())
print(parts[1].split(" ").map(w => w.slice(0, 1)).join("."))
print("{parts[0].padRight(8, ".")}{parts[1].len}")
print(parseInt("42").or(0) + 1)
ADA LOVELACE
A.L
name....12
43

Formatting support

fn fromChars(cs: char[]): string

A string made of these characters: fromChars(['h', 'i']) is "hi".

fn char.isDigit(c: char): bool
fn char.isLetter(c: char): bool

ASCII a-z and A-Z, and any character outside ASCII that is not a space.

fn char.isSpace(c: char): bool
fn char.isUpper(c: char): bool
fn char.isLower(c: char): bool
fn char.upper(c: char): char

ASCII upper case; other characters stay as they are.

fn char.lower(c: char): char

ASCII lower case; other characters stay as they are.

fn char.compare(a: char, b: char): int
fn string.indexOf(s: string, sub: string): int

Where sub first occurs, or -1 if it does not.

fn string.contains(s: string, sub: string): bool

Whether sub occurs anywhere in s.

fn string.startsWith(s: string, prefix: string): bool

Whether s begins with prefix.

fn string.endsWith(s: string, suffix: string): bool

Whether s ends with suffix.

fn string.isEmpty(s: string): bool

Whether s has no bytes.

fn string.split(s: string, sep: string): string[]

The pieces of s between occurrences of sep. An empty sep splits into single bytes.

fn string.trim(s: string): string

s without spaces, tabs and line breaks at either end.

fn string.upper(s: string): string

s with ASCII letters in upper case. Other characters are unchanged.

fn string.lower(s: string): string

s with ASCII letters in lower case. Other characters are unchanged.

fn string.repeat(s: string, times: int): string

s repeated `times` times.

fn string.replace(s: string, from: string, to: string): string

s with every occurrence of `from` replaced by `to`.

fn string.padLeft(s: string, width: int, fill: string): string

s with `fill` added on the left until it is at least `width` bytes.

fn string.padRight(s: string, width: int, fill: string): string

s with `fill` added on the right until it is at least `width` bytes.

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

The strings of `parts` with `sep` between them.

fn parseInt(s: string): Option<int>

The integer written in s (decimal, with an optional sign), or None if s is anything else.

fn parseFloat(s: string): Option<float>

The number written in s, or None.

Arrays

These return new arrays and leave the original as it was.

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

A new array with f applied to every item.

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

A new array with the items for which `keep` is true.

fn reduce<T, A>(xs: T[], init: A, f: (A, T) => A): A

Folds the array into one value: starts from `init` and combines it with each item in turn.

fn each<T>(xs: T[], f: (T) => void)

Calls f for every item.

fn sum<T>(xs: T[]): T

All items added together. Works on numbers, durations and strings.

fn count<T>(xs: T[], pred: (T) => bool): int

How many items satisfy `pred`.

fn any<T>(xs: T[], pred: (T) => bool): bool

Whether at least one item satisfies `pred`. Stops at the first that does.

fn all<T>(xs: T[], pred: (T) => bool): bool

Whether every item satisfies `pred`. Stops at the first that does not.

fn find<T>(xs: T[], pred: (T) => bool): Option<T>

The first item that satisfies `pred`, or None.

fn range(from: int, to: int): int[]

The integers from `from` up to, but not including, `to`.

fn first<T>(xs: T[]): Option<T>

The first item, or None for an empty array.

fn last<T>(xs: T[]): Option<T>

The last item, or None for an empty array.

fn Array.slice<T>(xs: T[], from: int, to: int): T[]

A new array with the items from `from` up to, but not including, `to`. Positions past either end are clamped.

fn Array.reverse<T>(xs: T[]): T[]

A new array with the items in reverse order.

fn Array.concat<T>(xs: T[], ys: T[]): T[]

A new array with the items of xs followed by those of ys.

fn Array.indexOf<T: Eq>(xs: T[], item: T): int

Where `item` first occurs, or -1. Uses ==, so it works on numbers, strings and bools.

fn Array.contains<T: Eq>(xs: T[], item: T): bool

Whether `item` occurs in xs.

fn Array.isEmpty<T>(xs: T[]): bool

Whether xs has no items.

fn filled<T>(n: int, value: T): T[]

A new array of n items, each a copy of value: filled(1000000, false). Panics if n is negative.

fn sort<T: Ord>(xs: T[]): T[]

A new array in ascending order (the Ord order): numbers, strings, durations and any type with `compare`; NaN sorts last. Stable (equal items keep their order), O(n log n) on every input.

fn sortBy<T>(xs: T[], less: (T, T) => bool): T[]

A new array ordered by `less`, which returns true when its first argument should come first. Stable, O(n log n).

let scores = [72, 95, 58, 88]
print(scores.filter(s => s >= 70).map(s => s / 10))
print(sort(scores).reverse().slice(0, 2))
print(scores.reduce(0, (best, s) => max(best, s)))
print(scores.find(s => s < 60))
print("{sum(scores)} over {scores.len}, any perfect: {scores.any(s => s == 100)}")
[7, 9, 8]
[95, 88]
95
Some(58)
313 over 4, any perfect: false

Option and Result

fn Option.isSome<T>(o: Option<T>): bool

Whether the option holds a value.

fn Option.isNone<T>(o: Option<T>): bool

Whether the option is empty.

fn Option.or<T>(o: Option<T>, fallback: T): T

The value inside, or `fallback` if there is none.

fn Option.unwrap<T>(o: Option<T>): T

The value inside. Panics on None, so use it only when None would be a bug.

fn Result.isOk<T, E>(r: Result<T, E>): bool

Whether the result is a success.

fn Result.isErr<T, E>(r: Result<T, E>): bool

Whether the result is a failure.

fn Result.or<T, E>(r: Result<T, E>, fallback: T): T

The success value, or `fallback` on failure.

fn Result.unwrap<T, E>(r: Result<T, E>): T

The success value. Panics on Err, so use it only when failure would be a bug.

Map

type Set<T> = { }

A set of distinct values, in the order they were first added. Built on Map, so lookups hash.

type Map<K, V> = { }

An insertion-ordered hash map: `get`, `set` and `has` take constant time on average (from 8 entries on; smaller maps are scanned). Keys are compared with `==`; a type with its own `equals` should also define `hash` (an `int` that is equal for equal keys), or lookups fall back to a scan. `m[k]` reads (panics if k is missing) and `m[k] = v` sets. `for k, v in m` walks it in insertion order; `keys()`, `values()` and `entries()` copy it out.

fn newMap<K, V>(): Map<K, V>

An empty map. The key and value types come from the annotation: `var m: Map<string, int> = newMap()`.

fn Map.set<K, V>(m: inout Map<K, V>, key: K, value: V)

Stores `value` under `key`, replacing any earlier value. Changes the map, so it needs a `var`.

fn Map.get<K, V>(m: Map<K, V>, key: K): Option<V>

The value stored under `key`, or None.

fn Map.at<K, V>(m: Map<K, V>, key: K): V

The value stored under `key`; panics if there is none. `m[key]` is the same, and `m[key] = v` is `m.set(key, v)`.

fn Map.has<K, V>(m: Map<K, V>, key: K): bool

Whether `key` is present.

fn Map.size<K, V>(m: Map<K, V>): int

How many keys the map holds.

fn Map.keys<K, V>(m: Map<K, V>): K[]

The keys, in the order they were first set (a new array).

fn Map.values<K, V>(m: Map<K, V>): V[]

The values, in the same order as keys() (a new array).

fn Map.entries<K, V>(m: Map<K, V>): ()<K, V>[]

(key, value) pairs in insertion order.

fn Map.getOr<K, V>(m: Map<K, V>, key: K, fallback: V): V

The value for key, or fallback.

fn Map.remove<K, V>(m: inout Map<K, V>, key: K): Option<V>

Removes key and gives back its value, or None. Keeps the order of the rest; takes time in the size of the map.

fn mapOf<K, V>(pairs: ()<K, V>[]): Map<K, V>

A map holding these (key, value) pairs; a later pair replaces an earlier one with the same key.

fn newSet<T>(): Set<T>
fn setOf<T>(xs: T[]): Set<T>

A set holding these values.

fn Set.add<T>(s: inout Set<T>, x: T)

Adds x; adding it again changes nothing.

fn Set.has<T>(s: Set<T>, x: T): bool
fn Set.remove<T>(s: inout Set<T>, x: T): bool

Removes x; gives whether it was there.

fn Set.size<T>(s: Set<T>): int
fn Set.values<T>(s: Set<T>): T[]

The values in the order they were added (a new array).

fn Set.union<T>(a: Set<T>, b: Set<T>): Set<T>

The values in both sets.

fn Set.intersect<T>(a: Set<T>, b: Set<T>): Set<T>

The values of a that are also in b.

var stock: Map<string, int> = newMap()
stock.set("tea", 4)
stock.set("coffee", 0)
stock.set("tea", stock.get("tea").or(0) + 1)
stock["milk"] = 2                      // the same as stock.set("milk", 2)
stock["milk"] += 1
print(stock["milk"])                   // panics if the key is missing; get gives an Option
print("{stock.get("tea")} {stock.get("milk")} {stock.has("coffee")} {stock.size()}")
print(stock.keys())
for item, n in stock { print("{item}: {n}") }
var seen = setOf(["tea", "tea", "jam"])
seen.add("bun")
print("{seen} {seen.has("jam")} {seen.size()}")
3
Some(5) Some(3) true 3
["tea", "coffee", "milk"]
tea: 5
coffee: 0
milk: 3
{"tea", "jam", "bun"} true 3

Numbers

fn min<T: Ord>(a: T, b: T): T

The smaller of two values (the Ord order). For floats NaN counts as largest, so min(NaN, 1.0) is 1.0.

fn max<T: Ord>(a: T, b: T): T

The larger of two values (the Ord order). For floats NaN counts as largest, so max(NaN, 1.0) is NaN.

fn int.compare(a: int, b: int): int
fn i64.compare(a: i64, b: i64): int
fn float.compare(a: float, b: float): int

A total order: NaN equals NaN and comes after every number; -0.0 equals 0.0.

fn string.compare(a: string, b: string): int
fn Duration.compare(a: Duration, b: Duration): int
fn Frequency.compare(a: Frequency, b: Frequency): int
fn abs<T>(x: T): T

The absolute value of an int or a float.

fn sqrt(x: float): float

The square root.

fn floor(x: float): float

The largest whole number not above x.

fn ceil(x: float): float

The smallest whole number not below x.

fn round(x: float): float

The nearest whole number; halves round up.

fn pow(base: float, exponent: float): float

`base` raised to `exponent`.

fn sin(x: float): float

Sine of an angle in radians.

fn cos(x: float): float

Cosine of an angle in radians.

fn tan(x: float): float

Tangent of an angle in radians.

fn exp(x: float): float

e raised to x.

fn ln(x: float): float

The natural logarithm.

fn float.fixed(x: float, digits: int): string

x as text with exactly `digits` decimals: (3.14159).fixed(2) is "3.14".

fn random(): float

A random float, at least 0 and below 1.

fn randomInt(from: int, to: int): int

A random integer from `from` up to, but not including, `to`.

Time, io

fn now(): Duration

The time since the program started.

fn sleep(time: Duration)

Pauses this task for `time`. Other tasks keep running.

fn within<T>(t: Task<T>, limit: Duration): Option<T>

Waits at most `limit` for a task. Some(result) if it finishes in time; otherwise the task and everything it started are stopped, and the answer is None.

fn input(prompt: string): string

Shows `prompt` and reads one line from the user.

fn env(name: string): string

The value of an environment variable, or "" if it is not set.

fn args(): string[]

The command-line arguments: `tin run f.tin a b` gives ["a", "b"]; everything after `--` too. Empty in a browser.

fn fetch(url: string): Result<string, string>

The body of an HTTP GET as text, or an Err with the reason it failed.

fn assertEq<T>(actual: T, expected: T)

Panics unless the two values print the same, showing both. Works on every type; made for tests.

fn assert(condition: bool, message: string)

Panics with `message` when `condition` is false.

let started = now()
sleep(20ms)
print(now() - started >= 20ms)
print(env("TIN_NO_SUCH_VARIABLE").isEmpty())
true
true

Talking agents (speech to speech)

type VoiceEvent = Connected(string) | Speech(Audio) | Hearing(string) | Heard(string) | Saying(string) | Said(string) | Wrote(string) | CallingTool { name: string, input: string } | ToolReturned { name: string, output: string, ok: bool } | BargedIn | TurnDone | TokensUsed { input: int, output: int } | RestartSoon(int) | Reconnected { reason: string, interrupted: bool } | HungUp(string)

What a live session reports, in order. \`s.next()\` waits for the next one.

type Session = { handle: int }

One live conversation with a \`voice agent\`, from \`A.open()\`.

type AudioOut = { handle: int }

Where sound goes: \`speaker()\`, or a file/pipe given with \`tin run --speaker\`.

type AudioIn = { handle: int }

Where sound comes from: \`mic()\`, or a file/pipe given with \`tin run --mic\`.

type Audio = { handle: int }

A piece of sound: 16-bit mono PCM held by the host, not copied into the program's memory.

fn mic(): AudioIn

The microphone (or the \`--mic\` file). Needs the \`mic\` capability.

fn speaker(): AudioOut

The speaker (or the \`--speaker\` file). Needs the \`speaker\` capability.

fn AudioIn.read(i: AudioIn): Option<Audio>

The next chunk of input, or None when the input has ended.

fn AudioOut.play(o: AudioOut, a: Audio)
fn AudioOut.clear(o: AudioOut)

Drop everything queued but not yet played (what a barge-in does).

fn Audio.seconds(a: Audio): float
fn Audio.rate(a: Audio): int
fn Audio.level(a: Audio): float

Loudness from 0.0 (silence) to 1.0 (root mean square).

fn Audio.show(a: Audio): string
fn tone(pitch: Frequency, length: Duration): Audio

A sine tone: \`tone(440Hz, 200ms)\`.

fn silence(length: Duration): Audio
fn Session.say(s: Session, text: string)

Send a user message as text.

fn Session.send(s: Session, a: Audio)

Stream a chunk of audio to the model.

fn Session.next(s: Session): VoiceEvent

Wait for the next event. After the session ends it is HungUp, again and again.

fn Session.interrupt(s: Session)

Cancel the reply being spoken.

fn Session.stop(s: Session)
fn Session.save(s: Session): string

The conversation so far, as JSON (the shape \`A.save()\` gives).