Monday, April 19, 2010

Groovy Goodness: New Ways to Curry

A couple of weeks ago I gave a presentation about Groovy and the subject of closures and the curry() method was covered. Someone from the audience asked if the arguments could be 'curried' from right to left instead of from left to right. I had to say no, but since Groovy 1.7.2 this isn't true anymore. Groovy 1.7.2 adds the rcurry() method which uses a right to left order. And as a bonus we also have got the ncurry() method where we can supply a parameter value for an argument of the closure at a specific index.

import org.apache.commons.lang.RandomStringUtils as RSU

def randomClosure = { size, letters, numbers ->
    // Invoke RandomStringUtils.random() method 
    RSU.random size, letters, numbers

def randomNumbers = randomClosure.rcurry(false, true)  // letters = false, numbers = true
def randomLetters = randomClosure.ncurry(1, true, false) // letters = true, numbers = false

println randomClosure(10, true, true)  // Sample output: VG7mffNAdA
println randomNumbers(10)              // Sample output: 8099670444
println randomLetters(10)              // Sample output: ZOHlHewEPU


Post a Comment