Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

# Recursion using Lambda in Java?

Martin Phee
Greenhorn
Posts: 6
Can I create recursive functions using lambda's? I have tree structures which I need to interact over and apply updates to nodes.

Stephan van Hulst
Bartender
Posts: 6479
83
You question is a little vague. Do you want lambdas to call themselves? This is not possible, since lambdas have no name, and therefore can not be called.

If you have a recursive function that applies an operation to each node, you can use lambdas for the operation. For instance, you could write a function that applies an operation to each node in a depth-first way like this:

Scott Shipp
Ranch Hand
Posts: 209
11
Yes you can use recursion. Here's an example of Fibonacci number generation with recursion:

Campbell Ritchie
Sheriff
Posts: 50699
83
Are you using that Fibonacci program as an example of exponential complexity?

Richard Warburton
Author
Greenhorn
Posts: 22
7
Martin Phee wrote:Can I create recursive functions using lambda's? I have tree structures which I need to interact over and apply updates to nodes.

Hi Martin,

Thanks to Scott for already answering the question. You can create recursive lambdas by declaring a field which holds the lambda and calling the single abstract method on the field. His comment shows an example of this. Its also possibly using what's known as a 'Y Combinator' [0]

Having said that, I would recommend against either of these approaches. The simplest and cleanest way of writing a recursive method is using a normal method. You can still use this in an API like the streams API by using a method reference to call this method. Often times code is cleaner if you give things names and recursive methods (which need to refer to themselves) are a good example of this.

regards,

Richard

[0] http://en.wikipedia.org/wiki/Fixed-point_combinator#Y_combinator

Scott Shipp
Ranch Hand
Posts: 209
11
Thanks for weighing in Richard! As luck would have it, this is also partially an answer to my other question! Recursion is an area where lambdas are not well-suited. :-)

Stephan van Hulst
Bartender
Posts: 6479
83
I got interested in the Y combinator solution that Richard proposed. Here's a Java implementation:
I managed to define factorial() and fibonacci() anonymously (that is, I could have applied the lamdas directly, rather than assigning them to a name first).

It should be clear that Java is not well suited for these functional approaches.