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:8080Parameters with defaults must come after required parameters.
Calling Functions
wyn
var sum = add(5, 3) // 8
greet("World") // Hello, World!Named Arguments
Call functions with named parameters in any order:
wyn
fn create_user(name: string, age: int, role: string = "member") -> string {
return "${name} (${role})"
}
// Positional
create_user("Alice", 30, "admin")
// Named — any order, defaults fill unspecified params
create_user(name: "Alice", age: 30)
create_user(role: "admin", name: "Bob", age: 25)Tuple Return Types
Functions can return multiple values:
wyn
fn divmod(a: int, b: int) -> (int, int) {
return (a / b, a % b)
}
var result = divmod(17, 5)
println(result.0.to_string()) // 3
println(result.1.to_string()) // 2Higher-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) // 25The main Function
The entry point is fn main(). No return type or return statement needed:
wyn
fn main() {
println("Hello, Wyn!")
}If you need to control the exit code (e.g., CLI tools that signal success/failure):
wyn
fn main() -> int {
if !validate_config() {
println("Invalid config")
return 1 // non-zero = error
}
println("OK")
return 0 // success
}Use -> int with return only when you need a specific exit code. For most programs, just use fn main() { }.
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
Press Run or Ctrl+Enter
See Also
- Closures & Lambdas — anonymous functions
- Error Handling — Result and Option types
- Generics — type parameters
- Named Arguments — call with
name: value