Guides · 04

Functions and closures

Everything you can call in Vyi is declared with fn. A method is a fn with a receiver, overloads are several fns that share a name, and a closure is a function value written inline with an arrow. This guide covers each of them in turn. It ends with lifetime annotations, which let a function state how long a pointer it returns stays valid.

Declaring functions

Parameters are written name: Type, separated by commas. The return type comes after the parameter list, with no arrow or keyword in front of it:

Vyi
import { println } from "@fmt"

fn add(a: i32, b: i32) i32 {
    return a + b
}

fn main() !u8 {
    println(add(2, 3))   // prints 5
    return Ok(0)
}

A function with no return type returns (), the empty tuple (guide 02). [*con]u8 is the type of a string:

Vyi
import { println } from "@fmt"

fn greet(name: [*con]u8) {
    println(name)
}

fn main() !u8 {
    greet("hello")   // prints hello
    return Ok(0)
}

A function's name is visible throughout the scope it's declared in, including the lines above the declaration. Functions can call each other whatever order you write them in:

Vyi
import { println } from "@fmt"

fn main() !u8 {
    println(double(4))   // prints 8
    return Ok(0)
}

fn double(n: i32) i32 {   // declared below its caller
    return n * 2
}

A function is private to its file unless you declare it with export fn. Other files can import an exported function by name (guide 14, Modules and packages).

Default arguments

A parameter can have a default value, written = expr after its type. A call can leave out trailing arguments that have defaults:

Vyi
import { println } from "@fmt"

fn cost(price: i32, quantity: i32 = 1) i32 {
    return price * quantity
}

fn main() !u8 {
    println(cost(5))      // prints 5
    println(cost(5, 3))   // prints 15
    return Ok(0)
}

A default is an ordinary expression of the parameter's type. Its names are the ones visible where the function is declared, never the caller's. A default that uses a helper private to the function's file works for callers in every file, and a caller's local that happens to have the same name is a different binding. The expression is evaluated again on every call that leaves the argument out.

A default can use the parameters to its left, with the values this call gives them:

Vyi
import { println } from "@fmt"

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

fn main() !u8 {
    println(area(3))      // prints 9
    println(area(3, 4))   // prints 12
    return Ok(0)
}

The parameter itself, and the parameters after it, aren't in scope yet:

Vyi · does not compile
fn area(
    width: i32 = height,   // error: undefined name "height"
    height: i32 = 2,
) i32 {
    return width * height
}

Arguments are matched by position, so only trailing arguments can be left out. A default on a parameter that comes before a required one can never be used:

Vyi · does not compile
fn area(width: i32 = 1, height: i32) i32 {
    return width * height
}

fn main() !u8 {
    con a = area(5)   // error: "area" expects 2 argument(s), got 1
    return Ok(0)
}

Overloading by signature

Several functions can share a name when their parameter types differ. These are overloads. A call picks the one whose parameters match the arguments it passes, by the number of arguments:

Vyi
import { println } from "@fmt"

fn greet() {
    println("hello")
}

fn greet(name: [*con]u8) {
    println($"hello, ${name}")
}

fn main() !u8 {
    greet()        // prints hello
    greet("ada")   // prints hello, ada
    return Ok(0)
}

or by their types:

Vyi
import { println } from "@fmt"

struct Celsius    { deg: i32 }
struct Fahrenheit { deg: i32 }

fn freezing(c: Celsius) bool    { return c.deg <= 0 }
fn freezing(f: Fahrenheit) bool { return f.deg <= 32 }

fn main() !u8 {
    println(freezing(Celsius{ deg: 3 }))      // prints false
    println(freezing(Fahrenheit{ deg: 3 }))   // prints true
    return Ok(0)
}

The result type never tells two overloads apart, because a call is resolved by what it passes. Two functions with the same parameter types are a duplicate, whatever they return:

Vyi · does not compile
fn half(n: i32) i32 {
    return n / 2
}

fn half(n: i32) f64 {   // error: duplicate declaration of "half"
    return f64(n) / 2.0
}

When more than one overload matches a call and none is the most specific, the compiler rejects the call as ambiguous rather than guessing.

Overloads are the functions sharing a name in one scope. A call's name is looked up like any other name, so a parameter or local named freezing hides both functions above, and another file's private freezing is never a candidate. A file sees its own functions plus the ones its imports bring in (guide 14). The expressions reference has the exact rule.

