Functions & Closures
Functions are the primary building blocks of code organization in Flame.
Defining Functions (fn)
Section titled “Defining Functions (fn)”Use the fn keyword to declare a function. Parameters require explicit type annotations, and the return type is declared with ->:
fn calculate_area(width: Float, height: Float) -> Float { return width * height}
let area = calculate_area(5.5, 10.0)print($"Area: {area}")If a function does not return a value, the -> Nil return type can be omitted:
fn log_message(msg: String) { print($"[LOG]: {msg}")}Closures & Anonymous Functions
Section titled “Closures & Anonymous Functions”Flame supports anonymous functions (closures) that can capture variables from their surrounding lexical environment:
let factor = 10
// Define an inline closurelet multiply = (x: Int) { return x * factor}
print(multiply(5)) // 50Closures can be passed as arguments to collection methods:
let nums = [1, 2, 3, 4, 5]let doubled = nums.map((n: Int) { return n * 2 })let evens = nums.filter((n: Int) { return n % 2 == 0 })
print(doubled) // [2, 4, 6, 8, 10]print(evens) // [2, 4]Higher-Order Functions & Closure Signatures
Section titled “Higher-Order Functions & Closure Signatures”Functions can accept closures with explicit parameter and return types:
// 1. Higher-order function with closure parameter (implicit Nil return)fn for_each(items: [String], action: (item: String)) { for item in items { action(item) }}
// 2. Closure with parameters and explicit return typefn process_text(text: String, transform: (input: String) -> String) -> String { return transform(text)}
let languages = ["Flame", "Rust", "TypeScript"]for_each(languages, (lang: String) { println($"• {lang}")})
let formatted = process_text("hello flame", (input: String) -> String { return $"[PROCESSED]: {input}"})println(formatted)Asynchronous Functions (async fn)
Section titled “Asynchronous Functions (async fn)”Functions marked with async fn execute concurrently without blocking OS worker threads and return a future:
async fn fetch_api_status(url: String) -> String { // Non-blocking network I/O return "200 OK"}Built-in Standard I/O Functions
Section titled “Built-in Standard I/O Functions”Flame includes standard global I/O functions out of the box:
print(...): Prints values to standard output (stdout) without a trailing newline.println(...): Prints values to standard output (stdout) followed by a newline.eprint(...): Prints values to standard error (stderr) followed by a newline (ideal for warnings/errors).input(prompt: String) -> String: Displays a prompt and reads a line of input fromstdin.
let user_name = input("Please enter your username: ")if user_name.len() == 0 { eprint("Username cannot be empty!")} else { print($"Welcome, {user_name}!")}