Ubuntu insights, Programming in groovy, java, et als!

Wednesday, May 09, 2012

Currying in Groovy

Currying is a process of transforming a function of n arguments into n partial functions of one argument each.

Although I was acquainted with the math part of it. I found it hard to implement it in code. I
couldn't help but posting Tim Yate's sample snippet to my question on SO about a simple implementation for currying in groovy.

def greet = { greeting, person -> "$greeting $person" }

// This takes a closure and a default parameter
// And returns another closure that only requires the
// missing parameter
def currier = { fn, param ->
  { person1 ->
     fn( param, person1 )

// We can then call our currying closure
def hi = currier( greet, 'Hi' )

// And test it out
hi( 'Vamsi' )

Here's an other pointer for doing functional programming in groovy. 


Post a Comment