08 Function composition

Lesson goal Understand what function composition is and learn to chain functions with compose and pipe, both for three functions and for any number of them.

Function composition combines functions into a new function that calls them in sequence: the result of one function is passed to the next.

Function composition is one of the fundamental concepts on which category theory is based.

// === composing 3 functions ===
// compose :: ((c -> z), (b -> c), (a -> b)) -> a -> z
const compose = (f3, f2, f1) => (...args) => f3(f2(f1(...args)))

// using the function
// our goal
// 1. Get the users whose status is online
// 2. Take their names
// 3. Log the list of names

// fetchAllUsers :: () -> Promise [Object]
const fetchAllUsers = () => new Promise(resolve => resolve([
  {
    name: 'John',
    status: 'online',
    age: 25
  },
  {
    name: 'Alex',
    status: 'offline',
    age: 18
  },
  {
    name: 'Angel',
    status: 'online',
    age: 18
  }
]))

fetchAllUsers() // simulate a request
  .then( // wait for the response
    compose( // pass the result into the composed function
        console.log, // log the results
        (usersActive) => usersActive.map(user => user.name), // collect the names
        (data) => data.filter(user => user.status === 'online'), // filter by status
      )
    )

// the same composition, but within the Array type
// not quite the classic functional approach
fetchAllUsers() // simulate a request
  .then( // wait for the response
      (data) => console.log(
          data
            .filter(user => user.status === 'online')
            .map(user => user.name)
        )
    )

// ===============================

If you noticed in the example above, the functions executed from right to left — mathematically that's fine. But it is often more convenient for the reader to read code from left to right.

So we can rewrite the code above.

// === composing 3 functions in a human-readable order ===
// the order is now left to right
// pipe :: ((a -> b), (b -> c), (c -> z)) -> a -> z
const pipe = (f1, f2, f3) => (...args) => f3(f2(f1(...args)))

// Now the composition is easier to read, left to right

fetchAllUsers() // simulate a request
  .then( // wait for the response
    pipe( // pass the result into the composed function
        (data) => data.filter(user => user.status === 'online'), // filter by status
        (usersActive) => usersActive.map(user => user.name), // collect the names
        console.log, // log the results
      )
    )

// Note

// compose: order in which the functions run
// 3 <- 2 <- 1

// pipe
// 1 -> 2 -> 3

// ===============================

Now imagine a situation where the number of functions is more than 3.

In real projects, use compose or pipe from existing libraries. We will try to build pipe in several ways: imperatively, declaratively and recursively.

// === composing an arbitrary number of functions ===

// === Imperative approach ===
// the order is now left to right
// pipe :: ((a -> b), (b -> c), ..., (y -> z)) -> a -> z
const pipe = (...fns) => (...args) => {

  // split the array of functions into head and tail
  const [ head, ...tail ] = fns

  // variable holding the result of the first function
  // and then of each of the remaining ones
  let result = head(...args)

  // call the remaining functions in a loop and overwrite
  // the variable with each result
  for (const fn of tail) {
    result = fn(result)
  }

  // return the final result
  return result
}

// ===============================

Now let's implement it in a functional style, declaratively.

// === composing an arbitrary number of functions ===

// === Declarative approach ===
// the order is now left to right
// pipe :: ((a -> b), (b -> c), ..., (y -> z)) -> a -> z
const pipe = (...fns) => (arg) => fns.reduce(
    (init, fn) => fn(init), // pass the accumulated value (arg on the first step) to the function
    arg // argument of the first call
  )

// at first glance this function is fine,
// and from a functional point of view a single argument is better and more correct,
// but the first call may need 2 or more arguments
const pipeMultiArgs = (...fns) => (...args) => fns.reduce(
    (init, fn, i) => i === 0 ? fn(...init) : fn(init) , // first call or a later one?
    args // arguments of the first call
)

// ===============================

We can also implement function composition recursively. The call pipe(...tail)(head(arg)) is in tail position, but that does not reduce the number of calls. With proper tail calls (ES2015, strict mode only) a tail call does not grow the stack, but among browser engines only JavaScriptCore (Safari) implements them: V8 (Chrome, Node.js) had them behind a flag and removed them, and SpiderMonkey (Firefox) does not have them. That is why deep recursion in JS needs a trampoline — more on it in the "Recursion" lesson. For a pipe of a few functions, stack depth is not a problem.

// === composing an arbitrary number of functions ===

// === Recursive approach ===
// the order is now left to right
// pipe :: ((a -> b), (b -> c), ..., (y -> z)) -> a -> z
const pipe = (...fns) => (arg) => {

  // base case: only one function is left
  if (fns.length === 1) {
    return fns[0](arg)
  }

  // split into head and tail:
  // the first function and the rest
  const [head, ...tail] = fns

  // call pipe recursively for the tail,
  // and call the first function with the current argument
  return pipe(...tail)(head(arg))
}

