Declaring a function¶
fn declares a named function. A declaration gives the name, the parameters
with their types, the result type after :, and the body:
fn days(pages: Int, per_day: Int) : Int = (pages + per_day - 1) / per_day
[days(412, 40), days(280, 40)]
[11, 7]
days has the type (Int, Int) -> Int. The parameter types and the result
type are always written. The checker does not infer them from the body,
because the declaration is the contract that callers rely on.
A call must pass every parameter, with the right type:
fn days(pages: Int, per_day: Int) : Int = (pages + per_day - 1) / per_day
days(412)
check error[type-mismatch]: this function takes 2 arguments, not 1
--> <expression>:2:1
|
2 | days(412)
| ^^^^^^^^^
The body after = is one expression. A longer body is a block in braces;
Function bodies covers both forms.
Parameters have no defaults¶
A function you declare in HQL takes every argument it declares. A parameter
cannot have a default value, so fn per_week(per_day: Int = 40) is
rejected. Some functions in the standard library do have defaults, such as
limit: Int = 0; those are declared in HQL and implemented in Rust, as
chapter 32 shows. When an argument is
usually the same, bind the value to a name and pass the name.
Recursion¶
A function's name is bound before its body is checked, so the body can call the function itself:
fn factorial(n: Int) : Int = 1 given n <= 1 otherwise n * factorial(n - 1)
[1, 2, 3, 4, 5] | map(factorial)
[1, 2, 6, 24, 120]
map(factorial) passes the function by its name. A declared function is a
value like a lambda.
Functions as parameters and results¶
A parameter can have a function type, and so can the result. adder returns
a function, and twice takes one:
fn adder(k: Int) : Int -> Int = n => n + k
fn twice(f: Int -> Int, x: Int) : Int = f(f(x))
twice(adder(3), 30)
36
The function adder(3) returns keeps the value of k it was created with.
A function that keeps values from where it was created is a closure.
Variadic parameters¶
A last parameter written ...T accepts any number of trailing arguments, and
the body sees them as a list:
fn total(xs: ...Int) : Int = xs | sum
[total(), total(1, 2), total(1, 2, 3, 4)]
[0, 3, 10]
A result that may be missing¶
A function that may have no result returns an Option<T>. some(x) holds a
value and none holds nothing:
fn rating_of(r: Int) : Option<Int> = some(r) given r > 0 otherwise none
[5, 0, 4] | map(rating_of) | somes
[5, 4]
somes keeps the present values. Option covers the
other ways to handle an Option.