Cookbook
Short, complete programs for everyday tasks: files, text, collections, sorting, maps, formatting, JSON, and a few classic data structures. Each recipe is a whole program you can copy into a file and run with tern run file.tn; the output shown under it is what it prints. The recipes stick to the standard library that ships with Tern.
Read a file line by line
fs.read returns the whole file as one string (or "" if it can't be read), and split("\n") turns it into lines. A file that ends with a newline gives an empty last piece, so skip empty lines or trim() the text first.
import fs
fn main():
path = "/tmp/tern_cookbook_lines.txt"
fs.write(path, "first line\nsecond line\n\nfourth line\n")
if not fs.exists(path):
print("missing file")
return
for i, line in fs.read(path).split("\n"):
if line == "":
continue
print(f"{i + 1}: {line}")
fs.remove(path)1: first line
2: second line
4: fourth lineWrite and append to a file
fs.write replaces the file; fs.append adds to the end. Both return false when the file can't be written, so check the result.
import fs
fn main():
path = "/tmp/tern_cookbook_log.txt"
if not fs.write(path, "started\n"):
print("can't write", path)
return
for i in 1..4:
fs.append(path, f"step {i} done\n")
print(fs.read(path).trim())
fs.remove(path)started
step 1 done
step 2 done
step 3 doneParse CSV
Split the text into lines, then each line into columns. Store rows in a struct so the rest of the program works with named, typed fields. (This handles simple CSV without quoted commas.)
struct Sale:
region: str
product: str
units: int
price: float
fn parse_sales(text: str) [Sale]:
out: [Sale] = []
for i, line in text.trim().split("\n"):
if i == 0:
continue # the header row
cols = line.split(",")
if len(cols) != 4:
continue # skip malformed rows
out.push(Sale(cols[0].trim(), cols[1].trim(), cols[2].to_int(0), cols[3].to_float(0.0)))
return out
fn main():
text = "region,product,units,price\nnorth,widget,10,2.5\nsouth,gadget,3,10.0\nbad row\nnorth,gadget,1,10.0\n"
sales = parse_sales(text)
revenue = 0.0
for s in sales:
revenue += float(s.units) * s.price
print(len(sales), "rows, revenue", revenue)
print(sales[0])3 rows, revenue 65.0
Sale{region: "north", product: "widget", units: 10, price: 2.5}Command-line arguments
os.args() returns the program name followed by its arguments. Pass arguments after -- when using tern run: tern run greet.tn -- ada 3.
import os
fn main():
args = os.args()
if len(args) < 3:
print("usage: greet NAME TIMES")
os.exit(0)
times = args[2].to_int(-1)
if times < 1:
print("TIMES must be a positive number, not", args[2])
os.exit(1)
for i in 0..times:
print("hello,", args[1])usage: greet NAME TIMESRun without arguments (as above) it prints the usage line. Use os.exit(1) for errors so scripts and shells can tell that the program failed.
Count words
A map from word to count, filled with get(key, 0) + 1. Maps keep insertion order, so sort the keys by count to find the most common words.
fn main():
text = "the cat sat on the mat the end"
counts: {str: int} = {}
for w in text.split(" "):
if w != "":
counts[w] = counts.get(w, 0) + 1
print(counts)
top = counts.keys().sort_by(fn(w) -counts[w])
for w in top[..2]:
print(w, counts[w]){"the": 3, "cat": 1, "sat": 1, "on": 1, "mat": 1, "end": 1}
the 3
cat 1sort_by is stable, so words with the same count stay in the order they first appeared.
Remove duplicates from an array
Keep a map of what you have seen. There is no set type; a {str: bool} map works as one.
fn dedupe(xs: [str]) [str]:
seen: {str: bool} = {}
out: [str] = []
for x in xs:
if not (x in seen):
seen[x] = true
out.push(x)
return out
fn main():
tags = ["go", "rust", "go", "tern", "rust", "c"]
print(dedupe(tags))["go", "rust", "tern", "c"]This keeps the first occurrence of each value and the original order.
Reverse an array or a string
xs.reversed() returns a reversed copy of an array. For a string, build a new one; to walk an array backwards without copying it, use a while loop, since for ranges only count up.
fn reversed_str(s: str) str:
out = ""
for ch in s:
out = ch + out
return out
fn main():
print([1, 2, 3, 4].reversed(), reversed_str("stressed"))
xs = [10, 20, 30]
i = len(xs) - 1
while i >= 0:
print(xs[i])
i -= 1[4, 3, 2, 1] desserts
30
20
10reversed_str works byte by byte, which is right for ASCII text. Reversing UTF-8 text character by character needs more care.
Sort structs by several keys
sort_by sorts by one key and is stable. To sort by several keys, sort by the least important key first and the most important last. Negate a number to sort it descending.
struct Player:
name: str
team: str
score: int
fn main():
players = [
Player("dee", "red", 12),
Player("ada", "blue", 30),
Player("cy", "red", 30),
Player("bob", "blue", 12),
Player("eve", "red", 30),
]
# by team (A-Z), then score (high first), then name (A-Z)
by_name = players.sort_by(fn(p) p.name)
by_score = by_name.sort_by(fn(p) -p.score)
ranked = by_score.sort_by(fn(p) p.team)
for p in ranked:
print(p.team, p.score, p.name)blue 30 ada
blue 12 bob
red 30 cy
red 30 eve
red 12 deeGroup items into a map of arrays
Create the array the first time a key appears, then push onto groups[key]. The push changes the array inside the map in place.
struct Order:
customer: str
item: str
fn main():
orders = [Order("ada", "tea"), Order("bob", "cake"), Order("ada", "scone"), Order("cy", "tea")]
by_customer: {str: [str]} = {}
for o in orders:
if not (o.customer in by_customer):
by_customer[o.customer] = []
by_customer[o.customer].push(o.item)
for name, items in by_customer:
print(name, items)ada ["tea", "scone"]
bob ["cake"]
cy ["tea"]Count with a map
Counting by a computed key works the same way as counting words. Here, requests are counted by status class and the counts summed afterwards.
fn main():
statuses = [200, 404, 200, 500, 301, 200, 404]
by_class: {str: int} = {}
for s in statuses:
key = f"{s / 100}xx"
by_class[key] = by_class.get(key, 0) + 1
total = 0
for k, n in by_class:
print(k, n)
total += n
print("total", total)2xx 3
4xx 2
5xx 1
3xx 1
total 7Build a string efficiently
Appending with += is fast: a string that only this variable holds grows in place, like a string builder in other languages. For a list of pieces with separators, join is simplest.
fn main():
out = ""
for i in 0..5:
out += str(i * i)
out += ";"
print(out)
parts: [str] = []
for word in ["alpha", "beta", "gamma"]:
parts.push(word.upper())
print(", ".join(parts))
print("-" * 20)0;1;4;9;16;
ALPHA, BETA, GAMMA
--------------------Parse integers safely
s.to_int(default) returns default when s isn't a whole number. When every int is a valid answer, parse twice with two different defaults: only a bad string gets both.
struct ParsedInt:
ok: bool
value: int
fn parse_int(s: str) ParsedInt:
t = s.trim()
a = t.to_int(0)
b = t.to_int(1)
if a != b:
return ParsedInt(false, 0) # neither parse worked: not a number
return ParsedInt(true, a)
fn main():
for s in ["42", " -7 ", "0", "3.5", "abc", ""]:
p = parse_int(s)
if p.ok:
print(f"[{s}] -> {p.value}")
else:
print(f"[{s}] is not a whole number")[42] -> 42
[ -7 ] -> -7
[0] -> 0
[3.5] is not a whole number
[abc] is not a whole number
[] is not a whole numberto_int doesn't skip spaces, so trim() input from users and files first.
Format money, decimals, and padding
F-strings have no format specs. The fmt module has the common ones. Keep money in whole cents (an int) so sums are exact, and format with fmt.cents at the end.
import fmt
struct Line:
item: str
cents: int
qty: int
fn main():
lines = [Line("coffee", 350, 2), Line("bagel", 275, 1), Line("juice", 1_250, 12)]
total = 0
for l in lines:
amount = l.cents * l.qty
total += amount
print(fmt.pad_right(l.item, 8, " ") + fmt.pad_left(str(l.qty), 3, " ") + fmt.pad_left(fmt.cents(amount), 9, " "))
print(fmt.pad_right("total", 11, " ") + fmt.pad_left(fmt.cents(total), 9, " "))
print(fmt.fixed(2.0 / 3.0, 3), fmt.thousands(1_234_567), "#" + fmt.zero_pad(42, 5))coffee 2 7.00
bagel 1 2.75
juice 12 150.00
total 159.75
0.667 1,234,567 #00042Read and write JSON config
json.decode fills an existing value. Keys missing from the JSON keep the value you started with, so start from the defaults. On bad JSON it returns false and changes nothing.
import json
struct Config:
name: str
port: int
debug: bool
admins: [str]
fn default_config() Config:
return Config("app", 8080, false, [])
fn main():
cfg = default_config()
if not json.decode(`{"port": 9000, "admins": ["ada"]}`, &cfg):
print("bad config")
print(cfg)
print(json.encode(cfg))
broken = default_config()
print(json.decode(`{"port": "not a number"}`, &broken), broken.port)Config{name: "app", port: 9000, debug: false, admins: ["ada"]}
{"name":"app","port":9000,"debug":false,"admins":["ada"]}
false 8080In a real program the text comes from fs.read("config.json"), and fs.write saves json.encode(cfg) back.
Binary search
On a sorted array, halve the range until the value is found. Return -1 when it isn't there.
fn search(xs: [int], want: int) int:
lo = 0
hi = len(xs) # search xs[lo..hi]
while lo < hi:
mid = (lo + hi) / 2
if xs[mid] == want:
return mid
if xs[mid] < want:
lo = mid + 1
else:
hi = mid
return -1
fn main():
xs = [2, 3, 5, 7, 11, 13, 17, 19]
print(search(xs, 13), search(xs, 2), search(xs, 4))5 0 -1Stack and queue
An array is a stack: push and pop work at the end. For a queue, keep a read index instead of removing from the front, which would copy the rest of the array each time.
fn main():
stack: [str] = []
stack.push("a")
stack.push("b")
stack.push("c")
while len(stack) > 0:
print("pop", stack.pop())
queue: [str] = []
head = 0 # the next item to take
queue.push("job1")
queue.push("job2")
while head < len(queue):
job = queue[head]
head += 1
print("run", job)
if job == "job1":
queue.push("job3") # work can add more workpop c
pop b
pop a
run job1
run job2
run job3Breadth-first search on a graph
Tern has no pointers, so nodes refer to each other by index into an array. BFS finds the fewest hops from one node to every other.
struct City:
name: str
roads: [int] # indexes into the cities array
fn hops_from(cities: [City], start: int) [int]:
dist = [-1] * len(cities)
dist[start] = 0
queue = [start]
head = 0
while head < len(queue):
c = queue[head]
head += 1
for next in cities[c].roads:
if dist[next] == -1:
dist[next] = dist[c] + 1
queue.push(next)
return dist
fn main():
cities = [City("oslo", [1, 2]), City("bergen", [3]), City("trondheim", [3]), City("tromso", []), City("island", [])]
dist = hops_from(cities, 0)
for i, c in cities:
if dist[i] < 0:
print(c.name, "unreachable")
else:
print(c.name, dist[i])oslo 0
bergen 1
trondheim 1
tromso 2
island unreachableA tree as an enum
Enums can contain themselves, so a binary search tree is an enum with an empty case and a node case. Inserting returns a new tree; there are no pointers to update.
enum Tree:
Leaf
Node(left: Tree, key: int, right: Tree)
fn insert(t: Tree, k: int) Tree:
match t:
Leaf:
return Tree.Node(Tree.Leaf, k, Tree.Leaf)
Node(l, key, r):
if k < key:
return Tree.Node(insert(l, k), key, r)
if k > key:
return Tree.Node(l, key, insert(r, k))
return t
fn in_order(t: Tree, out: mut [int]):
match t:
Leaf:
pass
Node(l, key, r):
in_order(l, &out)
out.push(key)
in_order(r, &out)
fn depth(t: Tree) int:
match t:
Leaf:
return 0
Node(l, _, r):
return 1 + max(depth(l), depth(r))
fn main():
t = Tree.Leaf
for k in [50, 30, 70, 20, 40, 60, 30]:
t = insert(t, k)
keys: [int] = []
in_order(t, &keys)
print(keys, "depth", depth(t))[20, 30, 40, 50, 60, 70] depth 3A state machine with an enum and match
Model each state as an enum variant, and write one function that takes the current state and an event and returns the next state.
enum Door:
Open
Closed
Locked(code: str)
fn step(d: Door, event: str, arg: str) Door:
match d:
Open:
if event == "close":
return Door.Closed
Closed:
if event == "open":
return Door.Open
if event == "lock":
return Door.Locked(arg)
Locked(code):
if event == "unlock" and arg == code:
return Door.Closed
return d # anything else: no change
fn name(d: Door) str:
match d:
Open:
return "open"
Closed:
return "closed"
Locked(_):
return "locked"
fn main():
d = Door.Open
events = [["close", ""], ["lock", "1234"], ["open", ""], ["unlock", "0000"], ["unlock", "1234"], ["open", ""]]
for e in events:
d = step(d, e[0], e[1])
print(f"{e[0]} -> {name(d)}")close -> closed
lock -> locked
open -> locked
unlock -> locked
unlock -> closed
open -> openShuffle an array
The Fisher-Yates shuffle swaps each position with a random earlier one. random.int(lo, hi) includes both ends. The output differs on every run, so this example prints only facts that don't change.
import random
fn shuffle(xs: mut [int]):
i = len(xs) - 1
while i > 0:
j = random.int(0, i)
tmp = xs[i]
xs[i] = xs[j]
xs[j] = tmp
i -= 1
fn main():
deck: [int] = []
for i in 1..11:
deck.push(i)
shuffle(&deck)
print(len(deck), "cards")
print("same cards:", deck.sort_by(fn(x) x))10 cards
same cards: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]random is fast but not for cryptography: don't use it for passwords or tokens.
Time a piece of code
time.now_ms() is wall-clock milliseconds. Read it before and after, and subtract. Run the work more than once, since the first run can include warm-up costs.
import time
fn count_primes(n: int) int:
count = 0
for i in 2..n:
prime = true
d = 2
while d * d <= i:
if i % d == 0:
prime = false
break
d += 1
if prime:
count += 1
return count
fn main():
start = time.now_ms()
n = count_primes(100_000)
elapsed = time.now_ms() - start
print(n, "primes")
if elapsed >= 0:
print("timed ok") # print elapsed itself in real code: f"{elapsed} ms"9592 primes
timed okRetry with backoff
Loop a fixed number of times, wait a little longer after each failure, and stop as soon as the operation works. Here the "operation" fails twice before succeeding.
import time
fn fetch(attempt: int) bool:
return attempt >= 3 # stands in for a flaky network call
fn main():
ok = false
wait_ms = 1
for attempt in 1..6:
if fetch(attempt):
print("succeeded on attempt", attempt)
ok = true
break
print("attempt", attempt, "failed; waiting", wait_ms, "ms")
time.sleep(wait_ms)
wait_ms *= 2
if not ok:
print("gave up")attempt 1 failed; waiting 1 ms
attempt 2 failed; waiting 2 ms
succeeded on attempt 3Simple text templates
Replace {{name}} placeholders with values from a map. Braces are ordinary characters in a normal string; only f-strings treat them specially.
fn render(template: str, vars: {str: str}) str:
out = template
for k, v in vars:
out = out.replace("{{" + k + "}}", v)
return out
fn main():
t = "Hello {{name}}, your order #{{id}} ships {{when}}."
print(render(t, {"name": "Ada", "id": "1042", "when": "today"}))
print(render(t, {"name": "Bob"}))Hello Ada, your order #1042 ships today.
Hello Bob, your order #{{id}} ships {{when}}.Placeholders with no value are left as they are, which makes missing values easy to spot.