Methods and receivers

A method is a function with a receiver, written in parentheses before the function's name. You call it with a dot, value.method():

Vyi
import { println } from "@fmt"

struct Account { balance: i32 }

fn (Account) empty() Account {
    return Account{ balance: 0 }
}

fn (a: Account) isEmpty() bool {
    return a.balance == 0
}

fn (a: *mut Account) deposit(amount: i32) {
    a.balance += amount
}

fn main() !u8 {
    mut account = Account.empty()
    println(account.isEmpty())   // prints true
    account.deposit(50)
    println(account.balance)     // prints 50
    return Ok(0)
}

The receiver says what the method works on. Guide 03 introduced pointers: &a is a pointer to a, and a *mut T can change what it points at. A *con T can only read it. Guide 09 covers pointers in full.

ReceiverThe method getsTypical use
(a: Account)the value, which it can read but not changecomputing something from the value
(a: *con Account)a read-only pointer to the value, without a copyreading a large value
(a: *mut Account)a writable pointer to the valuechanging the value
(Account)no value; you call it on the type, Account.empty()constructors

You don't write the & or the * at the call. account.deposit(50) passes a pointer to account for you, and calling a value method through a pointer reads the value it points at. Inside a pointer-receiver method, a.balance reaches the field through the pointer.

A *mut method changes the value, so it can only be called on something you're allowed to change: a mut binding, or a *mut pointer. Calling it on a con binding is an error:

Vyi · does not compile
struct Account { balance: i32 }

fn (a: *mut Account) deposit(amount: i32) {
    a.balance += amount
}

fn main() !u8 {
    con account = Account{ balance: 10 }
    account.deposit(5)   // error: cannot call "deposit" here
    return Ok(0)
}

A note on the error says the method exists for *mut Account but isn't callable on an immutable value. The methods and dispatch reference lists every way a receiver adapts to a call.

Methods are scope, not type members

A type's definition lists its fields and nothing else. Methods are declared on their own, outside the type, and the methods a value has are the ones in scope where you call them. This has two consequences.

First, any file can declare a method on any type, including the primitive types:

Vyi
import { println } from "@fmt"

fn (n: i32) doubled() i32 {
    return n * 2
}

fn main() !u8 {
    con a: i32 = 7
    println(a.doubled())   // prints 14
    return Ok(0)
}

A method can also be declared inside a function body or any other block. Like a function, it's visible in its whole block, and unknown outside it:

Vyi
import { println } from "@fmt"

fn main() !u8 {
    con n: i32 = 4
    println(n.squared())   // prints 16
    fn (x: i32) squared() i32 { return x * x }
    return Ok(0)
}

A method declared in a block receives only its receiver and its arguments. It can use types, known values, and other names in scope, but not a value the enclosing function computes while it runs:

Vyi · does not compile
fn scaled(n: i32, factor: i32) i32 {
    fn (x: i32) times() i32 {
        return x * factor   // error: a method declared in a block
    }
    return n.times()
}

Pass that value as a parameter instead, or write a closure, which this guide covers below.

Second, methods travel with their type through imports. When you import a type, its exported methods come with it, and you don't import them by name:

Vyi
// file: rect.vyi
export struct Rect { pub width: i32, pub height: i32 }

export fn (r: Rect) area() i32 {
    return r.width * r.height
}

// file: main.vyi
import { println } from "@fmt"
import { Rect } from "./rect"

fn main() !u8 {
    con r = Rect{ width: 2, height: 3 }
    println(r.area())   // prints 6
    return Ok(0)
}

A file can import Rect, declare more methods on it, and re-export it. Files that import Rect from that file see the extra methods too, and a file can import one of them on its own as Rect.method. When two declarations of the same method are in scope, the closer one wins: your own file's method beats an imported one, and a re-exporting file's method beats the original. The methods and dispatch reference has the exact rules.

Closures and function values

Functions are values. The type of a function value is written fn(SIG): the parameter types in parentheses, then the return type. A function's name is a value of that type, so you can pass a function to another function:

Vyi
import { println } from "@fmt"

fn double(n: i32) i32 { return n * 2 }

fn apply(f: fn(i32) i32, x: i32) i32 {
    return f(x)
}

fn main() !u8 {
    println(apply(double, 5))   // prints 10
    return Ok(0)
}

Arrow syntax

You write a function value inline with an arrow: a parameter list, an optional return type, =>, then an expression or a block. A function value written this way is a closure:

