Since I started to learn and work with Scala and functional programming in general, there has been one thing I never really got my head around.
Why would I want to make a function that returns a function?
Funny enough I found the answer in a Clojure book; I was reading a chapter about creating a minimalistic logging framework. I was assuming that all I was being told was old news, and then I got my enlightenment: it is awesome that functions can return functions.
Anyway, for those who haven’t got it yet, here is why you would want to have functions returning functions, the code is in Scala:
def optimist(a: Int, b: Int): Int = a + b def pessimist(a: Int, b: Int): Int = a - b def choose_operation(feeling_good: Boolean): (Int, Int) => Int = if (feeling_good) optimist else pessimist val a = 2 val b = 1 val operation_good = choose_operation(feeling_good = true) operation_good(a, b) == 3 val operation_bad = choose_operation(feeling_good = false) operation_bad(a,b) == 1
So, a little detail about what just happened.
Our code has to possible operations: optimist, pessimist
They both take two integers as parameters, do something with them and return a result.
The function choose_operation, based on the parameter feeling_good, returns a function that takes two integers, do something with them and returns a result.
So, we evaluate choose_operation, and we use what ever it returns to calculate the result of a and b.
In this manner we can “configure” how certain operations are perform, based on some initial context. In other words, the fact that functions can return functions, is another way to get rid off the need of passing objects with some state in them.