Recursion in Crystal
Our example demonstrates recursive functions in Crystal. Here’s a classic implementation of factorial:
When you run this program, you’ll see:
This example showcases two types of recursion in Crystal:
- A standard recursive function
fact
that calculates the factorial of a number. - A recursive Proc object
fib
that calculates Fibonacci numbers.
The fact
function is straightforward: it calls itself with n - 1
until it reaches the base case of 0.
The fib
Proc demonstrates how to create a recursive closure in Crystal. We first declare fib
with a type signature, then define it. This allows fib
to call itself within its own definition.
Crystal’s type system requires explicit type annotations for recursive Procs, which is why we specify the argument and return types.
Remember, while recursion can lead to elegant solutions for some problems, it’s important to be mindful of the stack usage, especially for deep recursions.