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)

fn 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)

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; a unit hint additionally displays the result in that unit. A plain number where a unit is expected is an error.

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

Hint names include every dimension (Length, Mass, Time, Speed, Area, Volume, Currency, …), any unit (kg, m/s^2), Integer, Real, String, Boolean, and Instant. 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.