With the recent rise of functional programming (in recent years) a lot of concepts have made their way into mainstream programming languages. Higher order functions, closures, partial function applications, currying; just to name a few.
But from all these concepts, the last two seem to be in many places used interchangeably, or so may they seem from various articles and code snippets spread over the internet. Don’t get me wrong, I am responsible for such confusion myself, and my co-workers can blame me for it on that time when I tried to explain partial function application.
That, ends today, because I’ve gotten my facts right and demistified these two strange concepts that seamingly do the same thing.
Now, in order to get this started I’d think the best approach should be to start with a formal definition:
In computer science, partial application (or partial function application) refers to the process of fixing a number of arguments to a function, producing another function of smaller arity. Given a function
f:(X × Y × Z) → N, we might fix (or ‘bind’) the first argument, producing a function of typepartial(f):(Y × Z) → N. Evaluation of this function might be represented asfpartial(2,3). Note that the result of partial function application in this case is a function that takes two arguments.
Given a function f of type
f:(X × Y) → Z, currying it makes a functioncurry(f):X → (Y → Z). That is,curry(f)takes an argument of typeXand returns a function of typeY → Z.
Where the following definitions could be used for papply and curry:
papply : (((a × b) → c) × a) → (b → c)
curry : ((a × b) → c) → (a → (b → c))
Now let’s try to define these two functions in JavaScript (the only programming language that everybody knows?)
Before we can safely proceed onwards let’s fiddle around with these two functions in order to get the hang of it:
As you can deduce from the sample code above, it is very clear that in our case we can define one as an application of the other. And let’s do just that with our papply function.
Partial application IS dependent on function currying. And if we’d done our implementation correctly, the following equation should hold true:
curry papply = curry
Again using our previously defined functions (including add) we’ll see if we got it right:
I highly recommend playing with the code in either Firebug or JsFiddle to get the hang of it.
Source of formal and mathematical definitions http://en.wikipedia.org/wiki/Partial_application, http://en.wikipedia.org/wiki/Currying