13. Where to go next
You have now seen all of Tern: values and types, control flow, functions, structs, arrays and maps, strings, enums, the value rules with mut and &, closures, parallelism, and modules. This last chapter puts everything together in one complete program, then points you to the rest of the documentation, depending on what you want to build.
A complete program
This program reads a small warehouse log, applies it to an inventory, and prints a report. It uses almost every feature from the tour: structs and an enum for the data, match to apply events, mut to update the inventory in place, a map to index items by SKU, string parsing for the input, a parallel: block for two independent summaries, closures with filter and sort_by, and the fmt module for the table.
import fmt
struct Item:
sku: str
name: str
qty: int
cents: int
enum Event:
Received(sku: str, n: int)
Shipped(sku: str, n: int)
Bad(line: str)
fn parse(line: str) Event:
parts = line.split(" ")
n = -1
if len(parts) == 3:
n = parts[2].to_int(-1)
if n < 0:
return Event.Bad(line)
match parts[0]:
"in":
return Event.Received(parts[1], n)
"out":
return Event.Shipped(parts[1], n)
_:
return Event.Bad(line)
fn apply(items: mut [Item], index: {str: int}, e: Event) str:
match e:
Received(sku, n):
if not (sku in index):
return "unknown sku " + sku
items[index[sku]].qty += n
Shipped(sku, n):
if not (sku in index):
return "unknown sku " + sku
i = index[sku]
if items[i].qty < n:
return f"only {items[i].qty} of {sku} left, can't ship {n}"
items[i].qty -= n
Bad(line):
return "can't read: " + line
return ""
fn value(items: [Item]) int:
t = 0
for it in items:
t += it.qty * it.cents
return t
fn main():
items = [Item("A1", "lamp", 4, 2500), Item("B2", "rope", 12, 899), Item("C3", "tent", 1, 15900)]
index: {str: int} = {}
for i, it in items:
index[it.sku] = i
log = "in A1 6\nout B2 10\nout C3 2\nin Z9 1\nout A1 x\nout C3 1"
problems: [str] = []
for line in log.split("\n"):
msg = apply(&items, index, parse(line))
if msg != "":
problems.push(msg)
parallel:
total = value(items)
low = items.filter(fn(it) it.qty < 3).map(fn(it) it.name)
for it in items.sort_by(fn(it) -it.qty * it.cents):
cost = fmt.cents(it.qty * it.cents)
print(fmt.pad_right(it.name, 6, " ") + fmt.pad_left(str(it.qty), 4, " ") + fmt.pad_left(cost, 10, " "))
print("total $" + fmt.cents(total), "| low stock:", ", ".join(low))
for p in problems:
print("warning:", p)lamp 10 250.00
rope 2 17.98
tent 0 0.00
total $267.98 | low stock: rope, tent
warning: only 1 of C3 left, can't ship 2
warning: unknown sku Z9
warning: can't read: out A1 xThings to notice:
applytakesitemsasmutandindexread-only, so the callapply(&items, index, ...)tells you exactly what can change.- Errors are ordinary values:
parsereturns aBadvariant andapplyreturns a message. Nothing is thrown, and thematchinapplymust handleBad. - The two tasks in the
parallel:block only readitems, so the compiler accepts them. - Items are found by SKU through a map of indexes into the array, the usual Tern way to "point" at something.
Try it
Extend the program: add a Price(sku: str, cents: int) event, written price A1 2750 in the log, that changes an item's price. The compiler will point at the match in apply until you handle the new variant. Then add a second report line with the most valuable item.
The rest of the documentation
Guides explain one topic in depth:
- Coming from Python, Go, Rust, or JavaScript: a translation table for your habits, and the mistakes people make most often.
- How memory works: copy-on-write, ownership, and why there is no garbage collector.
- Parallel programming: more patterns for
parallelandparallel for, and how the race checker thinks. - Performance tips: how to write fast Tern, and how to measure.
- Building web apps: HTTP servers, JSON, and SQLite.
- Calling C, and Tern as a library:
externblocks,ptr, andbuild --lib. - WebAssembly and JavaScript and iOS and Android: other targets.
- Cookbook: short recipes for everyday tasks.
The standard library is small and documented module by module, starting from the overview: fmt, math, random, time, os, fs, json, sqlite, and http.
Reference pages are for looking things up:
- Language reference: the complete, precise description of the language, with a table of what Tern has instead of features from other languages. You can also print it with
tern guide, or one topic withtern guide maps. - Builtin functions: every function available without an import.
- Grammar: the exact syntax, in EBNF.
- Compiler errors: what each error message means and how to fix it.
- Command line: every
terncommand and flag.
Some small projects to try
- A word-frequency counter: read a file with
fs.read, split it into words, count them in a map, and print the top 10 withsort_by. - A to-do list on the command line: store tasks as JSON with
json.encodeandjson.decode, and take commands fromos.args(). - A Mandelbrot or Game of Life renderer that prints ASCII art, then speed it up with
parallel forover the rows. - A small JSON API with
httpandsqlite, following the web apps guide.
Whatever you build, run tern check often. The compiler's messages, and their hints, are the fastest teacher Tern has.
Back to the start: 1. Getting started.