Thursday, January 14, 2010

MapReduce In Groovy

I came across an old post on Joel on Software about MapReduce and functions as first class citizens. You can read it here. I thought I'd have a go at doing the examples in Groovy. I know these examples have been abstraction already in 1.5+, but that takes the fun out of this exercise.

Closures to sum and join
def d = [1,2,3,4]
def c = ["a","b","c"]

def sum = {param ->
  def result = 0
  param.each{result += it}
  result
}

def join2 = {param ->
  def result = ""
  param.each{result += it}
  result
}

println sum(d) // 10
println join2(c) // abc


Abstract out the essence of sum and join into reduce
def d = [1,2,3,4]
def c = ["a","b","c"]

def reduce = { fn, a, init ->
  def result = init
  a.each { result = fn(result,it) }  
  result
}

def addition = {param1, param2 -> param1+param2}

println reduce (addition, d, 0)  // 10
println reduce (addition, c, "") // abc


This isn't going to take on Google, it was just a little exercise in functions as a first class citizens.

0 comments:

Post a Comment