Real currying on Groovy.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def realCurry(Closure clos) { | |
if (clos.maximumNumberOfParameters >= 1) { | |
return { x -> | |
def cc = clos.curry(x) | |
if (cc.maximumNumberOfParameters) realCurry(cc) | |
else cc() | |
} | |
} else { | |
return clos | |
} | |
} | |
def foldLeft(lst, init, f) { | |
def result = init | |
lst.each{e -> result = f(result)(e) } | |
result | |
} | |
assert 15 == foldLeft([1, 2, 3, 4, 5], 0, realCurry{x, y-> x + y}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// refs. http://en.wikipedia.org/wiki/Currying | |
Closure add = {a, b, c -> a + b + c } // Closure of adding 3 arguments. | |
assert add(1, 2, 3) == realCurry(add)(1)(2)(3) | |
assert 6 == add(1, 2, 3) | |
def curriedAdd = realCurry(add) | |
def curriedAdd_1 = curriedAdd(1) | |
def curriedAdd_1_2 = curriedAdd_1(2) | |
def addResult = curriedAdd_1_2(3) | |
assert 6 == addResult | |
def realCurry(Closure clos) { | |
if (clos.maximumNumberOfParameters >= 1) { | |
return { x -> | |
def cc = clos.curry(x) | |
if (cc.maximumNumberOfParameters) realCurry(cc) | |
else cc() | |
} | |
} else { | |
return clos | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment