Programming with Tail Recursion

Closures in Groovy provide a way to reap the benefits of recursion and at the same time avoid some of the common problems we run into when using recursions.

With recursion, we solve a problem using solutions to its subproblems. Recursive solutions have charm—they’re concise, and how cool is it that we can compose the solution using the solutions to the same problem but with smaller input size. In spite of these benefits, programmers often shy away from recursive solutions. The threat of a potential StackOverflowError for large input size can dissuade even the geekiest programmers among us.

Here’s the all-too-familiar overly simplified factorial function implemented as a simple recursion.

UsingClosures/simpleFactorial.groovy ...

Get Programming Groovy 2 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.