Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement recursive lambda function using Java 8

Java 8 introduced lambda functions and I want to implement something like factorial:

 IntToDoubleFunction fact = x -> x == 0 ? 1 : x * fact.applyAsDouble(x-1); 

Compilation returns

  error: variable fact might not have been initialized 

How can I reference function itself. Class is anonymous but instance exists: It is called fact.

like image 921
user2678835 Avatar asked Oct 17 '13 14:10

user2678835


People also ask

Can a lambda function be recursive?

You may not realise that you can write AWS Lambda functions in a recursive manner to perform long-running tasks. Here's two tips to help you do it right. AWS Lambda limits the maximum execution time of a single invocation to 5 minutes.

Does Java 8 have lambda?

Lambda Expressions were added in Java 8. A lambda expression is a short block of code which takes in parameters and returns a value. Lambda expressions are similar to methods, but they do not need a name and they can be implemented right in the body of a method.

What is recursion with example in Java?

In Java, a method that calls itself is known as a recursive method. And, this process is known as recursion. A physical world example would be to place two parallel mirrors facing each other. Any object in between them would be reflected recursively.


1 Answers

I usually use (once-for-all-functional-interfaces defined) generic helper class which wraps the variable of the functional interface type. This approach solves the problem with the local variable initialization and allows the code to look more clearly.

In case of this question the code will look as follows:

// Recursive.java // @param <I> - Functional Interface Type public class Recursive<I> {     public I func; }  // Test.java public double factorial(int n) {      Recursive<IntToDoubleFunction> recursive = new Recursive<>();     recursive.func = x -> (x == 0) ? 1 : x * recursive.func.applyAsDouble(x - 1);      return recursive.func.applyAsDouble(n); } 
like image 161
Andrey Morozov Avatar answered Sep 17 '22 00:09

Andrey Morozov