Recursion in Miranda

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

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 use anonymous inner classes to create
        // recursive lambda expressions
        RecursiveFunction<Integer, Integer> fib = new RecursiveFunction<Integer, Integer>() {
            @Override
            public Integer apply(Integer n) {
                if (n < 2) {
                    return n;
                }
                // Since fib was previously declared, Java
                // knows which function to call with fib here.
                return fib.apply(n - 1) + fib.apply(n - 2);
            }
        };

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

// Interface for recursive functions
interface RecursiveFunction<T, R> {
    R apply(T t);
}

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

$ javac Recursion.java
$ java Recursion
5040
13

In this Java version, we’ve implemented the factorial function fact as a static method, which is similar to the Go version. For the Fibonacci function, we’ve used an anonymous inner class implementing a RecursiveFunction interface to mimic the behavior of the recursive closure in the Go example. This approach allows us to create a recursive lambda-like structure in Java.

The main differences are:

  1. Java uses System.out.println instead of fmt.Println for output.
  2. We’ve created a RecursiveFunction interface to allow for recursive lambda-like structures.
  3. The recursive Fibonacci function is implemented using an anonymous inner class instead of a closure.

Despite these differences, the core concept of recursion remains the same in both languages.