Recursion in Fortress

Our example demonstrates the concept of recursion in programming. Here’s the full source code:

public class Recursion {
    // This fact method calls itself until it reaches the
    // base case of fact(0).
    public static int fact(int n) {
        if (n == 0) {
            return 1;
        }
        return n * fact(n - 1);
    }

    public static void main(String[] args) {
        System.out.println(fact(7));

        // In Java, we can use a recursive lambda expression
        // to define a Fibonacci function
        java.util.function.IntUnaryOperator fib = new java.util.function.IntUnaryOperator() {
            @Override
            public int applyAsInt(int n) {
                if (n < 2) {
                    return n;
                }
                return applyAsInt(n - 1) + applyAsInt(n - 2);
            }
        };

        System.out.println(fib.applyAsInt(7));
    }
}

This fact method calls itself until it reaches the base case of fact(0).

In Java, we can use a recursive lambda expression to define a Fibonacci function. We use an IntUnaryOperator interface to create a recursive function similar to the closure in the original example.

To run the program, compile it and then use java:

$ javac Recursion.java
$ java Recursion
5040
13

The output shows the factorial of 7 (5040) and the 7th Fibonacci number (13).

In Java, we don’t have the concept of closures in the same way as some other languages, but we can achieve similar functionality using lambda expressions or anonymous inner classes, as demonstrated in the Fibonacci example.