19 Side effects in function composition

Lesson goal Learn to add side effects to a function composition, such as logging for debugging or actions the program logic requires, so that the data keeps flowing down the chain unchanged.

Based on the principles of functional programming, one might think that creating side effects within function composition is forbidden. But in reality, any program, and especially web development, will create some side effect no matter what (DOM operations, input/output operations, logging, and so on ...).

In real-world cases, side effects within function composition can be useful to us mainly in two situations:

  1. Debugging the composition and logging it, in case of errors or simply to understand the execution flow and how the input data changes within the function composition.
  2. Creating a side effect within the program according to its logic and continuing the execution of the function composition.

Let's try to inspect the intermediate results within a function composition by creating a side effect in the form of logging the data.

// A program that takes the user's money,
// compares it with the product price
// and reports whether the user can afford the product
// ===============================
// pipe :: ((a -> b), (b -> c), ..., (y -> z)) -> a -> z
const pipe = (...fns) => (data) =>
                              fns
                                .reduce((init, fn) => fn(init), data)

// a test user with $10,000
const dataUser = {
  name: 'John',
  money: 10000,
}

// a product priced at $8,000
const product = {
  name: 'car',
  model: 'toyota',
  price: 8000
}

// prop :: String -> Record -> a
const prop = (prop) => (data) => data[prop]

// lte :: Number -> Number -> Boolean
const lte = (a) => (b) => a <= b

const pipeline = pipe(
  prop ('money'), // get the user's money
  lte (prop ('price') (product)), // check that the product price is not greater than the user's money
  (success) => success ? 'the product can be purchased' : "you don't have enough money"
  // report whether the user can buy the product or lacks the money
)

// run the composition
const resultMsg = pipeline (dataUser)

console.log(resultMsg) // the product can be purchased

But how do we obtain the results of each function call in pipeline (prop ('money') ...), if there won't even be any errors in the composition and we simply want to debug the code.

Let's write a universal utility for any case in the chain of composition calls.

// A utility that calls the function it was given
// and passes the argument further down the composition
// ===============================
// tapD :: (a -> *) -> a -> a
const tapD = (fn) => (arg) => {

  // check that the first argument
  // really is a function
  if (typeof fn === 'function') {
    // call the function with the argument
    fn (arg)
  }

  // don't forget to pass the argument on
  // to the next call in the composition
  return arg
}

// it can be shortened to one line
// tap :: (a -> *) -> a -> a
const tap = (fn) => (arg) => (fn (arg), arg)

// now let's prepare a utility
// that logs the data
// after each call in the composition

// standard console output
const log = console.log

// create the logger
const logger = tap (log)

// put the logger into the chain of function calls
// and run the chain right away
pipe(
  prop ('money'),
  logger, // 10000
  lte (prop ('price') (product)),
  logger, // true
  (success) => success ? 'the product can be purchased' : "you don't have enough money",
  logger, // 'the product can be purchased'
) (dataUser)

Key points

  • Any program, and especially web development, creates side effects: DOM operations, input and output, logging.
  • In function composition, side effects are needed mainly in two cases: for debugging and logging, and for actions the program logic requires, after which the composition keeps running.
  • The tap :: (a -> *) -> a -> a utility calls the given function with the argument and returns that same argument, so the next function in the composition receives the data unchanged.
  • A logger built as tap (console.log) and placed between the steps of pipe prints the intermediate result after each call.

Exercises

Exercise 1

To debug the total pipeline, someone put console.log straight between its steps, and the pipeline broke: console.log returns undefined, and the next step receives it instead of the data. Write tap and a labelled logger tapLog :: String -> a -> a that prints the line "label: value" (the value via JSON.stringify) and returns its argument unchanged. Put tapLog after each step of total instead of console.log, with the labels "items", "sum" and "discounted".

Starter code

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

// the cart: price and quantity of each item
const cart = [
  { name: 'book', price: 20, qty: 2 },
  { name: 'pen', price: 5, qty: 4 },
  { name: 'bag', price: 50, qty: 1 },
]

// your code: tap and tapLog

