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
.
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.
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.
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.
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With