Functions
Declare reusable behavior with typed parameters and return values.
Declaration
Write the function name, : func, and a parameter list. An arrow introduces the return type.
add : func(a : i32, b : i32) -> i32 {
return a + b
}
result := add(10, 20) // 30
| Part | Meaning |
|---|---|
add | The function's name. |
a : i32, b : i32 | Named, typed parameters. |
-> i32 | The type returned to the caller. |
return a + b | Computes and returns the result. |
No return value
Omit the return type when the function performs an action without returning a value.
increment : func(value : ^i32) {
^value += 1
} Default arguments
Give a parameter a default with =. Parameters with defaults must come last. Arguments are passed by position.
add_with_default : func(a : i32, b : i32 = 10) -> i32 {
return a + b
}
first := add_with_default(5) // 15
second := add_with_default(5, 2) // 7 Generic functions
Place type parameters after func. Chic can infer the type argument from a call and specializes the function at compile time.
max_of : func<T>(a : T, b : T) -> T {
if a > b { return a }
return b
}
largest := max_of(3, 7) // T is inferred
<T>; constraint forms such as <T : i32> are not supported.Multiple return values
Return a tuple when a function needs to produce more than one value.
divide : func(a : i32, b : i32) -> [i32, i32] {
return [a / b, a % b]
} Lambda functions
A lambda is an anonymous function used as a value. Write func, its parameters, and its body, then assign it to a binding and call it like any other function.
double := func(value : i32) -> i32 {
return value * 2
}
result := double(21) // 42
To use a local value from the surrounding scope, capture it explicitly in brackets after func. [offset] captures a copy of offset when the lambda is created.
offset := 10
add_offset := func[offset](value : i32) -> i32 {
return value + offset
}
shifted := add_offset(5) // 15