Currying and composition
A closure with two parameters can be fixed at one of them, which gives a closure of one parameter. That is partial application, and Groovy spells it curry.
Fixing an argument
curry.groovy
def add = { int a, int b -> a + b }
def bindFirst = add.curry(10)
def bindLast = add.rcurry(10)
println bindFirst(5)
println bindLast(5)
def greet = { String greeting, String name -> "${greeting}, ${name}" }
def hello = greet.curry('Hello')
println hello('Ada')
println greet.ncurry(1, 'Ada')('Hi')
groovy curry.groovy
15
15
Hello, Ada
Hi, Ada
curry fills from the left, rcurry from the right, and ncurry from a position: the first argument is the index and the rest are the values. The result is a new closure; the original is unchanged.
Composition
compose.groovy
def double = { int n -> n * 2 }
def increment = { int n -> n + 1 }
def doubleThenIncrement = double >> increment
def incrementThenDouble = double << increment
println doubleThenIncrement(5)
println incrementThenDouble(5)
println(doubleThenIncrement.curry(1)(1))
groovy compose.groovy
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
/tmp/gc/run/b-vr5oz2zc/compose.groovy: 1: Unexpected input: 'def double =' @ line 1, column 12.
def double = { int n -> n * 2 }
^
1 error
exit status: 1
f >> g runs f and then g; f << g runs g and then f. Both return a closure, so a pipeline is built from small functions with a name of its own.
A pipeline with names
pipeline.groovy
def trim = { String text -> text.trim() }
def lower = { String text -> text.toLowerCase() }
def slug = { String text -> text.replaceAll(/\s+/, '-') }
def toSlug = trim >> lower >> slug
println toSlug(' Groovy Course ')
println toSlug('Hello World')
groovy pipeline.groovy
groovy-course
hello-world
The composed closure reads left to right in the order the work happens, which is easier to review than three nested calls. The regular expression is a slashy string, so the pattern needs one backslash.
Related
- Closures, it and parameters: the closure these operators return.
- Memoize and trampoline: the other methods of a closure.
Автор статьи: Arthur Isaev