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:

import "std/io";
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.

import "std/io";
fn greet(name: str) {
io::Println("Hello, " + name);
}
import "std/io";
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:

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

Functions are first-class 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. See the Anonymous Functions page for detailed examples.