Groovy Functional Programming - Function (Closure) Composition

Consider the following closures.

def increment = { number ->
    number + 1
}

def square = { number ->
    number * number
}

println increment(2) // 3
println square(2) // 4

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

Now suppose you want to calculate the square of a number and increment the result by 1, you could achieve it using a closure.

def incrementSquareByOne = { number ->
    increment(square(number))
}
println incrementSquareByOne(2) // 5

If you are an experienced developer, you will agree that this kind of chaining functions can be seen very often( unless you write long methods with a lot of duplicate code). Hence programming languages that support functional style provide a syntax for composing functions - which helps the developer to express the intention in a crisp and clear way. Function(closure) composition can be achieved in Groovy in the following way.

def incrementSquareByOne = increment << square
println incrementSquareByOne(2) // 5

That code was more readable than before, isn't it?

Closure incrementSquareByOne achieves the functionality of calling square and passing the result into increment. Note the direction of double arrow << specifies the order in which closures are invoked. If you wish, you could compose the closures from left to right as well.

def incrementSquareByOne = square >> increment
println incrementSquareByOne(2) // 5

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