Cookbook

Complete programs for everyday jobs. Every example here is compiled by the build, so they stay correct as the language changes. Copy one into the playground and change it.

Count the words in some text

A map keeps a count for each word. in asks whether a key is already there.

fn word_counts(text) -> map:
    counts = {}
    for raw in text.lower().split():
        word = raw.trim()
        if word in counts:
            counts[word] += 1
        else:
            counts[word] = 1
    return counts

fn main() needs print:
    counts = word_counts("the cat and the hat and the bat")
    pairs = []
    for word in counts.keys():
        pairs.push([word, counts[word]])
    for p in pairs.sort_by(p -> 0 - p[1]):
        print("{p[0]}: {p[1]}")

Try it in the playground →

the: 3
and: 2
cat: 1
hat: 1
bat: 1

Read lines of data, and survive the bad ones

Parsing can fail, so parse_row returns a result. The ? hands a failure straight back to the caller, and the loop decides what to do with each one. Nothing throws.

record Row:
    name: text
    score: num

fn parse_row(line) -> result:
    parts = line.split(",")
    if parts.len() != 2:
        return err("bad line: {line}")
    score = to_int(parts[1].trim())?
    return ok(Row(name: parts[0].trim(), score: score))

fn main() needs print:
    text = "ada, 90\nbob, 72\ncy, x\n"
    total = 0
    for line in text.lines():
        r = parse_row(line)
        if r.is_ok():
            row = r.unwrap()
            total += row.score
            print("{row.name} -> {row.score}")
        else:
            print("skipped: {r}")
    print("total {total}")

Try it in the playground →

ada -> 90
bob -> 72
skipped: err("'x' is not a whole number")
total 162

To read the data from a file instead, call read("scores.csv")? inside a function that declares needs read, and run with --allow read.

A bank account that can't go wrong

Methods return a new account, or an err explaining why not. Because a failed step returns early with ?, a transfer can never take money out and fail to put it in.

record Account:
    owner: text
    balance: num

    fn deposit(self, amount: num) -> result:
        if amount <= 0:
            return err("deposit must be positive")
        return ok(Account(owner: self.owner, balance: self.balance + amount))

    fn withdraw(self, amount: num) -> result:
        if amount > self.balance:
            return err("insufficient funds: have {self.balance}, need {amount}")
        return ok(Account(owner: self.owner, balance: self.balance - amount))

fn transfer(from_acct: Account, to_acct: Account, amount: num) -> result:
    a = from_acct.withdraw(amount)?
    b = to_acct.deposit(amount)?
    return ok([a, b])

fn main() needs print:
    ada = Account(owner: "Ada", balance: 100)
    bob = Account(owner: "Bob", balance: 20)
    done = transfer(ada, bob, 30).unwrap()
    print(done[0].balance, done[1].balance)
    print(transfer(bob, ada, 500))

Try it in the playground →

70 50
err("insufficient funds: have 20, need 500")

A secret message (Caesar cipher)

ord turns a character into its code and chr turns a code back into a character.

fn shift(ch, k):
    code = ord(ch)
    if code >= 97 and code <= 122:
        return chr((code - 97 + k) % 26 + 97)
    return ch

fn caesar(text, k):
    out = ""
    for ch in text:
        out += shift(ch, k)
    return out

fn main() needs print:
    secret = caesar("hello, world", 3)
    print(secret)
    print(caesar(secret, 23))

Try it in the playground →

khoor, zruog
hello, world
fn binary_search(items, target):
    lo = 0
    hi = items.len() - 1
    while lo <= hi:
        mid = floor((lo + hi) / 2)
        if items[mid] == target:
            return mid
        elif items[mid] < target:
            lo = mid + 1
        else:
            hi = mid - 1
    return -1

fn main() needs print:
    xs = [1, 3, 5, 7, 9, 11]
    print(binary_search(xs, 7), binary_search(xs, 4))

Try it in the playground →

A state machine with an enum

