Functions
A function is the keyword f, a name, optional parameters and an optional C result type. The last expression is the result.
Today
f add(a: i32, b: i32) i32
a + b
f greet()
<
f clamp(x,lo,hi: i32) i32
if x < lo
< lo
if x > hi
< hi
x
f main
greet()
add(1, 2) + clamp(15, 0, 10) != 13int add(int a, int b) {
return a + b;
}
void greet(void) {
return;
}
int clamp(int x, int lo, int hi) {
if (x < lo) {
return lo;
}
if (x > hi) {
return hi;
}
return x;
}
int main(void) {
greet();
return add(1, 2) + clamp(15, 0, 10) != 13;
}- The result type is
voidby default andintformain. - Zero parameters may omit the parentheses:
f main. - Bare names share the preceding C type:
int x,lo,hi. < valuereturns early;<alone returns from a void function.
Target: typed signatures with sized types
The new signature spells every parameter as name type, and a single expression body can follow =.
f greet
puts("hello")
f main = 0
f add(a: i32, b: i32) i32
a + b
f double(x: i32) i32 = x * 2Related
- Types lists the sized type names.
- Control flow covers
<,!and^. - The guide lesson on functions has more examples.