Skip to content

Instantly share code, notes, and snippets.

@AlexKVal
Forked from getify/simplest-monad.js
Created January 21, 2022 21:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AlexKVal/844f34656e2e0f2f64c1c8b5f6d6aa94 to your computer and use it in GitHub Desktop.
Save AlexKVal/844f34656e2e0f2f64c1c8b5f6d6aa94 to your computer and use it in GitHub Desktop.
what's the simplest monad implementation we could express in JS?
function Identity(v) {
return { val: v };
}
function chain(m,fn) {
return fn(m.val);
}
// ^^^ that's it!
// extra helpers:
function IdentityMap(m,fn) {
return chain( m, v => Identity(fn(v)) );
}
function inc(v) { return Identity(v + 1); }
function double(v) { return Identity(v * 2); }
// use Identity:
const fortyOne = Identity(41); // { val: 41 }
// const fortyTwo = chain( fortyOne, inc );
const fortyTwo = IdentityMap( fortyOne, v => v + 1 ); // { val: 42 }
// monad law #1: Left Identity
chain( Identity(41), inc ); // { val: 42 }
// monad law #2: Right Identity
chain( Identity(42), Identity ); // { val: 42 }
// monad law #3: Associativity
chain( chain( Identity(20), inc ), double ); // { val: 42 }
chain( Identity(20), v => chain( inc(v), double ) ); // { val: 42 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment