Tin

Examples · 6 of 339

06-generics

Generics are monomorphised: Stack<int> and Stack<string> each compile to their own specialised WebAssembly, with no boxing and no runtime type checks.

examples/06-generics.tintin 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")