Functions
Function Declarations
Functions in Braid are declared with the fn keyword followed by the name, parameters in parentheses, an optional return type (with ->), and a body in braces.
fn greet() {
print("Hello, Braid!");
}
fn add(x: int, y: int) -> int {
return x + y;
}
fn multiply(a: int, b: int) {
return a * b;
}Parameters and Return Types
Each parameter has a name and a type separated by a colon. The return type is specified after ->. If omitted, the function returns nil by default.
fn divide(a: float, b: float) -> float {
return a / b;
}
fn log_message(msg: string, level: int) {
print("[" + level + "] " + msg);
}
fn compute_area(radius: float) -> float {
return 3.14159 * radius * radius;
}Early Returns
Use return to exit early from a function. A bare return with no value returns nil.
fn check_positive(val: int) -> bool {
if val > 0 {
return true;
}
return false;
}
fn abort_if_invalid(val: int) {
if val < 0 {
return;
}
print("valid: " + val);
}Closures (Inline Functions)
Anonymous functions can be defined inline and assigned to variables. They capture variables from their enclosing scope as closures.
let double = fn(x: int) -> int { return x * 2; };
let result = double(5);
let base = 100;
let adder = fn(x: int) -> int { return x + base; };
print(adder(50));
let scale = fn(a: float, b: float) -> float { return a * b; };
let scaled = scale(2.5, 4.0);Calling Functions
Functions are called with parentheses. Arguments are positional and must match the declared parameter types.
fn greet(name: string) {
print("Hello, " + name);
}
fn sum(a: int, b: int, c: int) -> int {
return a + b + c;
}
fn main() {
greet("Alice");
let total = sum(10, 20, 30);
print(total);
}Recursion
Braid functions can call themselves recursively. The compiler does not perform TCO yet, so deep recursion may overflow the stack.
fn factorial(n: int) -> int {
if n <= 1 {
return 1;
}
return n * factorial(n - 1);
}
fn fibonacci(n: int) -> int {
if n <= 1 {
return n;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}
fn main() {
print(factorial(5));
print(fibonacci(10));
}The main Function
Every Braid program starts execution from the main function. It takes no parameters and returns nothing. The compiler generates an entry point that callsmain.
fn main() {
let x = 42;
let y = 58;
let result = add(x, y);
print("The answer is " + result);
}
fn add(a: int, b: int) -> int {
return a + b;
}Extern Function Declarations
Functions from external C libraries can be declared with the extern fnsyntax. These are linked at compile time.
extern fn srand(seed: int);
extern fn rand() -> int;
extern fn sqrt(x: float) -> float;
fn main() {
srand(42);
let r = rand();
print(r);
}Native Function Declarations
Native functions are built into the BraidVM runtime. They are declared withnative fn and do not have a body.
native fn print_int(val: int);
native fn print_float(val: float);
native fn print_string(val: string);
fn main() {
print_string("value: ");
print_int(42);
}