Functions
Functions are declared with fn. Parameters are typed, and a return type is written after an arrow.
Parameters and return types
This program prints 5. print takes only a str and adds no newline, so numbers go through to_str.
fn add(a: int, b: int) -> int {
return a + b;
}
fn main() -> int {
print(to_str(add(2, 3)) + "\n");
return 0;
}
return main(); Returning early
Output: negative
fn classify(n: int) -> str {
if n > 0 {
return "positive";
} else if n < 0 {
return "negative";
} else {
return "zero";
}
}
fn main() -> int {
print(classify(0 - 4) + "\n");
return 0;
}
return main(); Recursion
fn factorial(n: int) -> int {
if n <= 1 {
return 1;
}
return n * factorial(n - 1);
}
fn main() -> int {
print(to_str(factorial(5)) + "\n");
return 0;
}
return main(); This program prints 120. Programs end with return main(); on the last line, and main's return value becomes the exit status. A file containing only fn main() {...} prints nothing, because top-level statements are what run.
Procedures
A function without a return type performs work without producing a value. This one prints Hello, RUDRA.
fn greet(name: str) {
print("Hello, " + name + "\n");
}
fn main() -> int {
greet("RUDRA");
return 0;
}
return main();