Showing posts with label groovy tail recursion optimization. Show all posts
Showing posts with label groovy tail recursion optimization. Show all posts

Thursday, January 5, 2012

Tail recursion in Groovy

Groovy ships with a limited form of tail recursion via a trampoline mechanism. Here, I expand on the existing trampoline to add a cleaner, more intuitive interface. This extension has two parts: a Java class and a new Object method (read: global function).

A Java class:
import groovy.lang.Closure;
// loop/recur

class RecursionWrapper {
    private Closure<object> _target;

    public RecursionWrapper(Closure<object> target) {
     _target = target;
    }
    
    public Object recur() {
        return _target.trampoline();
    }
    public Object recur(Object a) {
        return _target.trampoline(a);
    }
    public Object recur(Object... a) {
        return _target.trampoline(a);
    }
}

A global function:
// loop/recur

Object.metaClass.loop = {closure->
 def cln = closure.clone()
 def trCln = cln.trampoline()
 def rw = new RecursionWrapper(trCln)
 cln.delegate = rw
 trCln
}