JavaScript Monads Made Simple

Eric Elliott
Sep 12, 2017 · 16 min read
Image for post
Image for post
Smoke Art Cubes to Smoke — MattysFlicks — (CC BY 2.0)


const x = 20;             // Some data of type `a`
const f = n => n * 2; // A function from `a` to `b`
const arr = Array.of(x); // The type lift.
// JS has type lift sugar for arrays: [x]
// .map() applies the function f to the value x
// in the context of the array.
const result = arr.map(f); // [40]
[[1], [2, 3], [4]].flat(); // [1, 2, 3, 4] or
[].concat.apply([], [[1], [2, 3], [4]]); // [1, 2, 3, 4]

You’re probably already using monads.

g:           a => b
f: b => c
h = f(g(a)): a => c
g:             F(a) => F(b)
f: F(b) => F(c)
h = f(g(Fa)): F(a) => F(c)
g:                  a => M(b)
f: b => M(c)
h = composeM(f, g): a => M(c)
g:             a => M(b) flattens to => b
f: b maps to => M(c)
h composeM(f, g):
a flatten(M(b)) => b => map(b => M(c)) => M(c)
getUserById(id: String) => Promise(User)
hasPermision(User) => Promise(Boolean)
const compose = (...fns) => x => fns.reduceRight((y, f) => f(y), x);const trace = label => value => {
console.log(`${ label }: ${ value }`);
return value;
};
{
const label = 'API call composition';
// a => Promise(b)
const getUserById = id => id === 3 ?
Promise.resolve({ name: 'Kurt', role: 'Author' }) :
undefined
;
// b => Promise(c)
const hasPermission = ({ role }) => (
Promise.resolve(role === 'Author')
);
// Try to compose them. Warning: this will fail.
const authUser = compose(hasPermission, getUserById);
// Oops! Always false!
authUser(3).then(trace(label));
}
{
const composeM = chainMethod => (...ms) => (
ms.reduce((f, g) => x => g(x)[chainMethod](f))
);
const composePromises = composeM('then'); const label = 'API call composition'; // a => Promise(b)
const getUserById = id => id === 3 ?
Promise.resolve({ name: 'Kurt', role: 'Author' }) :
undefined
;
// b => Promise(c)
const hasPermission = ({ role }) => (
Promise.resolve(role === 'Author')
);
// Compose the functions (this works!)
const authUser = composePromises(hasPermission, getUserById);
authUser(3).then(trace(label)); // true
}

What Monads are Made of

const MyMonad = value => ({
// <... insert arbitrary chain and of here ...>
map (f) {
return this.chain(a => this.constructor.of(f(a)));
}
});
{ // Identity monad
const Id = value => ({
// Functor mapping
// Preserve the wrapping for .map() by
// passing the mapped value into the type
// lift:
map: f => Id.of(f(value)),
// Monad chaining
// Discard one level of wrapping
// by omitting the .of() type lift:
chain: f => f(value),
// Just a convenient way to inspect
// the values:
toString: () => `Id(${ value })`
});
// The type lift for this monad is just
// a reference to the factory.
Id.of = Id;
{
const x = 20; // The value
const p = Promise.resolve(x); // The context
const f = n =>
Promise.resolve(n * 2); // The function
const result = p.then(f); // The application result.then(
r => console.log(r) // 40
);
}

Building monadic (aka Kleisli) composition

const composeM = method => (...ms) => (
ms.reduce((f, g) => x => g(x)[method](f))
);
{
// The algebraic definition of function composition:
// (f ∘ g)(x) = f(g(x))
const compose = (f, g) => x => f(g(x));
const x = 20; // The value
const arr = [x]; // The container
// Some functions to compose
const g = n => n + 1;
const f = n => n * 2;
// Proof that .map() accomplishes function composition.
// Chaining calls to map is function composition.
trace('map composes')([
arr.map(g).map(f),
arr.map(compose(f, g))
]);
// => [42], [42]
}
const composeMap = (...ms) => (
ms.reduce((f, g) => x => g(x).map(f))
);
{
const label = 'Promise composition';
const g = n => Promise.resolve(n + 1);
const f = n => Promise.resolve(n * 2);
const h = composePromises(f, g); h(20)
.then(trace(label))
;
// Promise composition: 42
}
{
const composePromises = (...ms) => (
ms.reduce((f, g) => x => g(x).then(f))
);
const label = 'Promise composition'; const g = n => Promise.resolve(n + 1);
const f = n => Promise.resolve(n * 2);
const h = composePromises(f, g); h(20)
.then(trace(label))
;
// Promise composition: 42
}
const composeM = method => (...ms) => (
ms.reduce((f, g) => x => g(x)[method](f))
);
const composePromises = composeM('then');
const composeMap = composeM('map');
const composeFlatMap = composeM('flatMap');

The monad laws

The Identity Laws

Image for post
Image for post
Left and right identity
Image for post
Image for post
Identity morphisms

Associativity

h(x).chain(x => g(x).chain(f)) ==== (h(x).chain(g)).chain(f)

Proving the Monad Laws

{ // Identity monad
const Id = value => ({
// Functor mapping
// Preserve the wrapping for .map() by
// passing the mapped value into the type
// lift:
map: f => Id.of(f(value)),
// Monad chaining
// Discard one level of wrapping
// by omitting the .of() type lift:
chain: f => f(value),
// Just a convenient way to inspect
// the values:
toString: () => `Id(${ value })`
});
// The type lift for this monad is just
// a reference to the factory.
Id.of = Id;
const g = n => Id(n + 1);
const f = n => Id(n * 2);
// Left identity
// unit(x).chain(f) ==== f(x)
trace('Id monad left identity')([
Id(x).chain(f),
f(x)
]);
// Id monad left identity: Id(40), Id(40)
// Right identity
// m.chain(unit) ==== m
trace('Id monad right identity')([
Id(x).chain(Id.of),
Id(x)
]);
// Id monad right identity: Id(20), Id(20)
// Associativity
// m.chain(f).chain(g) ====
// m.chain(x => f(x).chain(g)
trace('Id monad associativity')([
Id(x).chain(g).chain(f),
Id(x).chain(x => g(x).chain(f))
]);
// Id monad associativity: Id(42), Id(42)
}

Conclusion

Level Up Your Skills with Live 1:1 Mentorship

Image for post
Image for post
https://devanywhere.io/

JavaScript Scene

JavaScript, software leadership, software development, and…

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store