A first hour with Trine

Sixteen short programs covering what people write in their first hour with a new language. Every program here is in [docs/tour/](tour/) and is checked by the test suite: it must produce exactly the output shown, on the interpreter, the ownership VM and native code.

Run one with trine run docs/tour/01_hello.tr. If you know Python, most of it will look familiar; the differences are listed at the end.

1. Hello

main is where a program starts. let names a value that never changes; var names one you can reassign. An f-string puts values into text with {...}, and {x:.2} shows two decimals.

fn main():
  let name = "Ada"
  var visits = 3
  visits = visits + 1
  print(f"Hello, {name}! Visit number {visits}.")
  let price = 19.99
  print(f"Total for 3: {price * 3.0:.2}")
Hello, Ada! Visit number 4.
Total for 3: 59.97

2. FizzBuzz

if/elif/else is an expression, so a function can simply end with one. range(1, 16) counts from 1 to 15. Lists are values: push(line, x) gives the list with x added, and assigning it back to line is updated in place, without a copy. x += 1 works as you'd expect.

fn fizzbuzz(n):
  if n % 15 == 0: "FizzBuzz"
  elif n % 3 == 0: "Fizz"
  elif n % 5 == 0: "Buzz"
  else: str(n)

fn main():
  var line = []
  for i in range(1, 16):
    line = push(line, fizzbuzz(i))
  print(join(line, " "))
  var total = 0
  for i in range(1, 101):
    if i % 3 == 0 or i % 5 == 0: total += i
  print(f"sum of multiples of 3 or 5 up to 100: {total}")
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz
sum of multiples of 3 or 5 up to 100: 2418

3. A table

Annotations are optional; here they document the function. range(a, b, step) takes a step, float(i) turns an Int into a Float (Trine never mixes them silently), and {x:>4} right-aligns in 4 columns (< left, ^ centre).

fn to_fahrenheit(c: Float) -> Float:
  c * 9.0 / 5.0 + 32.0

fn main():
  for c in range(-10, 41, 10):
    let f = to_fahrenheit(float(c))
    print(f"{c:>4} C = {round(f):>4} F")
 -10 C =   14 F
   0 C =   32 F
  10 C =   50 F
  20 C =   68 F
  30 C =   86 F
  40 C =  104 F

4. Counting words

A Map is written {} and indexed with m[key]. A list comprehension builds a list from a loop. Tuples group values; sort_by sorts by a key (here: most frequent first, then alphabetical), and a slice [:3] keeps the first three. for (word, n) in ... takes each tuple apart.

fn main():
  let text = "the quick brown fox jumps over the lazy dog the end"
  var counts = {}
  for word in split(text, " "):
    counts[word] = if word in counts: counts[word] + 1 else: 1
  let pairs = [(word, counts[word]) for word in counts]
  for (word, n) in sort_by(pairs, fn((w, n)) => (-n, w))[:3]:
    print(f"{word}: {n}")
the: 3
brown: 1
dog: 1

5. Loops

while, for, break and continue work as in Python. A one-line if can hold a return or a break.

fn is_prime(n):
  if n < 2: return false
  for d in range(2, n):
    if d * d > n: break
    if n % d == 0: return false
  true

fn main():
  var primes = []
  var n = 2
  while len(primes) < 10:
    if is_prime(n):
      primes = push(primes, n)
    n = n + 1
  print(primes)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

6. Fibonacci

(a, b) = (b, a + b) assigns both at once, for _ in repeats without naming the counter, and Ints are 64-bit (an overflow is an error, never a wrong answer).

fn fib(n):
  var (a, b) = (0, 1)
  for _ in range(n):
    (a, b) = (b, a + b)
  a

fn fib_slow(n):
  if n < 2: n else: fib_slow(n - 1) + fib_slow(n - 2)

fn main():
  print([fib(i) for i in range(10)])
  print(fib(90))
  print(fib_slow(20))
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
2880067194370816120
6765

7. Your own types

A type with | alternatives is a sum type, and match must handle every case (leave one out and the checker tells you which). A single-alternative type with named fields is a record: read fields with .x, and make a changed copy with .with(...). sum, min and max take a list.

type Shape =
  | Circle(r: Float)
  | Rect(w: Float, h: Float)

type Point = Point(x: Float, y: Float)

fn area(s: Shape) -> Float:
  match s:
    Circle(r) => PI * r * r
    Rect(w, h) => w * h

