Repository navigation
Functions
Functions in Lantern are a way to bundle reusable behavior. In fact, the entrypoint of every Lantern program is itself a function! It provides the behavior of the program when executed.
Functions are defined using the fun keyword and can have any number of parameters and a return type. For example, take a look at this function definition:
fun add(a: int, b: int) -> int {
val sum = a + b;
return sum;
}
This function is named add and it takes two different parameters, a and b. In this case, both of these parameters are integers. We can use these parameters in the function body in a way similar to variables, such as performing operations on them. Additionally, it returns an int back to the caller. In the function body, we are doing a simple addition calculation and storing in the sum variable. Then, we return that sum and give it back to the caller. Calling this function should look familiar:
add(2, 5);
Function arguments match with its parameters sequentially. In the case above, calling the add function means assigning 2 to a and 5 to b.
We can also store the result of the function (what it returns) in a variable:
val sum = add(2, 5);
// sum is 7
Note that sum here is an int, since the add function returns an int.
Functions can also be used as values:
val add_function = add;
val sum = add_function(5, 5);
// sum is 10
Note that we don't use parenthesis after add since we are not calling the function. Instead, we are assigning the function itself to the variable add_function. Lantern automatically infers this type to be a special fun(int, int) -> int type. Later, we can call this variable like any other function.
Functions can also be called recursively. That is, a function can call (and reference) itself. Take a simple example of a factorial:
fun factorial(n: int) -> int {
if (n <= 1) {
return 1;
}
return n * factorial(n - 1);
}
Then, we can compute factorials using this function:
val five_factorial = factorial(5);
// five_factorial is 120
Keep in mind that if we get rid of the condition at the top of the function, the function will continuously call itself until our program runs out of memory and crashes.
using std{};
fun factorial(n: int) -> int {
return n * factorial(n - 1);
}
fun main() {
factorial(5);
}
Running the above program gives us a stack overflow error:
Error: Stack overflow
at factorial (factorial:4)
at factorial (factorial:4)
at factorial (factorial:4)
at factorial (factorial:4)
at factorial (factorial:4)
at factorial (factorial:4)
at factorial (factorial:4)
at factorial (factorial:4)
at factorial (factorial:4)
at factorial (factorial:4)
at factorial (factorial:4)
at factorial (factorial:4)
at factorial (factorial:4)
at factorial (factorial:4)
at factorial (factorial:4)
...and 653 more