4.10 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 ... |
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access