Published
Edited
Jul 3, 2019
2 stars
Insert cell
Insert cell
resultA = Math.pow(Math.sin(Math.PI / 4), 2)
Insert cell
Insert cell
sin = (a) => Math.sin(a)
Insert cell
square = (b) => Math.pow(b, 2)
Insert cell
Insert cell
squareSin = (c) => square(sin(c))
Insert cell
resultB = squareSin(Math.PI / 4)
Insert cell
Insert cell
assertEqual(resultA, resultB)
Insert cell
Insert cell
compose = (f, g) => (a) => f(g(a))
Insert cell
squareSinUsingCompose = compose(square, sin)
Insert cell
resultC = squareSinUsingCompose(Math.PI / 4)
Insert cell
Insert cell
loggingSin = (a) => [Math.sin(a), `Computing the sin of ${a}.`]
Insert cell
loggingSquare = (b) => [Math.pow(b, 2), `Computing the square of ${b}.`]
Insert cell
loggingSin(Math.PI / 4)
Insert cell
loggingSquare(3)
Insert cell
Insert cell
loggingCompose = (f, g) => (a) => {
const [resultA, messageA] = g(a)
const [resultB, messageB] = f(resultA)
return [resultB, `${messageA} ${messageB}`.trim()]
}
Insert cell
loggingSquareSinUsingLoggingCompose = loggingCompose(loggingSquare, loggingSin)
Insert cell
resultD = loggingSquareSinUsingLoggingCompose(Math.PI / 4)
Insert cell
Insert cell
bind = (f) => ([n, s]) => {
const [m, p] = f(n)
return [m, `${s} ${p}`.trim()]
}
Insert cell
Insert cell
loggingSquareSinUsingCompose = compose(bind(loggingSquare), bind(loggingSin))
Insert cell
resultE = loggingSquareSinUsingCompose([Math.PI / 4, ''])
Insert cell
Insert cell
unit = (a) => [a, '']
Insert cell
Insert cell
resultF = loggingSquareSinUsingCompose(unit(Math.PI / 4))
Insert cell
Insert cell
resultG = compose(loggingSquareSinUsingCompose, unit)(Math.PI / 4)
Insert cell
Insert cell
lift = (f) => compose(unit, f)
Insert cell
md`Let's try to add a simple function just to check that everything works as expected.`
Insert cell
half = n => n / 2
Insert cell
half(3)
Insert cell
composableHalf = bind(lift(half))
Insert cell
composableHalf([3, ""])
Insert cell
Insert cell
loggingHalfSquareSinUsingCompose = compose(compose(composableHalf, loggingSquareSinUsingCompose), unit)(Math.PI / 4)
Insert cell
Insert cell
Insert cell

{
const f = x => [2 * x, ''];
// bind(f)(unit(x)) ≡ f(x)
return assertEqual(bind(f)(unit(1)), f(1))
}

Insert cell
Insert cell
Insert cell
{
const m = [1, 'a'];
// bind(unit)(m) ≡ m
return assertEqual(bind(unit)(m), m)
}
Insert cell
Insert cell
{
const m = [5, 'a']
const f = x => [2 * x, 'b'];
const g = x => [x - 1, 'c'];
// bind(g)(bind(f)(m)) ≡ bind(x => bind(g)(f(x)))(m)
return assertEqual(bind(g)(bind(f)(m)), bind(x => bind(g)(f(x)))(m))
}
Insert cell
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more