Skip to content

Function Basics

Functions are reusable blocks of code that perform specific tasks.

Defining Functions

Use the fn keyword to define a function:

fn greet() {
    print "Hello, World!";
}

// Call the function
greet();  // Hello, World!

Functions with Parameters

fn greet(name) {
    print "Hello, #{name}!";
}

greet("Alice");  // Hello, Alice!
greet("Bob");    // Hello, Bob!

Multiple Parameters

fn add(a, b) {
    let result = a + b;
    print result;
}

add(5, 3);   // 8
add(10, 20); // 30

Return Values

Use return to send a value back to the caller:

fn add(a, b) {
    return a + b;
}

let sum = add(5, 3);
print sum;  // 8

Early Return

fn divide(a, b) {
    if b == 0 {
        print "Error: Division by zero";
        return 0;
    }
    return a / b;
}

print divide(10, 2);  // 5
print divide(10, 0);  // 0 (with error message)

Function Examples

Calculator Functions

fn multiply(a, b) {
    return a * b;
}

fn subtract(a, b) {
    return a - b;
}

let product = multiply(4, 5);
let difference = subtract(10, 3);

print product;     // 20
print difference;  // 7

String Functions

fn make_greeting(name, time_of_day) {
    let greeting = "Good #{time_of_day}, #{name}!";
    return greeting;
}

print make_greeting("Alice", "morning");
print make_greeting("Bob", "evening");

Validation Function

fn is_valid_age(age) {
    if age < 0 {
        return false;
    }
    if age > 150 {
        return false;
    }
    return true;
}

if is_valid_age(25) == true {
    print "Valid age";
}

Calling Functions

fn calculate_area(width, height) {
    return width * height;
}

// Direct call
print calculate_area(5, 10);  // 50

// Store result
let area = calculate_area(8, 12);
print area;  // 96

// Use in expression
let total_area = calculate_area(5, 5) + calculate_area(3, 3);
print total_area;  // 34

Scope

Functions have their own scope:

let global_var = "global";

fn test() {
    let local_var = "local";
    print global_var;  // Can access global
    print local_var;   // Can access local
}

test();
print global_var;  // Works
print local_var;   // Error: undefined