Thursday, May 29, 2008

Currying Closures

This threw my brain for a loop... Groovy code using a "Execute Around Method" pattern:

def tellFortunes(closure) {
Date date = new Date("11/15/2007")

//closure date, "Your day is filled with ceremony"
//closure date, "They're features, not bugs"
// You can curry to avoid sending date repeatedly

postFortune = closure.curry(date)

postFortune "Your day is filled with ceremony"
postFortune "They're features, not bugs"
}

tellFortunes() { date, fortune ->
println "Fortune for ${date} is '${fortune}'"
}

From "Programming Groovy" pps 92-93

Result is:
Fortune for Thu Nov 15 00:00:00 EST 2007 is 'Your day is filled with ceremony'
Fortune for Thu Nov 15 00:00:00 EST 2007 is 'They're features, not bugs'

  1. Basically tellFortunes() accepts date and fortune as parameters, defines a code block which prints the message with the date and fortune in it
  2. This calls postFortune(closure) accepting the code block (called a Closure in Groovy)
  3. the first use of postFortune binds the date to the inbound closure and holds a reference in postFortune
  4. the next two postFortunes pass the string (and the date by use of curry) to the code block thus printing the message each time

No comments: