Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 5

[ 103 ]

Curried parameters


Curried parameters does not mean that we are including our parameters as
ingredients in an Indian dish. Currying is a term borrowed from functional
programming that is named after its inventor, the logician Haskell Curry. Currying
involves transforming a function or method that takes multiple arguments in such a
way that it can be called as a chain of functions or methods taking a single argument.


In practice, with Groovy closures, this means we can "curry" a closure by prepacking
one or more of its parameters. This is best illustrated with an example:


given: "a closure taking three parameters"
def indian = { style, meat, rice ->
return "${meat} ${style} with ${rice} rice."
}
when: "we curry the closure with different first parameters"
def vindaloo = indian.curry "Vindaloo"
def korma = indian.curry "Korma"
then: "it is as if we passed these parameters together"
vindaloo "Chicken","Fried" == "Chicken Vindaloo with Fried rice."
korma "Lamb","Boiled" == "Lamb Korma with Boiled rice."

The preceding indian closure accepts three parameters. We can prepack its first
parameter by calling the curry method of the closure. The curry method returns
a new instance of the closure with one or more of its parameters set. The variables
vindaloo and korma contain instances of the indian closure with the first parameter
style set. We refer to these as curried closures.


We can curry multiple parameters in one go. Parameters will always be curried in
their order of declaration, so in this case, chickitikka will cause the style and
meat parameters to be set:


when: "we curry the closure with multiple parameters"
def chickitikka = indian.curry "Tikka", "Chicken"
then: "it is the same as if we passed these parameters together"
chickitikka "Boiled" == "Chicken Tikka with Boiled rice."

If we take a curried closure such as korma and curry it again, we now curry the
subsequent parameters from the original indian closure. The style and meat
parameters are now curried into the variable lambKorma:


when: "we curry a curried closure"
def lambKorma = korma.curry "Lamb"
then:
lambKorma "Fried" == "Lamb Korma with Fried rice."
Free download pdf