Over a million developers have joined DZone.

Cool Stuff in Groovy 1.8: Trampoline

DZone's Guide to

Cool Stuff in Groovy 1.8: Trampoline

· Java Zone ·
Free Resource

Verify, standardize, and correct the Big 4 + more– name, email, phone and global addresses – try our Data Quality APIs now at Melissa Developer Portal!

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

Developers! Quickly and easily gain access to the tools and information you need! Explore, test and combine our data quality APIs at Melissa Developer Portal – home to tools that save time and boost revenue. Our APIs verify, standardize, and correct the Big 4 + more – name, email, phone and global addresses – to ensure accurate delivery, prevent blacklisting and identify risks in real-time.


Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}