Recursion in Logo

import java.util.function.IntUnaryOperator;

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 lambda expressions to create recursive functions.
        // Here's how we can define a recursive Fibonacci function:
        IntUnaryOperator fib = new 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 Java code demonstrates recursion, a concept where a function calls itself. Here’s a breakdown of the example:

  1. We define a static method fact that calculates the factorial of a number recursively. It calls itself with n-1 until it reaches the base case of 0.

  2. In the main method, we first call and print the result of fact(7).

  3. Java doesn’t have closures in the same way as some other languages, but we can achieve similar functionality using lambda expressions or anonymous inner classes. In this example, we use an anonymous inner class that implements IntUnaryOperator to create a recursive Fibonacci function.

  4. The Fibonacci function is defined to return n if n is less than 2, otherwise it returns the sum of fib(n-1) and fib(n-2).

  5. Finally, we call the Fibonacci function with fib.applyAsInt(7) and print the result.

To run this program, save it as Recursion.java, compile it with javac Recursion.java, and then run it with java Recursion. The output will be:

5040
13

This example demonstrates how recursion can be implemented in Java, both with regular methods and with functional interfaces. While Java doesn’t have the exact same syntax for closures as some other languages, it provides powerful alternatives that allow for similar patterns of recursive computation.