Slide 1

Slide 1 text

Partial Function Application and bind() Daniel Brook-Roberge October 22, 2015 Engineering Meeting

Slide 2

Slide 2 text

What is Partial Function Application? ● Partial application is an operation on a function and one or more parameter values, that produces a new function with the given parameter values “fixed”. ● partial(f, 5) → g(x) ● g(x) == f(5, x)

Slide 3

Slide 3 text

Currying and Partial Application ● Currying is another operation on a function, that converts a function of multiple parameters into a series of functions of a single parameter: f(x, y, z) → f(x)(y)(z) ● Functions are automatically curried in several functional languages, such as Haskell and F#. ● A curried function is trivial to partially apply, as we can just execute a subset of the functions: f(2) → g(y, z) = f(x, y, z) ● As such, currying and partial application are often confused.

Slide 4

Slide 4 text

Function.bind() in Javascript ● ES5 provides a function method bind() that can be used for partial application. ● The first parameter to bind() is bound to this inside the function, and subsequent parameters are bound to the function parameters in order.

Slide 5

Slide 5 text

Partial Application and Callbacks ● Partial application is very useful for callbacks, as it can provide a callback with parameters set at registration time alongside parameters set at call time.

Slide 6

Slide 6 text

DRYing Code with Partial Application ● Partial application can be useful to remove code duplication while preserving an existing API.

Slide 7

Slide 7 text

Example from Web Push Client

Slide 8

Slide 8 text

Partial Application and Function Parameters ● Partial application is useful when combined with arguments that are functions. ● This allows a function to be configurable for a variety of applications.

Slide 9

Slide 9 text

Summary ● Partial function application is a technique for specifying some of the parameters to a function separately from the function call itself. ● We can use it to customize functions for callbacks or to modularize logic for a DRYer codebase. ● Javascript provides Function.bind for partially applying a function. ● This is a technique that I find myself using all the time now that I am familiar with it.