Functions

A function gives a name to a piece of code, so it can be used again:

fn greet(name: str): str {
    return "Hello, ${name}!"
}

print(greet("Ann"))
print(greet("Bo"))

Output:

Hello, Ann!
Hello, Bo!

fn starts a function. Then come its name, its parameters in ( ) and its result type after a :, written just like a variable: name: type. The block holds its code, and return gives the result.

Parameters and results

Each parameter has a name and a type. The arguments of a call must match them in number and type:

fn area(width: float, height: float): float {
    return width * height
}

fn repeat(word: str, times: int): [str] {
    out: [str] = []
    [1, 2, 3, 4, 5].walk(i) {
        if i > times { stop }
        out[] = word
    }
    return out
}

print(area(2.5, 4.0))
print(repeat("hi", 3))

Output:

10.0
["hi", "hi", "hi"]

Any type can be a parameter or a result: numbers, str, bool, lists, maps, sets, error and file.

Default values

A parameter can have a default, written like a variable’s value. A call can leave it out, and the function gets the default:

fn greet(name: str, greeting: str = "Hello"): str => "${greeting}, ${name}!"

print(greet("Ann"))
print(greet("Bo", "Hi"))

fn find(name: str, limit: int = 10, exact: bool = false): str {
    return "${name}: ${limit} ${exact}"
}
print(find("ann"))
print(find("ann", 5))
print(find("ann", 5, true))

Output:

Hello, Ann!
Hi, Bo!
ann: 10 false
ann: 5 false
ann: 5 true
  • They come last. The parameters with defaults are after the others, and a call leaves out arguments from the end: find("ann", 5) gives limit and takes exact’s default.
  • A default is a fixed value: a literal, a locked value or operators on them (LIMIT * 2), [] or {}, which is a new one for each call, or nil for an optional parameter. A default that has to be worked out when the function is called is a ?T = nil, set inside: if limit == nil { ... }.
  • Methods have them too, and so does init: Shop("Corner") with fn init(name: str, open: bool = true).
  • Only by name: through a function value every argument is given, as its type, fn(str, str): str, says. The same for spawn and wait. A trait’s methods can have defaults too; the objs that are the trait have the same ones.

Functions without a result

Without : type, a function returns nothing. It is called as a statement, and can use return alone to stop early:

fn report(name: str, score: int) {
    if score < 0 {
        return
    }
    print("${name}: ${score}")
}

report("Ann", 90)
report("Bo", -1)
report("Cid", 75)

Output:

Ann: 90
Cid: 75

Using such a function as a value, as in x: int = report("Ann", 90), is a compile error.

A function with a result can also be called as a statement. Its result is then thrown away.

One-line functions

A function whose body is one expression can be written with => instead of a block. It means the same as { return expression }:

fn add(a: int, b: int): int => a + b
fn greet(name: str): str => "Hello, ${name}!"
fn even(x: int): bool => x % 2 == 0
fn announce(x: str) => print("Value: ${x}")

print(add(2, 3))
print(greet("Ann"))
print(even(4))
announce("hi")

Output:

5
Hello, Ann!
true
Value: hi
  • The result type is written, as in any function. Without one, the expression must give nothing, like the call in announce; fn even(x: int) => x % 2 == 0 is an error that tells you to add : bool.
  • Everywhere a function can be: methods (fn area(): float => self.w * self.h), pub functions, and several results, written as in a return: fn divide(a: int, b: int): (int, int) => a / b, a % b.
  • One expression only: no statements, variables or loops. When the function needs them, use a block.
  • A long expression can start on the next line, after the =>:
fn digits(a: int, b: int, c: int): int =>
    a * 100 + b * 10 + c

print(digits(1, 2, 3))

Output:

123

Several results

A function can give several values. Its result lists their types in parentheses, and return gives them separated by commas:

fn divide(a: int, b: int): (int, int) {
    return a / b, a % b
}

fn lookup(id: int): (str, bool) {
    if id == 7 {
        return "Ann", true
    }
    return "", false
}

q: int, r: int = divide(17, 5)
print("${q} rest ${r}")

name: str, found: bool = lookup(7)
print("${name} ${found}")

Output:

3 rest 2
Ann true

The values are taken with several names before the =:

  • New variables, each with its type, like parameters: q: int, r: int = divide(17, 5).
  • Existing places, without types: q, r = divide(9, 4). A place can also be a list element or a field: p.x, p.y = divide(100, 7).
  • _ drops a value that isn’t needed: name, _ = lookup(8), _, found: bool = lookup(7).

One statement either declares all its names or assigns to all of them. The types must match the function’s results in order, and the compiler checks the count too.

The values come only together. A call with several results can’t be used as one value, as in print(divide(7, 2)). Take its values first, then use them. A function with the same results can pass them on, with return divide(a, b). On its own line, the call’s values are thrown away, as with any result.

Methods can give several results too: fn both(): (int, int) { return self.x, self.y }. A function with several results can’t be used as a value, or with wait, yet.

Every way must return

A function with a result must reach a return on every way through it. Luma checks this when it compiles:

fn sign(x: int): int {
    if x > 0 {
        return 1
    }
}            // error: sign must return an int, but it can reach its end without a return

An if returns on every way when both its block and its else do. A throw also counts, because the function doesn’t go on after it:

fn sign(x: int): int {
    if x > 0 {
        return 1
    } else if x < 0 {
        return -1
    }
    return 0
}

print(sign(-5))
print(sign(0))

Output:

-1
0

return inside walk and try

return leaves the whole function, also from inside a walk or a try:

fn find(names: [str], who: str): int {
    i: int = 0
    names.walk(name) {
        if name == who {
            return i
        }
        i = i + 1
    }
    return -1
}

print(find(["Ann", "Bo", "Cid"], "Bo"))
print(find(["Ann", "Bo", "Cid"], "Dan"))

Output:

1
-1

Where functions are

Functions are written at the top level of the program, not inside a block. They can be called anywhere in the file, also above their definition, so a function can call itself or another function defined later:

print(fact(10))

fn fact(n: int): int {
    if n <= 1 {
        return 1
    }
    return n * fact(n - 1)
}

Output:

3628800

A function calling itself is called recursion. Up to 10,000 calls can be nested. One more raises error 10, too many nested calls, usually because the recursion never stops.

What a function can see

A function sees only its parameters and the variables it declares itself. It doesn’t see the program’s variables:

limit: int = 10
fn check(x: int): bool {
    return x < limit     // error: undefined variable limit: a function can't see
}                        // the program's variables ...; pass it as an argument

Pass what it needs as an argument instead, or make it a locked value if it never changes: lock LIMIT: int = 10 can be used in every function. Each call has its own variables, so two functions, or two calls of the same function, never mix up their variables, even with the same names.

Variables can’t have the name of a function, and a function can’t have the name of a built-in like print or len.

Arguments are copies, but lists are shared

A parameter is a new variable that gets the argument’s value. Changing it doesn’t change the caller’s variable:

fn bump(n: int): int {
    n = n + 1
    return n
}

count: int = 5
print(bump(count))
print(count)

Output:

6
5

Lists, maps and sets are shared, as with assignment: a function that changes a list changes the caller’s list too:

fn add_twice(list: [int], x: int) {
    list[] = x
    list[] = x
}

nums: [int] = [1]
add_twice(nums, 7)
print(nums)

Output:

[1, 7, 7]

Errors and functions

An error raised inside a function, by throw or by something like a division by zero, leaves the function, and the functions that called it, until a try catches it:

fn check_age(age: int): int {
    if age < 0 {
        throw error(100, "an age can't be negative")
    }
    return age
}

fn total(ages: [int]): int {
    sum: int = 0
    ages.walk(a) {
        sum = sum + check_age(a)
    }
    return sum
}

err: error = nil
try err {
    print(total([30, 40]))
    print(total([30, -1]))
}
print(err.message)

Output:

70
an age can't be negative

Functions as values

A function is also a value: its name, without ( ), can be put into a variable, a list, a map or a field, passed to another function and returned from one. A variable that holds a function is called like the function itself:

fn double(x: int): int {
    return x * 2
}
fn square(x: int): int {
    return x * x
}
fn apply(f: fn(int): int, x: int): int {
    return f(x)
}

f: fn(int): int = double
print(f(5))
f = square
print(f(5))
print(apply(double, 21))

Output:

10
25
42

The type of a function is written like its header: fn(int): int takes an int and gives an int, fn(str, int): bool takes two values, and fn(str) gives nothing. A function value fits only where the parameters and the result are exactly these types.

That lets one function do a job its caller fills in:

fn shout(s: str): str {
    return s.upper()
}
fn each(words: [str], change: fn(str): str): [str] {
    out: [str] = []
    words.walk(w) {
        out[] = change(w)
    }
    return out
}

print(each(["hi", "there"], shout))
styles: {str: fn(str): str} = {"loud": shout}
print(styles["loud"]("quiet"))

Output:

["HI", "THERE"]
QUIET
  • Of other files and objects: geo.area is a pub function of an imported file, as a value, and Point.moved is a method; it takes the object as its first argument: m: fn(Point, int): Point = Point.moved, then m(p, 1).
  • In objects: a field of a function type is called like a method: an obj Button { click: fn(str) } can be clicked with b.click("ok").
  • Comparing: == and != tell whether two values are the same function. print shows one as fn double, and a lambda as fn.

Lambdas

A function can also be written right where a value goes, without a name: fn, the parameters, then => expression or a block.

nums: [int] = [1, 2, 3, 4, 5, 6]
print(nums.map(fn(n) => n * 2))
print(nums.filter(fn(n) => n % 2 == 0))

obj Person {
    name: str
    age: int
}
people: [Person] = [Person{name: "Ann", age: 40}, Person{name: "Bo", age: 20}]
print(people.sort(fn(a, b) => a.age < b.age).map(fn(p) => p.name))

square: fn(int): int = fn(x: int): int => x * x
print(square(7))

Output:

[2, 4, 6, 8, 10, 12]
[2, 4, 6]
["Bo", "Ann"]
49
  • Types come from the place. Where the lambda goes says what it takes and gives: a parameter of a function type, a variable, field or list of one, sort, map, filter or wait. So fn(a, b) => a.age < b.age needs no types. Where the place doesn’t say, write them, fn(x: int): int => x * x; the compiler asks for what it needs.
  • The result of fn(x) => ... can also come from its expression, as in map. A block’s is written, fn(id): str { ... }, when the place doesn’t give it. Without one, the function gives nothing: fn() { print("done") }.
  • One result. A lambda can’t give several; return an object.

What a lambda sees

A lambda sees its parameters and the variables around it. It takes a copy of the ones it uses when it is made, as a function takes its arguments: a later change outside doesn’t reach it, and lists, maps and objects are shared.

fn adder(n: int): fn(int): int => fn(x) => x + n

add5: fn(int): int = adder(5)
add10: fn(int): int = adder(10)
print(add5(1))
print(add10(1))

greeting: str = "Hello"
greet: fn(str): str = fn(name) => "${greeting}, ${name}!"
greeting = "Bye"
print(greet("Ann"))

Output:

6
11
Hello, Ann!
  • Read-only: count = count + 1 inside a lambda is a compile error, as it would change only the lambda’s copy. To share a value that changes, keep it in an object’s field or a list: c.count = c.count + 1 changes the object both see.
  • Each its own copy: a lambda made in a walk takes that step’s element; one made by each call of adder keeps its own n.
  • In a method, self is seen like any variable: fn() => self.count reads the object’s field when it is called.
  • Safe in parallel: with wait and spawn, each call has its own copies of numbers and strs. Lists, maps and objects are shared as with any function.
  • Memory: a lambda that captures something is a small object, freed when the last value holding it goes. An object that holds a lambda that captured the same object is never freed (like two objects that point to each other).

Not available yet

  • Named arguments (find("ann", exact: true)): arguments go in the order of the parameters.

See Limitations.