Skip to content
THOUSAND-SKY edited this page Sep 26, 2022 · 1 revision

How-to

Problem

I want to do something "on the side," like carry execution logs.

Solution

A Writer can carry around an extra value that can be modified easily.

import * as C from "fp-ts/Chain"
import { pipe } from "fp-ts/function"
import * as RA from "fp-ts/ReadonlyArray"
import * as W from "fp-ts/Writer"

const Monad = W.getMonad(RA.getMonoid<string>())
const bind = C.bind(Monad)
const chainFirst = C.chainFirst(Monad)
const Do = Monad.of({})

const logNumber =
  (n: number): W.Writer<ReadonlyArray<string>, number> =>
  () =>
    [n, ["Got number: " + n]]

const multWithLog = pipe(
  Do,
  bind("a", () => logNumber(3)),
  bind("b", () => logNumber(5)),
  chainFirst(() => W.tell(["multiplying"])),
  W.map(({ a, b }) => a * b)
)

console.log(multWithLog()) // => [ 15, [ 'Got number: 3', 'Got number: 5', 'multiplying' ] ]
Clone this wiki locally