Sn Tin

Chapter 2 of 8

Structs and sum types

Data is described with type. A sum type lists every shape a value can take, and match must handle all of them. Every value is copied, never shared.

examples/03-shapes.tintin 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

Delete the Triangle arm in area() and the compiler names the shape you forgot.

Methods are ordinary functions declared on a type: fn Account.deposit(…) is called as account.deposit(50). There are no classes and no inheritance.

examples/13-bank.tintin 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"]

Arrays and structs are values, like numbers. Assigning, passing or capturing one gives you your own copy, and only a var can change in place. A function changes its caller's variable only when the parameter says inout and the call says &arm, so nothing changes behind your back, and every mutation is visible where it happens.

examples/15-values.tintin 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