Recursion in D Programming Language
This D program demonstrates recursion using two examples: a factorial function and a Fibonacci sequence generator.
The
fact
function is a classic example of recursion. It calculates the factorial of a given number by calling itself with a decremented value until it reaches the base case of 0.The
main
function first calls and prints the result offact(7)
.Then, it demonstrates recursive delegates (similar to closures in other languages). In D, we need to declare the delegate type explicitly before defining it.
The
fib
delegate calculates the Fibonacci number for a given input. It’s defined recursively, calling itself forn-1
andn-2
.Finally, the program prints the result of
fib(7)
.
To run the program, save it as recursion.d
and use the D compiler:
The output shows the factorial of 7 (5040) and the 7th Fibonacci number (13).
D’s syntax for recursion is similar to many other languages, making it straightforward to implement recursive algorithms. The ability to create recursive delegates adds flexibility, allowing for more complex recursive structures when needed.