Tutorial: a word counter, from nothing to a native binary
Half an hour, one small program: wordcount prints the most frequent words of a file. On the way: a package, pure functions and their tests, a module, capabilities, and a native build. The finished project is in docs/tutorial/wordcount; a test builds and runs it, and checks every code block on this page is part of it.
You need the trine binary (README.md) and, for step 6, a C compiler (trine toolchain says which one it found).
1. A package
$ trine new wordcount
created wordcount (edition 1.0): `trine run wordcount/main.tr` or `trine test wordcount`
$ cd wordcount
$ trine run main.tr
hello from Trine
trine.toml names the package and its edition (COMPATIBILITY.md); main.tr is the program.
2. Pure functions first
Put the counting in its own file, counting.tr. First, the words of a text:
# the words of a text, lower case, without punctuation
pub fn words(text: Str) -> List[Str]:
let cleaned = join([if is_letter(c): lower(c) else: " " for c in text], "")
[w for w in split(cleaned, " ") if w != ""]
fn is_letter(c: Str) -> Bool:
let k = ord(lower(c))
(k >= ord("a") and k <= ord("z")) or c == "'"
No type annotations are needed inside a function: Trine infers them (trine check counting.tr prints every function's type). for c in text walks the characters; [... for ... in ... if ...] builds a list. pub makes words visible to files that import this one.
Then the tally: a map from word to count.
# how many times each word appears
pub fn tally(ws: List[Str]) -> Map[Str, Int]:
var counts = {}
for w in ws:
counts[w] = (get(counts, w) ?? 0) + 1
counts
var is a variable you can assign to; counts[w] = ... updates the map in place (it has one owner, so nothing is copied: FBIP.md). get gives an Option[Int], and ?? 0 takes 0 when the word isn't there yet.
3. Tests next to the code
test "words are lower case, without punctuation":
assert_eq(words("Hello, hello world!"), ["hello", "hello", "world"])
test "tally counts each word":
let t = tally(["a", "b", "a"])
assert_eq(t["a"], 2)
assert_eq(t["b"], 1)
$ trine test
test counting.tr: words are lower case, without punctuation ... ok
test counting.tr: tally counts each word ... ok
A failing test shows its output, the failed check (assertion failed: 1 != 2) and the call stack (TESTING.md).
4. Records and sorting
The top words, as records: a Count holds a word and its count.
pub type Count = Count(word: Str, n: Int)
# the n most frequent words, the most frequent first (ties alphabetically)
pub fn top(counts: Map[Str, Int], n: Int) -> List[Count]:
let all = sort_by([Count(word: w, n: counts[w]) for w in keys(counts)], fn(c) => (-c.n, c.word))
all[:min(n, len(all))]
sort_by sorts by a key; a tuple key sorts by its first part, then the next.
5. The outside world, by permission
Now main.tr: it imports the module and reads files. A Trine program can't touch a file unless it is handed a capability for a directory, and it gets one only for directories you grant when you run it.
import "counting.tr"
fn report(d: Dir, file: Str) -> Result[Unit, Str]:
let text = read_file(d, file)?
let ws = counting.words(text)
print(f"{file}: {len(ws)} words, {len(counting.tally(ws))} different")
for c in counting.top(counting.tally(ws), 5):
print(f"{c.n:>4} {c.word}")
Ok(())
report can read files in the directory it is given, and nothing else: that's in its type (Dir). read_file gives a Result; ? returns the error if there is one.
fn main(sys):
let files = args(sys)
if len(files) == 0:
eprint("usage: wordcount FILE...")
exit(2)
match dir(sys, "."):
Err(e) =>
eprint(e)
exit(1)
Ok(d) =>
for f in files:
match report(d, f):
Ok(_) => print("")
Err(e) => eprint(f"{f}: {e}")
$ trine run main.tr -- sample.txt
no permission for '.' (run with --allow-read=. or --allow-write=.)
$ trine run main.tr --allow-read=. -- sample.txt
sample.txt: 27 words, 14 different
6 the
3 on
3 sat
2 cat
2 dog
trine caps main.tr lists what every function can reach: the counting module can't reach the outside world at all, report reads files in a directory it's given, and only main holds the system capability.
6. A native binary
$ trine build main.tr -o wordcount
$ ./wordcount --allow-read=. sample.txt
The same program, compiled through C: the same output, much faster on big files. (trine run also compiles in the background and uses the native build from the second run on.)
Where next
- TOUR.md: sixteen short programs, one feature each.
- GALLERY.md: every example in the repository, by topic.
- CARD.md: the whole language on one page; SPEC.md decides the details.
- EDITOR.md: the language server, for types and ownership hints as you type.