Skip to content

Przemysław Konieczniak - Dev Notes

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.

TechniqueDescriptionExample
CurryingTransforms multi-argument function into a sequence of many unary functions.const foo (a,b,c) => f(a) => f(b) => f(c) => d
Partial ApplicationApplies 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 + c
2const bar = foo.bind(null, 1, 2)
3
4bar(0) // 3
5bar(10) // 13

We can get the same results using any library that supports the FP paradigm like Lodash, Underscore, or Ramda.

1//Ramda.js
2const bar = R.partial(foo, [1])
3bar(2, 3) // 6
4
5//Lodash
6const 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.

Resources

© 2020 by Przemysław Konieczniak - Dev Notes. All rights reserved.