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