Groovy functional sugar: Trampoline


Based on Gr8-Docs, recursive algorithms are often restricted by the maximum stack height (physical limit). If you call a method that recursively calls itself too deep, you will eventually receive a StackOverflowException.

An approach that helps in those situations is using Closure and trampoline capability.

The trampoline() method on a closure is wrapped in TrampolineClosure instance. Calls to the TrampolineClosure are executed sequentially invoking the original closure, until the original closure returns something different to TrampolineClosure. This way the stack isn’t filled, calls are made serially and we can “avoid” stack overflow exceptions.

Without trampoline: stackoverflow

With trampoline: Ok!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s