Partial Application
— JavaScript, Functional Programming
The previous note was about the Currying. In this one we will focus on quite similar technique called Partial Application.
Let's start with similarities. Both techniques reduces the function arity and as a result produces the function that takes less number of arguments than the primary function. The difference is how they handle this topic.
Technique | Description | Example |
---|---|---|
Currying | Transforms multi-argument function into a sequence of many unary functions. | const foo (a,b,c) => f(a) => f(b) => f(c) => d |
Partial Application | Applies to the function any numbers of arguments and returns the function that takes the rest rest of arguments. | const foo (a,b,c) => f(a) => f(b,c) => d |
To create a partial function we can use a bind method. It's not the best approach, because the bind function besides the arguments that we want to apply needs the context as the first argument. Nowadays, thanks to ES6 and arrows functions, the bind function is used less than in the past, but we can still meet with the binding, and partial application is a good example of this.
1const foo = (a, b, c) => a + b + c2const bar = foo.bind(null, 1, 2)34bar(0) // 35bar(10) // 13
We can get the same results using any library that supports the FP paradigm like Lodash, Underscore, or Ramda.
1//Ramda.js2const bar = R.partial(foo, [1])3bar(2, 3) // 645//Lodash6const bar = _.partial(foo, 1)7bar(2, 3) // 6
Currying and Partial application are useful because they allow us to create reusable pure functions and they support functions composition.