Skip to content

Functions

Basic Functions

wyn
fn add(a: int, b: int) -> int {
    return a + b
}

fn greet(name: string) {
    println("Hello, ${name}!")
}

Default Parameters

wyn
fn greet(name: string = "world") -> string {
    return "Hello, ${name}!"
}

fn connect(host: string = "localhost", port: int = 8080) {
    println("Connecting to ${host}:${port}")
}

greet()              // Hello, world!
greet("Wyn")         // Hello, Wyn!
connect()            // Connecting to localhost:8080
connect("0.0.0.0")   // Connecting to 0.0.0.0:8080

Parameters with defaults must come after required parameters.

Calling Functions

wyn
var sum = add(5, 3)     // 8
greet("World")          // Hello, World!

Higher-Order Functions

Pass functions as arguments:

wyn
fn apply(x: int, f: fn(int) -> int) -> int {
    return f(x)
}

fn square(n: int) -> int { return n * n }

var result = apply(5, square)   // 25

Error Propagation with ?

The ? operator unwraps a ResultInt or returns early on error:

wyn
fn parse_int(s: string) -> ResultInt {
    if s == "42" { return ResultInt_Ok(42) }
    return ResultInt_Err("not a number")
}

fn double_parsed(s: string) -> ResultInt {
    var n = parse_int(s)?    // returns early if Err
    return ResultInt_Ok(n * 2)
}

Named Function References

wyn
fn dbl(x: int) -> int { return x * 2 }

var nums = [1, 2, 3]
var doubled = nums.map(dbl)     // [2, 4, 6]

Try It

🐉 Playground
Press Run or Ctrl+Enter

MIT License