Recursion in Mercury

Our example demonstrates recursive functions in Java. Here’s a classic example of recursion.

public class Recursion {
    // This fact function 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 define a recursive lambda function
        // using a functional interface.
        IntFunction<Integer> fib = new IntFunction<Integer>() {
            @Override
            public Integer apply(int n) {
                if (n < 2) {
                    return n;
                }
                // Since fib is defined within the apply method,
                // Java knows which function to call with fib here.
                return fib.apply(n - 1) + fib.apply(n - 2);
            }
        };

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

To run the program, compile it and then execute:

$ javac Recursion.java
$ java Recursion
5040
13

In this Java example, we’ve implemented both a recursive method (fact) and a recursive lambda function (fib).

The fact method is a straightforward translation of the original factorial function. It calls itself with n-1 until it reaches the base case of n == 0.

For the Fibonacci sequence, we’ve used a lambda function defined with a functional interface (IntFunction<Integer>). This is similar to the closure in the original example, but uses Java’s functional programming features. The lambda function is defined anonymously and can call itself recursively using the apply method.

Note that in Java, we don’t need to explicitly declare the type of the lambda function before defining it, as Java can infer the type from the context. However, we do need to use a functional interface to create a recursive lambda.

This example demonstrates how recursion can be implemented in Java, both with traditional methods and with functional programming constructs.