Groovy Functional Programming - Higher Order Functions

Lets create a closure which adds two numbers.

def add = { number1, number2 ->
  number1 + number2
}

If you are not familiar with closures, this article has the necessary details.

Let's create a function which accepts this closure and invokes it by passing two numbers.

def perform(def operation) {
  def number1 = 10
  def number2 = 20
  def result = operation(number1, number2)
  println "Result is $result"
}
perform(add) // Result is 30

Note that I opted to express perform as a function. You are free to define a closure instead. Since perform acccepts another closure as an argument, it becomes a higher order function.

Similary we can create another closure multiply which can be passed as an argument to perform to multiply the numbers.

def multiply = { number1, number2 ->
  number1 * number2
}
perform(multiply) // Result is 200

Also we can define higher order functions that return closures.

def createOperation = { String symbol ->
    if (symbol == '+') {
        add
    } else if (symbol == '*') {
        multiply
    }
}

def addOperation = createOperation('+')
perform(addOperation) // Result is 30
def multiplyOperation = createOperation('*')
perform(multiplyOperation) // Result is 200

We could improve this code by moving the definitions of add and multiply closures into createOperation.

def createOperation = { String symbol ->
	 def add = { number1, number2 ->
  		number1 + number2
	 }
	 def multiply = { number1, number2 ->
  		number1 * number2
	 }
    if (symbol == '+') {
        add
    } else if (symbol == '*') {
        multiply
    }
}

You may want to take a look at slides from my FunctionalConf talk for more examples.