Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Partial Function Application and bind()

Partial Function Application and bind()

Danielle Brook-Roberge

November 05, 2015
Tweet

More Decks by Danielle Brook-Roberge

Other Decks in Programming

Transcript

  1. 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)
  2. 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.
  3. 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.
  4. 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.
  5. DRYing Code with Partial Application • Partial application can be

    useful to remove code duplication while preserving an existing API.
  6. 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.
  7. 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.