Anand Ramamurthy
Anand Ramamurthy

Reputation: 93

Factorial recursion implementation using lambda function

The code which i tried to implement factorial using Lambda function. The error in the code states that operator " == " or " - " cannot be applied in the lambda function.

@FunctionalInterface
public interface RecFunction {
    Integer recursiveFunction(Integer n);
}
        // Lambda Function
        Integer Fact = (n)-> {
            if (n == 0) return 1;
            else return n * factorial.recursiveFunction ( n - 1 );
        };

Upvotes: 1

Views: 686

Answers (1)

Eran
Eran

Reputation: 393811

The target of a lambda expression must be a functional interface, not an Integer.

Once you resolve that, you'll probably want Fact and factorial to be the same variable.

That won't be possible if factorial is a local variable, but it is possible with an instance variable or a static variable.

For example:

class Test 
{
    static RecFunction factorial = null;

    public static void main (String[] args)
    {
        factorial = n -> {
            if (n == 0) {
                return 1;
            } else {
                return n * factorial.recursiveFunction (n - 1);
            }
        };
        System.out.println (factorial.recursiveFunction(5));
    }
}

The lambda expression can also be re-written as:

factorial = n -> n == 0 ? 1 : n * factorial.recursiveFunction (n - 1);

This will output

120

Upvotes: 3

Related Questions