Functions that return functions, how I reason about it

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[1]; 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.


One thought on “Functions that return functions, how I reason about it

  1. Jody Watley? LolAnd I was gonna mention Usain Bolt too. He broke the 200 meter record (19.19) are they gonna test to see if he39#&;s actually human or as you say a cheetah.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s