Functions
fn add(int a, int b) {
return a + b
}
print(add(2, 3))
5
Each parameter has its type first. The return type is worked out from the return lines, or you can write it after ->:
fn label(int n) -> string {
return "#{n}"
}
print(label(7))
#7
A function that calls itself needs its return type written:
fn fib(int n) -> int {
if n < 2 { return n }
return fib(n - 1) + fib(n - 2)
}
print(fib(20))
6765
A function that gives back a value has to return on every path. One with no return value gives back nothing.
Functions can be used before the line that defines them, and they can't be defined inside other code.
Default values and named values
fn greet(string who, string greeting := "hello") {
print("{greeting}, {who}")
}
greet("noa")
greet("dan", greeting = "shalom")
greet(greeting = "hey", who = "tal")
hello, noa
shalom, dan
hey, tal
A default value has to be fixed when compiling, like 100 or "hello". Plain values come before named ones.
Changing the caller's variable
Parameters are read-only, and passing a string doesn't copy it. Mark a parameter mut to let the function change the variable it was given:
fn hurt(mut int hp, int dmg) {
hp -= dmg
}
fn shout(mut string s) {
s = s + "!"
}
hp := 100
hurt(hp, 30)
word := "hi"
shout(word)
print(hp, word)
70 hi!
A mut parameter needs a variable of exactly its type, and the same variable can't be given to two mut parameters in one call.
To change a plain parameter inside the function only, make a copy first:
fn twice(string t) {
t := t + t
return t
}
print(twice("ab"))
abab