Add a state later and every match that forgot it is refused before the program runs. That is the point of using an enum instead of text like "red".

enum Light:
    Red
    Green
    Yellow

fn next(l: Light) -> Light:
    match l:
        Red: return Light.Green
        Green: return Light.Yellow
        Yellow: return Light.Red

fn name(l: Light) -> text:
    match l:
        Red: return "red"
        Green: return "green"
        Yellow: return "yellow"

fn main() needs print:
    l = Light.Red
    for i in range(5):
        print(name(l))
        l = next(l)

Try it in the playground →

Prime numbers

fn sieve(n):
    flags = []
    for i in range(n + 1):
        flags.push(true)
    primes = []
    for i in range(2, n + 1):
        if flags[i]:
            primes.push(i)
            j = i * i
            while j <= n:
                flags[j] = false
                j += i
    return primes

fn main() needs print:
    print(sieve(30))

Try it in the playground →

Fast Fibonacci with a cache

A map remembers answers already worked out, so each one is computed once.

fn fib(n, memo):
    if n < 2:
        return n
    if n in memo:
        return memo[n]
    v = fib(n - 1, memo) + fib(n - 2, memo)
    memo[n] = v
    return v

fn main() needs print:
    print(fib(50, {}))

Try it in the playground →

A simulation you can repeat exactly

rng(seed) needs no permission, and the same seed always gives the same numbers, so a surprising result can be reproduced. See Simulations.

fn coin_flips(seed, count):
    dice = rng(seed)
    heads = 0
    for i in range(count):
        if dice.chance(0.5):
            heads += 1
    return heads

fn main() needs print:
    print(coin_flips(2026, 1000) == coin_flips(2026, 1000))

Try it in the playground →

A calculator that reads text

This turns text like (1 + 2) * 3 into a number, written entirely in Cresset. It shows enums with match, a record that holds the parser's position, and results with ? carrying every failure (a bad character, a missing bracket, dividing by zero) back to the caller without a single crash.

enum Token:
    Number(value: num)
    Op(symbol: text)
    Open
    Close

fn tokenize(text) -> result:
    tokens = []
    i = 0
    chars = text.chars()
    while i < chars.len():
        ch = chars[i]
        if ch == " ":
            i += 1
        elif ch.is_digit():
            digits = ""
            while i < chars.len() and (chars[i].is_digit() or chars[i] == "."):
                digits += chars[i]
                i += 1
            tokens.push(Token.Number(value: to_float(digits)?))
        elif ch in ["+", "-", "*", "/"]:
            tokens.push(Token.Op(symbol: ch))
            i += 1
        elif ch == "(":
            tokens.push(Token.Open)
            i += 1
        elif ch == ")":
            tokens.push(Token.Close)
            i += 1
        else:
            return err("unexpected character '{ch}'")
    return ok(tokens)

record Parser:
    tokens: list
    pos: num

fn peek(p: Parser):
    if p.pos < p.tokens.len():
        return p.tokens[p.pos]
    return none

fn parse_atom(p: Parser) -> result:
    t = peek(p)
    if t == none:
        return err("unexpected end")
    p.pos += 1
    match t:
        Number(value):
            return ok(value)
        Open:
            v = parse_expr(p)?
            c = peek(p)
            if c == none or c != Token.Close:
                return err("missing )")
            p.pos += 1
            return ok(v)
        Op(symbol):
            if symbol == "-":
                v = parse_atom(p)?
                return ok(0 - v)
            return err("unexpected {symbol}")
        Close:
            return err("unexpected )")

fn parse_term(p: Parser) -> result:
    left = parse_atom(p)?
    while true:
        t = peek(p)
        if t == none:
            break
        is_mul = false
        is_div = false
        match t:
            Op(symbol):
                is_mul = symbol == "*"
                is_div = symbol == "/"
            _:
                pass
        if not is_mul and not is_div:
            break
        p.pos += 1
        right = parse_atom(p)?
        if is_mul:
            left = left * right
        else:
            if right == 0:
                return err("division by zero")
            left = left / right
    return ok(left)

