Skip to content

Functions

Functions are reusable blocks of code that perform specific tasks.

To declare a function, use the fn keyword followed by the function name. Let’s define a function that greets a user:

fn greet() {
io::Println("Hello!");
}

Functions can take inputs from outside which are called parameters. Parameters are just like variables that are defined in the function signature.

fn greet(name: str) {
io::Println("Hello, " + name);
}
let message := greet("World");
io::Println(message); // Hello, World

Functions can return values:

fn add(a: i32, b: i32) -> i32 {
return a + b;
}
let sum := add(5, 3); // 8

Functions that don’t return a value:

fn log_message(msg: str) {
io::Println("[INFO] " + msg);
}

Functions are values in ferret and can be assigned to variables or passed as arguments. We can define unnamed functions using the fn keyword without a name:

let square = fn(x: i32) -> i32 {
return x * x;
};
let result = square(5); // 25

This allows for greater flexibility in how functions are used and composed.