Skip to content

Instantly share code, notes, and snippets.

@fumokmm
Created September 4, 2011 21:36
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save fumokmm/1193548 to your computer and use it in GitHub Desktop.
Real currying on Groovy.
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})
// 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