Vyi
import { println } from "@fmt"

fn main() !u8 {
    con add = (a: i32, b: i32) i32 => a + b
    con double = (n: i32) => n * 2
    con larger = (a: i32, b: i32) i32 => {
        if a > b { return a }
        return b
    }
    println(add(3, 4))      // prints 7
    println(double(10))     // prints 20
    println(larger(5, 8))   // prints 8
    return Ok(0)
}

add has an expression body, and larger has a block. double leaves out its return type. Without one, the closure returns whatever its body gives: the type of an expression body, or for a block body, the types its return statements give. double above is a fn(i32) i32.

The fn name() { … } form only declares a function. It can't be used as a value, with or without a name:

Vyi · does not compile
fn main() !u8 {
    con one = fn() i32 {   // error: function values use arrow syntax
        return 1
    }
    return Ok(0)
}

A closure bound with con and a function declared with fn give the same kind of value. They differ only in where their names are visible: a fn is visible in its whole block, and a con from its line down.

An overloaded function as a value

An overloaded name used as a value has no arguments to pick an overload with. The function type expected where it's used picks it instead: write the type on the binding, or pass the name where a parameter of function type expects it:

Vyi
import { println } from "@fmt"

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

fn apply(f: fn(i32) i32, x: i32) i32 {
    return f(x)
}

fn main() !u8 {
    con rect: fn(i32, i32) i32 = area
    println(rect(2, 3))       // prints 6
    println(apply(area, 4))   // prints 16
    return Ok(0)
}

The binding's type picks the two-parameter area, and the parameter f of apply picks the one-parameter area. Without a function type there, as in con g = area, the compiler reports that area is overloaded and lists the candidates. The same holds for an overloaded type-receiver method such as Point.make. A function with a known parameter (guide 11) is never a value. Call it, or pass a closure that calls it.

Capture is by value

A closure can use the bindings around it. It copies, or captures, each value it uses at the moment the closure is created:

Vyi
import { println } from "@fmt"

fn main() !u8 {
    con tax = 10
    con withTax = (price: i32) i32 => price + tax
    println(withTax(100))   // prints 110
    return Ok(0)
}

A captured struct is copied whole, so the closure's copy is independent of the original. A copy of a binding that later changes would quietly show an old value, so capturing a mut binding is an error:

Vyi · does not compile
fn main() !u8 {
    mut n = 10
    con get = () i32 => n   // error: closure captures mutable
    n = 99
    return Ok(0)
}

Capturing pointers

When a closure needs to change something outside itself, capture a pointer to it. The pointer is copied into the closure, and the closure writes through it:

Vyi
import { println } from "@fmt"

fn main() !u8 {
    mut count = 0
    con p = &count
    con bump = () => { *p += 1 }
    bump()
    bump()
    println(count)   // prints 2
    return Ok(0)
}

State that a closure shares with the code around it is always a pointer you chose to capture, so it's visible in the source.

A closure is a pointer

A closure is stored in two parts: its instance, which holds the values it captured, and the code to run. A closure value, of type fn(SIG), points at its instance. So every fn(SIG) is the same size whatever the closure captured, and a struct field, a parameter, or a Vec element of function type fits any closure.

The instance lives where the closure literal is written, like any other value, and a closure can't outlive its instance. Calling a closure in the scope where it's written, and passing it down into a call, are always fine. Returning it, or storing it somewhere that outlives its instance, is an error:

Vyi
import { println } from "@fmt"

fn apply(f: fn(i32) i32, x: i32) i32 {
    return f(x)
}

fn main() !u8 {
    con tax = 10
    con withTax = (price: i32) i32 => price + tax
    println(withTax(100))          // prints 110
    println(apply(withTax, 200))   // prints 210
    return Ok(0)
}
Vyi · does not compile
fn adder(n: i32) fn(i32) i32 {
    con add = (x: i32) i32 => x + n
    return add   // error: frame-bound pointer fn(i32) i32 escapes
}

The message goes on to say how to keep a closure longer: put it into an allocator, as shown below. The rule is the one every pointer follows, and guide 09 spells out where an instance lives and how long.

A closure that captures nothing has no instance, and neither does a named function used as a value. Both are fine anywhere, including as a return value:

Vyi
import { println } from "@fmt"

fn triple(n: i32) i32 { return n * 3 }

