Skip to content

Functions ​

fn ​

A function's value is its last expression. return is only needed for an early exit.

mzs
fn add(a, b) { a + b }
add(2, 3)  # → 5

fn sign(n) {
  return "minus" if n < 0
  n == 0 ? "zero" : "plus"
}
sign(-5)  # → "minus"

Top-level functions are hoisted: they can be called before the declaration.

mzs
x = later()
fn later() { "works" }
x  # → "works"

The number of arguments is checked:

mzs
fn add(a, b) { a + b }
add(1)
text
argument: add expects 2 argument(s), got 1

Default values ​

Evaluated on every call; they may refer to earlier parameters.

mzs
fn greet(name, greeting = "Hello") { "${greeting}, ${name}!" }
greet("Ann")  # → "Hello, Ann!"
greet("Ann", "Good morning")  # → "Good morning, Ann!"

fn take(xs, n = xs.len) { xs.first(n) }
take([1, 2, 3])  # → [1,2,3]

Named arguments ​

name = value lets you skip a parameter in the middle.

mzs
fn area(w, h = 2, unit = "cm") { "${w * h} ${unit}" }
area(3)  # → "6 cm"
area(3, unit = "m")  # → "6 m"
area(h = 5, w = 3)  # → "15 cm"

Named arguments come after positional ones. Built-in functions take arguments by position only.

*rest and spreading ​

*rest collects extra arguments into an array. In a call, *xs spreads an array over positions, **d a dict over names.

mzs
fn tag(name, *classes) { "<${name} class='${classes.join(" ")}'>" }
tag("div", "big", "red")  # → "<div class='big red'>"

fn area(w, h = 2, unit = "cm") { "${w * h} ${unit}" }
dims = [3, 5]
area(*dims)  # → "15 cm"
area(3, **{unit: "m"})  # → "6 m"
max(*[3, 9, 2])  # → 9

The same syntax builds literals:

mzs
[*[1, 2], 3, *(4..5)]  # → [1,2,3,4,5]
defaults = {unit: "cm", h: 2}
{**defaults, unit: "m"}  # → {"unit":"m","h":2}

Closures and it ​

{ … } is a closure. Without a parameter list it has one parameter, it.

mzs
[1, 2, 3].map { it * 2 }  # → [2,4,6]
[1, 2, 3].map { (x) -> x * 10 }  # → [10,20,30]
[1, 2, 3].reduce(0) { (acc, x) -> acc + x }  # → 6
double = { (n) -> n * 2 }
double(4)  # → 8

A closure passed last is written after the call's parentheses. A nested closure has its own it.

Closures do not check the number of arguments: extra ones are dropped, missing ones are nil.

mzs
{ 42 }.call(9)  # → 42
{ (a, b) -> b }.call(1)  # → nil

return inside a closure exits the enclosing function, break exits the call the closure was passed to:

mzs
fn first_big(xs) {
  xs.each { return it if it > 10 }
  nil
}
first_big([3, 15, 40])  # → 15
[1, 2, 3].each { break it * 100 if it == 2 }  # → 200

Anonymous functions ​

fn(…) { … } and (…) -> { … } are functions without a name. Unlike { … }, they check the number of arguments, and return exits the function itself.

mzs
add = fn(a, b) { a + b }
add(2, 3)  # → 5
mul = (a, b) -> { a * b }
mul(2, 3)  # → 6
ops = {inc: fn(x) { x + 1 }}
ops["inc"](4)  # → 5

An arrow function's body goes in braces only: (x) -> x * 2 does not compile.

Closures capture by reference ​

mzs
fn counter() {
  n = 0
  { n += 1; n }
}
tick = counter()
tick()
tick()
tick()  # → 3

x.f(y) is f(x, y) ​

Any function can be called with a dot: the value on the left becomes the first argument.

mzs
fn shout(s) { s.upper + "!" }
"yay".shout  # → "YAY!"
shout("yay")  # → "YAY!"

fn between(x, lo, hi) { x >= lo && x <= hi }
5.between(1, 10)  # → true
len("world") == "world".len  # → true

Your own function with a library name replaces the library one wherever it is visible.

Scope ​

Every { … } block is its own scope. = writes to the nearest existing variable, otherwise creates it here; := always creates a new one.

mzs
total = 0
for i in 1..3 { total += i }
total  # → 6

n = 0
{ n := 5 }.call()
n  # → 0

A variable that first appears inside a block is not visible outside it:

mzs
if true { y = 5 }
y
text
name: undefined variable 'y'

A function sees the variables declared above it:

mzs
rate = 100
fn cents(x) { x * rate }
cents(3)  # → 300

Recursion ​

Call depth is limited (200 by default); exceeding it is not caught by try.

mzs
fn fact(n) { n <= 1 ? 1 : n * fact(n - 1) }
fact(10)  # → 3628800