// ===============================

Key points

  • Function composition combines functions into a new function that calls them in sequence: the result of one function is passed to the next.
  • Function composition is one of the fundamental concepts on which category theory is based.
  • compose calls the functions right to left, which is fine from a mathematical point of view, while pipe calls them left to right, which is often easier for the reader.
  • pipe for any number of functions can be written imperatively (with a loop), declaratively (with reduce) or recursively; in real projects, use compose or pipe from existing libraries.

Exercises

Exercise 1

In the lesson, compose is written for exactly three functions, while pipe handles any number of them. Write compose for any number of functions: it should call them right to left. Check that compose(square, double, inc) and pipe(inc, double, square) give the same result, while compose(inc, double, square) gives a different one. Hint: arrays have a reduceRight method — the same as reduce, except that it walks the array from right to left.

Starter code

// pipe: the declarative approach from the lesson
// pipe :: ((a -> b), (b -> c), ..., (y -> z)) -> a -> z
const pipe = (...fns) => (arg) => fns.reduce((init, fn) => fn(init), arg)

// compose :: ((y -> z), ..., (b -> c), (a -> b)) -> a -> z
const compose = (...fns) => (arg) => {
  // your code
}

// inc :: Number -> Number
const inc = (n) => n + 1
// double :: Number -> Number
const double = (n) => n * 2
// square :: Number -> Number
const square = (n) => n * n

console.log(pipe(inc, double, square)(3))
console.log(compose(square, double, inc)(3))
console.log(compose(inc, double, square)(3))

Expected output

64
64
19
Show solution
// pipe: the declarative approach from the lesson
// pipe :: ((a -> b), (b -> c), ..., (y -> z)) -> a -> z
const pipe = (...fns) => (arg) => fns.reduce((init, fn) => fn(init), arg)

// compose :: ((y -> z), ..., (b -> c), (a -> b)) -> a -> z
// reduceRight starts with the last function, so it is called first
const compose = (...fns) => (arg) => fns.reduceRight((init, fn) => fn(init), arg)

// inc :: Number -> Number
const inc = (n) => n + 1
// double :: Number -> Number
const double = (n) => n * 2
// square :: Number -> Number
const square = (n) => n * n

// inc, then double, then square: (3 + 1) * 2 = 8, 8 * 8 = 64
console.log(pipe(inc, double, square)(3))
// the same order of calls, just written right to left
console.log(compose(square, double, inc)(3))
// square, then double, then inc: 3 * 3 = 9, 9 * 2 = 18, 18 + 1 = 19
console.log(compose(inc, double, square)(3))

Exercise 2

Use pipe to build a slugify function that turns a lesson title into a URL anchor like the ones this course uses: "Pure Functions" → pure-functions. It trims the spaces at both ends, converts the string to lower case, splits it into words and joins them with hyphens. Make each step a separate function of one argument. Annotate the steps with Hindley–Milner notation and check that the result type of each step matches the argument type of the next one.

Starter code

// pipe :: ((a -> b), (b -> c), ..., (y -> z)) -> a -> z
const pipe = (...fns) => (arg) => fns.reduce((init, fn) => fn(init), arg)

// slugify :: String -> String
const slugify = pipe(
  // your code
)

console.log(slugify('Pure Functions'))
console.log(slugify('  Partial Application  '))
console.log(slugify('Imperative vs Declarative'))

Expected output

pure-functions
partial-application
imperative-vs-declarative
Show solution
// pipe :: ((a -> b), (b -> c), ..., (y -> z)) -> a -> z
const pipe = (...fns) => (arg) => fns.reduce((init, fn) => fn(init), arg)

// trim :: String -> String
const trim = (str) => str.trim()
// toLower :: String -> String
const toLower = (str) => str.toLowerCase()
// words :: String -> [String]
const words = (str) => str.split(' ')
// joinWithDash :: [String] -> String
const joinWithDash = (list) => list.join('-')

// the result of each step is the argument of the next one:
// trim and toLower return a String, words takes a String and returns [String],
// joinWithDash takes [String] and returns a String
// slugify :: String -> String
const slugify = pipe(trim, toLower, words, joinWithDash)

console.log(slugify('Pure Functions'))
console.log(slugify('  Partial Application  '))
console.log(slugify('Imperative vs Declarative'))

Playground

Write and run JavaScript right here — Ramda (R) and Sanctuary (S) are available.

Connected:
playground
Output
—