Over a million developers have joined DZone.

Cool Stuff in Groovy 1.8: Trampoline

· Java Zone

Discover how powerful static code analysis and ergonomic design make development not only productive but also an enjoyable experience, brought to you in partnership with JetBrains

Those who have experience with functional programming know how useful tail recursion is. It allows use to write recursive functions occupying only one stack frame for all their calls instead of taking a new frame for each call. Tail recursion is a feature that you’d rarely see in object-oriented languages and Groovy is not an exception. I’d rather say it used to be this way in an obsolete Groovy 1.7. All of us who are using a brand new Groovy 1.8 can enjoy a tail recursion substitute (not being an expert in functional programming I can’t say if it works in all cases, but it’d be interesting to look at an example where it won’t be sufficient).

Let’s take a look at this piece of code:

def factorial
factorial = {
    it <= 1 ? 1G : it * factorial(it - 1)
factorial(500G) //stack overflow

Stack overflow is what you will get trying to execute this piece of code. What we can do in Groovy 1.8 to make it work is to use the trampoline method:

def factorial
factorial = {it, acc = 1->
    it <= 1 ? acc : factorial.trampoline(it - 1, it * acc)

factorial(500G) //no stack overflow

The trampoline method wraps our closure into a TrampolineClosure object. Groovy executes all factorial.trampoline(..) calls sequentially until our closure returns something else than an instance of TrampolineClosure. This is amazing how useful and, at the same time, simple it is.

From http://victorsavkin.com/post/5231079655/cool-stuff-in-groovy-1-8-trampoline

Learn more about Kotlin, a new programming language designed to solve problems that software developers face every day brought to you in partnership with JetBrains.


The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}