Functions
Functions in ROX are first-class citizens, meaning they can be assigned to variables, passed as arguments, and returned from other functions.
Function Declaration
Functions are declared using the function keyword, followed by the function name, parameters, and
return type.
function add(int64 a, int64 b) -> int64 {
return a + b;
}
Note: Function names (except main) are automatically namespaced by the compiler.
User identifiers must not begin with roxv26_.
Parameters
Parameters must have explicit types.
function greet(string name) -> none {
print("Hello, ", name, "!\n");
}
Return Type
The return type must be explicitly specified after ->. If a function does not return a value, use
none.
function do_nothing() -> none {
return;
}
Rule: If a function has return type none, reaching the end of the function body
implicitly returns none.
Functions as Values
Since functions are first-class, you can use them just like any other value.
Type Syntax
Function types are written as function(ParamType1, ParamType2, ...) -> ReturnType.
Type Matching: Function types must match exactly. No implicit conversions or variance are allowed.
Assigning to Variables
You can assign a function to a variable with a matching function type.
function square(int64 x) -> int64 {
return x * x;
}
// Declare a variable 'op' that holds a function taking a int64 and returning a int64
function(int64) -> int64 op = square;
print(op(5)); // Output: 25
Passing as Arguments
Functions can be passed to other functions (higher-order functions).
function apply(function(int64) -> int64 f, int64 val) -> int64 {
return f(val);
}
function double(int64 x) -> int64 {
return x * 2;
}
print(apply(double, 10)); // Output: 20
Returning Functions
Functions can return other functions.
function log(string msg) -> none {
print(msg);
}
function get_logger() -> function(string) -> none {
return log;
}
function(string)->none logger = get_logger();
logger("Log this message\n");
Recursion
Recursive functions are fully supported.
function factorial(int64 n) -> int64 {
if (n <= 1) {
return 1;
}
return n * factorial(n - 1);
}
Notes
- Anonymous Functions: Anonymous functions (lambdas) are not supported by design. You must define a named function first.
- Closures: Functions do not capture variables from their surrounding scope by design. They only have access to their parameters and global constants.