In Java you can only reference final fields inside a closure. Here’s my solution*.
Note: You could use a Y Combinator, but that is not practical at all. My solution simply creates an object with a private field.
When you define a closure you are at the point where the closure is created to then be assigned to a final field. You can’t use that field yet and this
doesn’t point to the closure.
This small projects is the solution for recursive functions in Java. This also works for operators, callables, runnables etc.
final IntToLongFunction fib;
fib = Recursive.intToLongFunction(
(n, self) ->
n <= 1 ? n
: self.applyAsLong(n - 1) + self.applyAsLong(n - 2));
Here’s how to use Koloboke as a cache:
final IntLongMap m = HashIntLongMaps.newMutableMap();
final IntToLongFunction fib = Recursive.cachedIntToLongFunction(
(n, self) -> n <= 1 ? n : self.applyAsLong(n - 1) + self.applyAsLong(n - 2),
(i,s) -> m.computeIfAbsent(i, x -> s.getAsLong()));
The project is hosted on GitHub: https://github.com/claudemartin/Recursive
Check out Demo to see more examples.
* The code is based on the idea of Andrey Morozov.
Note: I also have another project: https://github.com/claudemartin/Functions
For now Functions only supports nonprimitive types, while Recursive supports all types.
One thought on “Recursive Closures in Java”