fn main():
  let shapes = [Circle(1.0), Rect(2.0, 3.0), Circle(0.5)]
  for s in shapes:
    print(f"{s} has area {area(s):.2}")
  let total = sum([area(s) for s in shapes])
  print(f"total: {total:.3}")
  let p = Point(x: 1.0, y: 2.0)
  let q = p.with(y: 5.0)
  print(f"{p} -> {q}, distance {hypot(q.x - p.x, q.y - p.y)}")
Circle(1.0) has area 3.14
Rect(2.0, 3.0) has area 6.00
Circle(0.5) has area 0.79
total: 9.927
Point(1.0, 2.0) -> Point(1.0, 5.0), distance 3.0

8. Missing values and errors

There is no null and there are no exceptions. A value that may be missing is an Option (Some(x) or None); an operation that may fail returns a Result (Ok(x) or Err(e)). ? unwraps a Some/Ok, or returns the None/Err from the function right away.

fn parse_pair(s: Str) -> Option[(Int, Int)]:
  let parts = split(s, ",")
  if len(parts) != 2: return None
  let a = parse_int(trim(parts[0]))?
  let b = parse_int(trim(parts[1]))?
  Some((a, b))

fn safe_div(a: Int, b: Int) -> Result[Int, Str]:
  if b == 0: Err("division by zero") else: Ok(a / b)

fn ratio(s: Str) -> Result[Int, Str]:
  match parse_pair(s):
    Some((a, b)) => safe_div(a, b)
    None => Err(f"can't read '{s}'")

fn main():
  for s in ["10, 2", "7,0", "x,1", "9"]:
    match ratio(s):
      Ok(v) => print(f"{s} -> {v}")
      Err(e) => print(f"{s} -> error: {e}")
10, 2 -> 5
7,0 -> error: division by zero
x,1 -> error: can't read 'x,1'
9 -> error: can't read '9'

9. A grid

Conway's Game of Life on a list of lists. enumerate pairs each element with its position, g[r][c] = x updates one cell (in place when nothing else shares the grid), and var next = g makes an independent copy: changing one never changes the other.

fn neighbours(g: List[List[Int]], r: Int, c: Int) -> Int:
  var n = 0
  for dr in range(-1, 2):
    for dc in range(-1, 2):
      if dr == 0 and dc == 0: continue
      let (rr, cc) = (r + dr, c + dc)
      if rr >= 0 and rr < len(g) and cc >= 0 and cc < len(g[0]):
        n = n + g[rr][cc]
  n

fn step(g: List[List[Int]]) -> List[List[Int]]:
  var next = g
  for (r, row) in enumerate(g):
    for (c, alive) in enumerate(row):
      let n = neighbours(g, r, c)
      next[r][c] = if n == 3 or (alive == 1 and n == 2): 1 else: 0
  next

fn show(g):
  for row in g:
    print(join([if x == 1: "#" else: "." for x in row], ""))

