Recursion in Nim
Our example demonstrates recursive functions in Nim. Here’s a classic implementation of factorial calculation using recursion.
In this example, we define two recursive functions:
fact
: A classic factorial function that recursively calculates the factorial of a given number.fib
: A Fibonacci sequence generator implemented as an anonymous recursive function.
The fact
function demonstrates simple recursion, calling itself with a decremented value until it reaches the base case of 0.
For the Fibonacci sequence, we use an anonymous function (lambda) that’s assigned to the fib
variable. In Nim, we can define recursive anonymous functions directly, which is a bit simpler than some other languages that require forward declarations.
To run this program, save it as recursion.nim
and use the Nim compiler:
This example showcases how Nim supports recursive functions, both named and anonymous, providing flexibility in implementing algorithms that benefit from recursive approaches.