Callable
Callable types represent functions or methods that can be invoked. In this language, a callable type is a first-class object, and you can assign it to variables, pass it around, and invoke it just like any other value.
Syntax
Callable types are defined using the fn
keyword, followed by a parameter list and the function body.
fn add(a, b) {
return a + b;
}
You can also assign functions to variables:
const sum = fn(a, b) {
return a + b;
};
// Or with arrow functions
//1. variation
const sum = (a, b) => a + b;
//2. variation
const sum = (a, b) => {
return a + b;
};
Invoking a Callable
To invoke a callable, use parentheses with any required arguments:
const result = add(2, 3); // 5
If the callable is stored in a variable:
const result = sum(2, 3); // 5
Parameters
Callables can take any number of parameters, and their types are not restricted. Parameters are accessed within the body of the callable by their names.
fn multiply(x, y) {
return x * y;
}
Return Values
A callable can return a value using the return keyword:
fn divide(a, b) {
if (b === 0) {
return "Cannot divide by zero";
}
return a / b;
}
⚠️ If a function doesn't explicitly return a value, it implicitly returns undefined
Anonymous Callables
You can define anonymous callables directly within expressions, often as arguments to higher-order functions:
const numbers = [1, 2, 3];
const squared = numbers.transform(fn(n) {
return n * n;
});
Example
// Define a callable
fn greet(name) {
return "Hello, " + name;
}
// Assign to a variable
const greetFunc = greet;
// Invoke the callable
const message = greetFunc("Alice"); // "Hello, Alice"
Binding Callables to Methods
You can bind methods to variables, allowing you to invoke them like regular callables. For instance, methods defined on objects can be extracted and called separately.
const toupper = "hello".toupper; // Bind the method "toupper"
const uppercase = toupper(); // Invoke the `toupper` method
console.log(uppercase); //HELLO
The binding creates a reference to the operand, so you can call it even when the original operand goes out of scope
fn helloToUpper() {
//"hello" will not be destroyed because of the reference created by .toupper
return "hello".toupper;
}
const method = helloToUpper();
console.log(method()); // "HELLO"
Notes
- Callables are first-class citizens, meaning they can be passed around and assigned to variables.
- Unlike JavaScript, this language does not support the
this
keyword. - Callables can be anonymous or named.