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.

  1. 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.

  2. The main function first calls and prints the result of fact(7).

  3. Then, it demonstrates recursive delegates (similar to closures in other languages). In D, we need to declare the delegate type explicitly before defining it.

  4. The fib delegate calculates the Fibonacci number for a given input. It’s defined recursively, calling itself for n-1 and n-2.

  5. 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.