// total :: [Object] -> Number
const total = pipe(
  (items) => items.map((item) => item.price * item.qty), // the cost of each item
  console.log, // debugging: prints, but returns undefined
  (sums) => sums.reduce((sum, x) => sum + x, 0), // the total sum
  (sum) => (sum > 100 ? sum - 10 : sum), // a discount of 10 if the sum is over 100
)

console.log(total(cart))

Expected output

items: [40,20,50]
sum: 110
discounted: 100
100
Show solution
// pipe :: ((a -> b), (b -> c), ..., (y -> z)) -> a -> z
const pipe = (...fns) => (data) => fns.reduce((acc, fn) => fn(acc), data)

// the cart: price and quantity of each item
const cart = [
  { name: 'book', price: 20, qty: 2 },
  { name: 'pen', price: 5, qty: 4 },
  { name: 'bag', price: 50, qty: 1 },
]

// tap :: (a -> *) -> a -> a
const tap = (fn) => (arg) => (fn(arg), arg)

// a labelled logger: prints the value and returns it unchanged
// tapLog :: String -> a -> a
const tapLog = (label) => tap((value) => console.log(`${label}: ${JSON.stringify(value)}`))

// total :: [Object] -> Number
const total = pipe(
  (items) => items.map((item) => item.price * item.qty), // the cost of each item
  tapLog('items'),
  (sums) => sums.reduce((sum, x) => sum + x, 0), // the total sum
  tapLog('sum'),
  (sum) => (sum > 100 ? sum - 10 : sum), // a discount of 10 if the sum is over 100
  tapLog('discounted'),
)

console.log(total(cart))

Exercise 2

The second case is a side effect the program logic requires. Write tapWhen :: (a -> Boolean) -> (a -> *) -> a -> a: it calls the effect function only if the predicate returned true, and returns the argument in any case. Use it at the start of the checkout pipeline to add the user's name to the declined log when they don't have enough money for the product. The composition must still run to the end and return a message.

Starter code

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

// tap :: (a -> *) -> a -> a
const tap = (fn) => (arg) => (fn(arg), arg)

// your code: tapWhen

// the product
const product = { name: 'car', price: 8000 }

// the log: who didn't have enough money
const declined = []

// checkout :: Object -> String
const checkout = pipe(
  // your code: add to the declined log
  (user) => user.money >= product.price, // is there enough money
  (success) => (success ? 'the product can be purchased' : "you don't have enough money"),
)

const users = [
  { name: 'John', money: 10000 },
  { name: 'Anna', money: 5000 },
  { name: 'Mike', money: 8000 },
]

users.map(checkout).forEach((message) => console.log(message))
console.log(`not enough money: ${declined.join(', ')}`)

Expected output

the product can be purchased
you don't have enough money
the product can be purchased
not enough money: Anna
Show solution
// pipe :: ((a -> b), (b -> c), ..., (y -> z)) -> a -> z
const pipe = (...fns) => (data) => fns.reduce((acc, fn) => fn(acc), data)

// tap :: (a -> *) -> a -> a
const tap = (fn) => (arg) => (fn(arg), arg)

// the effect fires only on the condition; the argument always moves on
// tapWhen :: (a -> Boolean) -> (a -> *) -> a -> a
const tapWhen = (pred) => (fn) => tap((arg) => {
  if (pred(arg)) fn(arg)
})

// the product
const product = { name: 'car', price: 8000 }

// the log: who didn't have enough money
const declined = []

// checkout :: Object -> String
const checkout = pipe(
  tapWhen((user) => user.money < product.price)((user) => declined.push(user.name)),
  (user) => user.money >= product.price, // is there enough money
  (success) => (success ? 'the product can be purchased' : "you don't have enough money"),
)

const users = [
  { name: 'John', money: 10000 },
  { name: 'Anna', money: 5000 },
  { name: 'Mike', money: 8000 },
]

users.map(checkout).forEach((message) => console.log(message))
console.log(`not enough money: ${declined.join(', ')}`)

Playground

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

Connected:
playground
Output
—