Recursion in Chapel
Our example demonstrates recursive functions in Chapel. Here’s a classic example of calculating factorials using recursion.
proc fact(n: int): int {
if n == 0 {
return 1;
}
return n * fact(n-1);
}
proc main() {
writeln(fact(7));
// Chapel doesn't have closures in the same way as some other languages,
// but we can define a nested function to achieve similar functionality
proc fib(n: int): int {
if n < 2 {
return n;
}
return fib(n-1) + fib(n-2);
}
writeln(fib(7));
}
This fact
function calls itself until it reaches the base case of fact(0)
.
In Chapel, we don’t have closures in the same way as some other languages. However, we can achieve similar functionality using nested functions. In this example, we define the fib
function inside the main
procedure.
To run the program, save it as recursion.chpl
and use the Chapel compiler:
$ chpl recursion.chpl -o recursion
$ ./recursion
5040
13
The output shows the factorial of 7 (5040) and the 7th Fibonacci number (13).
Chapel supports recursive functions, allowing for elegant solutions to problems that can be naturally expressed in a recursive manner. However, it’s important to use recursion judiciously, as deep recursion can lead to stack overflow errors. In such cases, an iterative approach might be more appropriate.