Tin

Examples · 26 of 339

26-traits

Traits: say what a generic function needs, and get the error at the call.

examples/26-traits.tintin 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