fn main():
  var g = [[0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [1, 1, 1, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
  for gen in range(3):
    print(f"generation {gen}:")
    show(g)
    g = step(g)
generation 0:
.#...
..#..
###..
.....
.....
generation 1:
.....
#.#..
.##..
.#...
.....
generation 2:
.....
..#..
#.#..
.##..
.....

10. Generators

A function declared with yields produces values one at a time with yield. It runs only as far as the loop that consumes it asks, so an endless generator is fine.

fn countdown(n: Int) yields Int:
  var i = n
  while i > 0:
    yield i
    i = i - 1

fn squares() yields Int:
  var i = 1
  while true:
    yield i * i
    i = i + 1

fn main():
  print([x for x in countdown(5)])
  for s in squares():
    if s > 50: break
    print(s)
[5, 4, 3, 2, 1]
1
4
9
16
25
36
49

11. Numbers

Float arithmetic, the math functions (sqrt, pow, sin, log, ...) and the constants PI, TAU and E. / on two Ints divides whole numbers; on Floats it is ordinary division.

fn mean(xs: List[Float]) -> Float:
  sum(xs) / float(len(xs))

fn stddev(xs: List[Float]) -> Float:
  let m = mean(xs)
  sqrt(sum([(x - m) * (x - m) for x in xs]) / float(len(xs)))

fn median(xs: List[Float]) -> Float:
  let s = sort(xs)
  let n = len(s)
  if n % 2 == 1: s[n / 2] else: (s[n / 2 - 1] + s[n / 2]) / 2.0

fn main():
  let data = [2.5, 3.1, 4.7, 1.2, 5.0, 3.3]
  print(f"n      = {len(data)}")
  print(f"mean   = {mean(data):.3}")
  print(f"median = {median(data):.3}")
  print(f"stddev = {stddev(data):.3}")
  print(f"range  = {min(data)} .. {max(data)}")
  print(f"circle of radius 2: {PI * pow(2.0, 2.0):.4}")
n      = 6
mean   = 3.300
median = 3.200
stddev = 1.287
range  = 1.2 .. 5.0
circle of radius 2: 12.5664

12. Text

Strings are UTF-8 and indexed by character: s[0], s[1:3] and len(s) count characters, not bytes. split, join, trim, lower, upper, replace, find and x in s cover most text work. print with several values separates them with spaces.

fn capitalize(w: Str) -> Str:
  if w == "": w else: upper(w[:1]) + w[1:]

fn is_palindrome(s: Str) -> Bool:
  let cs = [c for c in chars(lower(s)) if c != " "]
  cs == reverse(cs)

fn main():
  let title = "the art of computer programming"
  print(join([capitalize(w) for w in split(title, " ")], " "))
  for s in ["Never odd or even", "trine"]:
    print(f"{s:<20}|{is_palindrome(s)}")
  let csv = "name,age\nann,31\nbo,27"
  for (i, line) in enumerate(split(csv, "\n")[1:]):
    let fields = split(line, ",")
    print(f"{i + 1}. {fields[0]:>5} is {fields[1]}")
  print(replace("a-b-c", "-", "+"), len("héllo"), "ell" in "hello")
The Art Of Computer Programming
Never odd or even   |true
trine               |false
1.   ann is 31
2.    bo is 27
a+b+c 5 true

13. Files

A program can reach only what it is handed. main(sys) receives the system capability, and dir(sys, path) gives a directory only if the command line granted it (--allow-read=docs/tour). Without the flag, the program runs but is told no.

Run with trine run docs/tour/13_files.tr --allow-read=docs/tour.

# run with: --allow-read=docs/tour
fn count_lines(d: Dir, name: Str) -> Result[Int, Str]:
  let text = read_file(d, name)?
  Ok(len([line for line in split(text, "\n") if trim(line) != ""]))

fn main(sys):
  match dir(sys, "docs/tour"):
    Ok(d) =>
      match count_lines(d, "13_files.tr"):
        Ok(n) => print(f"this program has {n} non-empty lines")
        Err(e) => print(f"error: {e}")
    Err(e) => print(f"no access: {e}")
this program has 11 non-empty lines

14. Functions as values

fn(x) => ... is a lambda; functions can take and return functions. A map comprehension {k: v for ...} builds a Map, which keeps insertion order.

fn apply_twice(f, x):
  f(f(x))

fn make_adder(n: Int):
  fn(x) => x + n

fn main():
  let add3 = make_adder(3)
  print(apply_twice(add3, 10))
  let words = ["pear", "fig", "banana", "kiwi"]
  print(sort_by(words, fn(w) => len(w)))
  print(sort_by(words, fn(w) => (-len(w), w)))
  let lengths = {w: len(w) for w in words}
  print(lengths)
16
["fig", "pear", "kiwi", "banana"]
["banana", "kiwi", "pear", "fig"]
{"pear": 4, "fig": 3, "banana": 6, "kiwi": 4}

15. Reading input

read_line(sys) returns the next line of standard input, or None at the end. parse_int returns an Option, so bad input is handled where it happens.

Its input (the # input: line, which the test feeds to it):

# input: 12\n7\noops\n23\n
fn main(sys):
  var total = 0
  var count = 0
  while true:
    match read_line(sys):
      None => break
      Some(line) =>
        match parse_int(trim(line)):
          Some(n) =>
            total += n
            count += 1
          None => print(f"skipping '{trim(line)}'")
  print(f"{count} numbers, total {total}, average {float(total) / float(count):.2}")
skipping 'oops'
3 numbers, total 42, average 14.00

16. A Caesar cipher

for c in text loops over characters; ord and chr convert between a character and its code.

fn shift(c: Str, k: Int) -> Str:
  let code = ord(c)
  if code >= ord("a") and code <= ord("z"):
    chr((code - ord("a") + k) % 26 + ord("a"))
  elif code >= ord("A") and code <= ord("Z"):
    chr((code - ord("A") + k) % 26 + ord("A"))
  else:
    c

fn caesar(text: Str, k: Int) -> Str:
  join([shift(c, k) for c in text], "")

fn main():
  let secret = caesar("Hello, World!", 3)
  print(secret)
  print(caesar(secret, 23))
  var vowels = 0
  for c in lower("Programming Language"):
    if c in "aeiou": vowels += 1
  print(f"{vowels} vowels")
Khoor, Zruog!
Hello, World!
7 vowels

Coming from Python

Next: the language card for the whole language on one page, and the specification for the details.