Functions
fn
A function's value is its last expression. return is only needed for an early exit.
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.
x = later()
fn later() { "works" }
x # → "works"The number of arguments is checked:
fn add(a, b) { a + b }
add(1)argument: add expects 2 argument(s), got 1Default values
Evaluated on every call; they may refer to earlier parameters.
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.
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.
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]) # → 9The same syntax builds literals:
[*[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.
[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) # → 8A 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.
{ 42 }.call(9) # → 42
{ (a, b) -> b }.call(1) # → nilreturn inside a closure exits the enclosing function, break exits the call the closure was passed to:
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 } # → 200Anonymous functions
fn(…) { … } and (…) -> { … } are functions without a name. Unlike { … }, they check the number of arguments, and return exits the function itself.
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) # → 5An arrow function's body goes in braces only: (x) -> x * 2 does not compile.
Closures capture by reference
fn counter() {
n = 0
{ n += 1; n }
}
tick = counter()
tick()
tick()
tick() # → 3x.f(y) is f(x, y)
Any function can be called with a dot: the value on the left becomes the first argument.
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 # → trueYour 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.
total = 0
for i in 1..3 { total += i }
total # → 6
n = 0
{ n := 5 }.call()
n # → 0A variable that first appears inside a block is not visible outside it:
if true { y = 5 }
yname: undefined variable 'y'A function sees the variables declared above it:
rate = 100
fn cents(x) { x * rate }
cents(3) # → 300Recursion
Call depth is limited (200 by default); exceeding it is not caught by try.
fn fact(n) { n <= 1 ? 1 : n * fact(n - 1) }
fact(10) # → 3628800