fn parse_expr(p: Parser) -> result:
    left = parse_term(p)?
    while true:
        t = peek(p)
        if t == none:
            break
        is_add = false
        is_sub = false
        match t:
            Op(symbol):
                is_add = symbol == "+"
                is_sub = symbol == "-"
            _:
                pass
        if not is_add and not is_sub:
            break
        p.pos += 1
        right = parse_term(p)?
        if is_add:
            left = left + right
        else:
            left = left - right
    return ok(left)

fn calc(text) -> result:
    tokens = tokenize(text)?
    p = Parser(tokens: tokens, pos: 0)
    v = parse_expr(p)?
    if p.pos != tokens.len():
        return err("unexpected input after the expression")
    return ok(v)

fn main() needs print:
    for e in ["1 + 2 * 3", "(1 + 2) * 3", "10 / 4 - 1", "-(2 + 3) * 2", "1 / 0", "(1 + 2"]:
        print("{e} = {calc(e)}")

Try it in the playground →

1 + 2 * 3 = ok(7)
(1 + 2) * 3 = ok(9)
10 / 4 - 1 = ok(1.5)
-(2 + 3) * 2 = ok(-10)
1 / 0 = err("division by zero")
(1 + 2 = err("missing )")

Shortest path: a word ladder

Change one letter at a time to get from one word to another. A list used as a queue, and a map to remember what has been seen, are all a breadth-first search needs.

fn neighbors(word, words):
    out = []
    for w in words:
        if w.len() != word.len():
            continue
        diff = 0
        for i in range(word.len()):
            if word[i] != w[i]:
                diff += 1
        if diff == 1:
            out.push(w)
    return out

fn ladder(start, goal, words):
    queue = [[start]]
    seen = {start: true}
    while queue.len() > 0:
        path = queue.remove_at(0)
        last = path[path.len() - 1]
        if last == goal:
            return ok(path)
        for n in neighbors(last, words):
            if not seen.has(n):
                seen[n] = true
                queue.push(path + [n])
    return err("no ladder from {start} to {goal}")

fn main() needs print:
    words = ["hot", "dot", "dog", "lot", "log", "cog", "hit", "cot"]
    print(ladder("hit", "cog", words))
    print(ladder("hit", "xyz", words))

Try it in the playground →

ok(["hit", "hot", "cot", "cog"])
err("no ladder from hit to xyz")

A cache that forgets the oldest thing

A record can hold its own data and the methods that change it. This keeps at most capacity items, and when it is full, drops the one used least recently.

record Cache:
    capacity: num
    order: list
    data: map

    fn get(self, key):
        if not self.data.has(key):
            return none
        self.order = self.order.filter(k -> k != key)
        self.order.push(key)
        return self.data[key]

    fn put(self, key, value):
        if self.data.has(key):
            self.order = self.order.filter(k -> k != key)
        elif self.order.len() >= self.capacity:
            oldest = self.order.remove_at(0)
            self.data.remove(oldest)
        self.data[key] = value
        self.order.push(key)

fn main() needs print:
    c = Cache(capacity: 2, order: [], data: {})
    c.put("a", 1)
    c.put("b", 2)
    print(c.get("a"))
    c.put("c", 3)
    print(c.get("b"), c.get("a"), c.get("c"), c.order)

Try it in the playground →

1
none 1 3 ["a", "c"]

Test it as you go

Put checks next to the code, and run them with cresset test. See Testing.

fn average(items):
    if items.len() == 0:
        return 0
    return items.sum() / items.len()

test "average of some numbers":
    assert_eq(average([2, 4, 6]), 4)

test "average of nothing is zero":
    assert_eq(average([]), 0)

fn main() needs print:
    print(average([10, 20]))

Try it in the playground →

Next

Every function and method in one place: Reference.