Tin

Examples · py · 335 of 339

stats

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.

examples/py/stats.tintin 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))
}