Tern

10. Functions as values

Functions in Tern are values: you can store them in variables, pass them to other functions, return them, and keep them in struct fields and arrays. This chapter covers lambdas (fn(x) x * 2), nested functions, function types, and how closures capture variables, then puts map, filter, and sort_by to real use.

Lambdas

A lambda is a small unnamed function: fn(parameters) expression. It has no : and no return; its body is one expression, and that expression's value is the result:

fn main():
    double = fn(x: int) x * 2
    shout = fn(s: str) s.upper() + "!"
    is_even = fn(n: int) n % 2 == 0
    print(double(21), shout("hey"), is_even(7))
Output
42 HEY! false

When the lambda is passed somewhere that already says the parameter types, you can leave them out. That is the common case with map, filter, and sort_by:

fn main():
    prices = [12, 5, 30, 8]
    print(prices.map(fn(p) p * 2))
    print(prices.filter(fn(p) p < 10))
    print(prices.sort_by(fn(p) p))
Output
[24, 10, 60, 16]
[5, 8]
[5, 8, 12, 30]

When nothing says the type, the compiler asks you to write it:

Does not compile
fn main():
    double = fn(x) x * 2
    print(double(3))
Compiler output
2: error: can't tell the type of parameter `x`; write `fn(x: int) ...`, or give the variable a type, e.g. `f: fn(int) int = ...`

Function types

The type of a function is written like its signature without names: fn(int) int takes an int and returns an int; fn(str, int) bool takes two values and returns a bool; fn(str) returns nothing. Use these types for parameters, return values, struct fields, and array elements:

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

fn make_multiplier(k: int) fn(int) int:
    return fn(x) x * k

fn main():
    triple = make_multiplier(3)
    print(triple(5), apply_twice(triple, 2))
    steps: [fn(int) int] = [fn(x) x + 1, fn(x) x * 10, make_multiplier(-1)]
    n = 4
    for step in steps:
        n = step(n)
    print(n)
Output
15 18
-50

make_multiplier returns a new function each time it is called, and each one remembers its own k. A function that remembers values from where it was created is called a closure.

Nested functions

A lambda is limited to one expression. For anything longer, define a named function inside another function. It can use the enclosing function's variables, can call itself, and can be passed by name like any other function:

fn main():
    min_len = 4
    fn label(word: str) str:
        if len(word) < min_len:
            return word + " (short)"
        return word + " (" + str(len(word)) + " letters)"
    words = ["fig", "banana", "kiwi"]
    for w in words.map(label):
        print(w)
    fn fib(n: int) int:
        if n < 2:
            return n
        return fib(n - 1) + fib(n - 2)
    print(fib(20))
Output
fig (short)
banana (6 letters)
kiwi (4 letters)
6765

Closures capture by copy

A closure copies the variables it uses at the moment it is created. Changing the variable afterwards does not affect the closure, and the closure can't change the variable:

fn main():
    rate = 10
    add_tax = fn(price: int) price + price * rate / 100
    rate = 50                                # too late: add_tax has its own copy
    print(add_tax(200))
Output
220

This is the same rule as everywhere else in Tern: values are copies. It means a closure can never change your variables behind your back, and a closure that is stored and called later (for example as a button's click handler) behaves the same no matter what happened in the meantime. Trying to change a captured variable is an error:

Does not compile
fn main():
    total = 0
    fn add(n: int):
        total += n
    add(3)
    print(total)
Compiler output
4: error: can't modify `total` here: this function has its own copy of it, made when the function was created (return a new value, or take it as a `mut` parameter)

The error names both fixes. Either return the new value and let the caller store it, or pass the variable in as a mut parameter:

fn main():
    total = 0
    fn add(t: mut int, n: int):
        t += n
    add(&total, 3)
    add(&total, 4)
    print(total)
    plus = fn(t: int, n: int) t + n
    total = plus(total, 10)
    print(total)
Output
7
17

In practice, most accumulation is simpler as a plain loop.

Functions in structs

A struct field can hold a function. Calling b.on_click(3) calls the function stored in the field. This is how you write callbacks and simple plug-in behavior without classes or interfaces:

struct Rule:
    name: str
    check: fn(str) bool

fn main():
    rules = [
        Rule("not empty", fn(s) len(s) > 0),
        Rule("max 8 chars", fn(s) len(s) <= 8),
        Rule("no spaces", fn(s) not (" " in s)),
    ]
    for name in ["ada", "grace hopper", ""]:
        failed: [str] = []
        for r in rules:
            if not r.check(name):
                failed.push(r.name)
        print(f"[{name}]", failed)
Output
[ada] []
[grace hopper] ["max 8 chars", "no spaces"]
[] ["not empty"]

map, filter, and sort_by in practice

With lambdas, most collection processing becomes a short chain. Each call returns a new array, so the original is never changed:

struct Film:
    title: str
    year: int
    rating: float

fn main():
    films = [
        Film("Alien", 1979, 8.5),
        Film("Heat", 1995, 8.3),
        Film("Up", 2009, 8.3),
        Film("Jaws", 1975, 8.1),
    ]
    recent = films.filter(fn(f) f.year >= 1990).map(fn(f) f.title)
    print(recent)
    for f in films.sort_by(fn(f) -f.rating):
        print(f.rating, f.title)
    by_title = films.sort_by(fn(f) f.title)
    print(by_title.map(fn(f) f"{f.title} ({f.year})"))
Output
["Heat", "Up"]
8.5 Alien
8.3 Heat
8.3 Up
8.1 Jaws
["Alien (1979)", "Heat (1995)", "Jaws (1975)", "Up (2009)"]
  • sort_by(key) sorts by the key the function returns: an int, float, or str. To sort numbers in descending order, negate the key.
  • The sort is stable: elements with equal keys keep their original order (Heat stays before Up). To sort by two keys, sort by the second key first, then by the first.
  • There is no reduce. A sum or a maximum is a three-line loop, which is also the fastest way to write it.

Mistakes from other languages

Does not compile
fn main():
    xs = [1, 2, 3]
    ys = xs.map(lambda x: x + 1)
    print(ys)
Compiler output
3: error: expected `,`, found 'x'
3: hint: lambdas are written `fn(x) x + 1` (one expression)

Arrow functions (x => x + 1) and Rust closures (|x| x + 1) get similar hints.

Try it

Write fn compose(f: fn(int) int, g: fn(int) int) fn(int) int that returns a function applying f and then g. Use it to build inc_then_square from two lambdas, and apply it to [1, 2, 3] with map. Then sort the words ["kiwi", "fig", "banana", "date"] by length, keeping alphabetical order for words of the same length (hint: two sort_by calls).

Solution

fn compose(f: fn(int) int, g: fn(int) int) fn(int) int:
    return fn(x) g(f(x))

fn main():
    inc_then_square = compose(fn(x) x + 1, fn(x) x * x)
    print([1, 2, 3].map(inc_then_square))
    words = ["kiwi", "fig", "banana", "date"]
    print(words.sort_by(fn(w) w).sort_by(fn(w) len(w)))
Output
[4, 9, 16]
["fig", "date", "kiwi", "banana"]

Next: 11. Parallelism. Reference: §13 Functions as values.

Source: docs/tour/10-closures.md. Every example on this page is compiled and run by tern x test docs.