Well now, you're asking two different questions.
What's the benefit returning a function compared to a value?
Functions can do things. Values just sit there being things. Unless of course the value is a function.
With listing 1 you can say sortBy(0)(x, y)
With listing 2 you have to say sortBy(0, x, y)
Things get fun with listing 1 when you say s = sortBy(0)
because now you can say s(x,y)
or s(y,z)
. It's remembered the 0 so you don't have to pass it when you call s
. That means the benefit is that you can know these values at different times. You don't have to shove them all in at once.
What you've got hold of there in listing 1 is a little thing called a closure. It's almost the same as an object. The first call acts like a constructor. The second is call is like a method call. The difference is that closures only have one method. So you don't have to know it's name. You give it a name and just throw another () after it.
Of course the functional people hate to hear them called methods. It's not a method it's a closure that "has access to it's enclosing lexical scope". Feh, it's a fancy way to say the vars outside of the inner function the same way a method has access to instance member vars. In this case it's the p
that was passed in.
Unlike with objects you get to decide what the method, sorry, closure, is called.