Recursion in Cilk

Here’s the translated code and explanation in Markdown format suitable for Hugo:

Our first example demonstrates recursion, a fundamental concept in programming where a function calls itself. Here’s a classic example of calculating factorials using recursion.

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 anonymous inner classes to create recursive functions
        // similar to closures in some other languages.
        IntUnaryOperator fib = new IntUnaryOperator() {
            @Override
            public int applyAsInt(int n) {
                if (n < 2) {
                    return n;
                }
                // Since this is an anonymous inner class, we can refer to 'this'
                // to call the method recursively.
                return this.applyAsInt(n - 1) + this.applyAsInt(n - 2);
            }
        };

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

To run the program, compile and execute it using the javac and java commands:

$ javac Recursion.java
$ java Recursion
5040
13

In this example, we define a fact method that calculates the factorial of a given number recursively. The base case is when n is 0, which returns 1. For any other positive integer, it multiplies n by the factorial of n-1.

We also demonstrate how to create a recursive function using an anonymous inner class, which is similar to closures in some other languages. Here, we implement the Fibonacci sequence. The fib function is defined as an IntUnaryOperator, which is a functional interface in Java that represents a function that accepts an int-valued argument and produces an int-valued result.

The Fibonacci function checks if the input is less than 2 (base case), and if not, it recursively calls itself for n-1 and n-2, summing the results.

Both functions are called in the main method with an argument of 7, and their results are printed.

This example showcases how recursion can be implemented in Java, both with regular methods and with functional interfaces, providing a powerful tool for solving problems that have a recursive nature.