Tin

Examples · 13 of 339

13-bank

Structs with methods, and errors as ordinary values.

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"]