Functions
Functions are reusable blocks of code that perform specific tasks.
Function Declaration
Section titled “Function Declaration”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!");}Function Parameters
Section titled “Function Parameters”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);}Calling Functions
Section titled “Calling Functions”import "std/io";
let message := greet("World");io::Println(message); // Hello, WorldReturn Types
Section titled “Return Types”Functions can return values:
fn add(a: i32, b: i32) -> i32 { return a + b;}
let sum := add(5, 3); // 8Void Functions
Section titled “Void Functions”Functions that don’t return a value:
import "std/io";
fn log_message(msg: str) { io::Println("[INFO] " + msg);}Unnamed or Anonymous Functions
Section titled “Unnamed or Anonymous Functions”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); // 25This allows for greater flexibility in how functions are used and composed. See the Anonymous Functions page for detailed examples.