Recursion in D Programming Language
import std.stdio;
// This `fact` function calls itself until it reaches the
// base case of `fact(0)`.
int fact(int n) {
if (n == 0) {
return 1;
}
return n * fact(n - 1);
}
void main() {
writeln(fact(7));
// Delegates can also be recursive, but this requires the
// delegate to be declared with a type explicitly
// before it's defined.
int function(int) fib;
fib = (int n) {
if (n < 2) {
return n;
}
// Since `fib` was previously declared in `main`, D
// knows which function to call with `fib` here.
return fib(n - 1) + fib(n - 2);
};
writeln(fib(7));
}
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:
$ dmd recursion.d
$ ./recursion
5040
13
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.