Skip to content

Functions

Name a calculation once and call it with different values. The shortest form is name(params) = expression.

double(x) = x * 2
double(21)
bmi(weight, height) = weight / height^2 to 1 dp
bmi(72 kg, 1.78 m)

The fn keyword is the explicit form. A body on the next lines is indented; the last line is the result.

fn hypotenuse(a, b):
  let squares = a^2 + b^2
  sqrt(squares)
hypotenuse(3 m, 4 m)

Parameters can be phrases, and a body can branch with if.

fn elapsed(start time, end time) = end time - start time
elapsed(2 hour, 9 hour)
fn label(n) = if n < 0 then "negative" else if n == 0 then "zero" else "positive"
label(-3)

Arguments can be passed by name, as name = value or name: value, in any order. Positional arguments come first, named ones after.

fn elapsed(start time, end time) = end time - start time
elapsed(end time: 9 hour, start time: 2 hour)
elapsed(2 hour, end time = 9 hour)

Functions may call themselves.

fact(n) = if n == 0 then 1 else n * fact(n - 1)
fact(10)

A when clause states what a function accepts. A call that breaks it is an error at the call site.

fn safe divide(a, b) when b != 0 = a / b
safe divide(10, 2)
safe divide(10, 0)

A parameter can name the dimension or unit it expects. A dimension hint accepts any unit of that dimension, and a plain number there is an error.

fn speed(distance: Length, time: Time) = distance / time
speed(100 km, 2 hour)
speed(100, 2)

A unit hint accepts any unit of its dimension too, and gives a plain number its unit. The same holds for a return hint (-> kg), let, record fields, formula arguments, and a formula property that a line defines (w: kg with w = a * 2).

fn in grams(mass: kg) = mass to g
in grams(3 lb)
in grams(2)

Hint names include every dimension (Length, Mass, Time, Speed, Area, Volume, Currency, …), any unit (kg, m/s^2), Integer, Real, String, Boolean, Instant, Date, and TimeOfDay. A named value can carry a hint too: let height: m = 5 ft stores and shows metres.

A function name binds one definition. Declaring it again replaces it.