fn tripler() fn(i32) i32 {
    return triple
}

fn doubler() fn(i32) i32 {
    return (n: i32) i32 => n * 2
}

fn main() !u8 {
    println(tripler()(5))   // prints 15
    println(doubler()(5))   // prints 10
    return Ok(0)
}

A function declared with fn inside another function works the same way: used as a value, it creates an instance where it's referenced, and returning it is an error if it captures anything.

Putting a closure into an allocator

A closure outlives the scope it's written in only when you put it into memory from an allocator (guide 09). *closure is the closure's instance, and an allocator's put(v) stores a copy of v and returns a pointer to it. A pointer to a closure's instance is that closure, so put(*closure) gives back a fn(SIG) that lives as long as the allocator:

Vyi
import { println } from "@fmt"
import {
    Allocator, ArenaAllocator, OutOfMemory, systemAllocator,
} from "@mem"

fn adder(n: i32, a: Allocator) OutOfMemory!fn(i32) i32 {
    return a.put(*(x: i32) i32 => x + n)
}

fn main() !u8 {
    mut arena = ArenaAllocator.new(systemAllocator)
    defer arena.deinit()
    con add5 = try adder(5, &arena)
    println(add5(3))   // prints 8
    return Ok(0)
}

Write the * directly before the closure literal, as above, or before a con bound directly to one, as in arena.put(*add). Without the *, put stores the closure value itself and returns a pointer to it, a *mut fn(i32) i32, and the compiler tells you to write put(*f).

A closure in an allocator lives as long as the allocator. One put into an arena the function creates can't be returned from that function. delete doesn't take a fn(SIG), so keep closures in an arena and let the arena's reset free them.

_ inference

_ is the inference placeholder. Write it where a type goes, and the compiler works the type out. As a return type, it comes from the function's return statements. When they return different types, the result is their union:

Vyi
import { println } from "@fmt"

fn double(n: i32) _ {    // returns i32
    return n * 2
}

fn userKey(id: i32) _ {  // returns i32 | [*con]u8
    if id == 0 { return "guest" }
    return id
}

fn main() !u8 {
    println(double(4))   // prints 8
    con key: i32 | [*con]u8 = userKey(0)
    return Ok(0)
}

A recursive function can infer its return type too. The recursive call returns whatever the function returns, so the other return statements decide:

Vyi
import { println } from "@fmt"

fn factorial(n: i32) _ {   // returns i32
    if n > 1 { return n * factorial(n - 1) }
    return 1
}

fn main() !u8 {
    println(factorial(4))   // prints 24
    return Ok(0)
}

The inferred type has to have a fixed size. A function that returns its own result inside a tuple, as in return (nest(n - 1), 1), would contain itself, so it needs its return type written.

In a closure, a _ parameter or return type is worked out from the function type expected where the closure is used: the type on the binding, or the type of the parameter you pass the closure to:

Vyi
import { println } from "@fmt"

fn apply(g: fn(i32) i32, x: i32) i32 { return g(x) }

fn main() !u8 {
    con inc: fn(i32) i32 = (x: _) _ => x + 1
    println(inc(10))                         // prints 11
    println(apply((y: _) i32 => y * 2, 5))   // prints 10
    return Ok(0)
}

On a named function, a _ parameter type means more: the function accepts an argument of any type, and the compiler builds a separate version of it for each argument type you call it with. _ written as an argument asks the compiler to work out a known argument. Guide 11, Known values and generics, covers both.

Lifetime annotations

A function that returns a pointer can state how long the result stays valid, with a lifetime annotation after the return type. Guide 09 introduces pointers: &x takes the address of x, and *mut T is a pointer you can write through. Here the result of xOf points into the point it was given:

Vyi
import { println } from "@fmt"

struct Point { x: i32, y: i32 }

fn xOf(p: *mut Point) *mut i32 '(p) {
    return &p.x
}

fn main() !u8 {
    mut pt = Point{ x: 1, y: 2 }
    con x = xOf(&pt)
    *x = 10
    println(pt.x)   // prints 10
    return Ok(0)
}

Read '(p) as "valid as long as what p refers to". The annotation belongs in the signature because callers rely on it: the compiler checks each call against what the signature says, not against the body, so the body can change without changing what callers may do. Without an annotation, the compiler works the lifetime out from the body. Guide 09 covers lifetimes in full.

See also the methods and dispatch reference and the memory model reference.