Skip to content

Function bodies

A function body is either one expression after =, or a block in braces. Both forms declare the same kind of function, and either works for any result type:

fn doubled_sum(xs: List<Int>) : Int = xs | map(x => x * 2) | sum

fn doubled_sum_block(xs: List<Int>) : Int {
    xs
    | map(x => x * 2)
    | sum
}

[doubled_sum([1, 2, 3]), doubled_sum_block([1, 2, 3])]
[12, 12]

Use = for a body that fits on one line. Use a block when the body is longer, or when naming intermediate values makes it clearer. Inside a block, a pipeline can continue over several lines, each starting with |.

A block is one of two kinds, depending on whether it contains yield:

d2 diagram

The value block

A value block is a series of bindings, name = expr, one per line, followed by one final expression. The value of the final expression is the result of the function, and its type must be the declared result type:

fn label(pages: Int) : String {
    days = (pages + 39) / 40
    kind = "short" given pages < 200 otherwise "long"
    fmt("{} ({} days)", kind, days)
}

[145, 412] | map(label)
["short (4 days)", "long (11 days)"]

Each binding names one step of the computation, and the final line combines them. A value block can return a sequence too. Without yield, the last line is the sequence:

fn even_squares(xs: List<Int>) : Seq<Int> {
    evens = xs | filter(x => x % 2 == 0)
    evens | map(x => x * x)
}

List(even_squares([1, 2, 3, 4]))
[4, 16]

Scope

A binding in a block can be used from the line after it to the end of the block. A binding with the same name as one outside the block shadows it: inside the block the name means the new value, and outside it keeps the old one. A lambda on the last line can use the block's bindings:

k = 100

fn adder(n: Int) : Int -> Int {
    k = n * 10
    x => x + k
}

add = adder(2)
[add(1), add(5), k]
[21, 25, 100]

The bindings of a block cannot be used outside the function:

fn area(w: Float, h: Float) : Float {
    a = w * h
    a
}
a
check error[unknown-name]: `a` is not bound
 --> <expression>:5:1
  |
5 | a
  | ^
  = help: did you mean `at`?

The iterating block

A block that contains yield is an iterating block. It can hold bindings, yield expr and for name in collection { … }. Its result is the sequence of values in the order the yields produce them, so the declared result type is Seq<T>, which ends, or Stream<T>, which need not:

fn countdown(from: Int) : Seq<Int> {
    for n in range(0, from) {
        yield from - n
    }
}

List(countdown(3))
[3, 2, 1]

Chapter 7 covers iterating functions and the streams they produce.

Rules for blocks

A block ends either in a final expression or in yields:

  • A block of bindings alone has no value, and is rejected.
  • A block that yields cannot also have an expression on a line of its own.
  • for is allowed only in an iterating block.

The parser reports each of these:

fn one() : Int {
    x = 1
}

one()
parse failure[unexpected-token]: a block ends in a value or yields; this one holds only bindings
 --> <expression>:1:16
  |
1 | fn one() : Int {
  |                ^^^^^^^^^^^^^

A block is written without =. After =, braces start a record or a set literal, so fn one() : Int = { x = 1 } does not parse.

Where functions are declared

A function has the same form wherever it is declared: at the top level of a program, in a module (chapter 5), as a receiver function that takes self (receiver modules), and in a trait or an implementation (traits). A lambda's body is always one expression; a function that needs a block is declared with fn.