Skip to content

Instantly share code, notes, and snippets.

@getify
Last active July 20, 2022 19:18
Show Gist options
  • Save getify/3f05b7106913161f580fd235d0b82097 to your computer and use it in GitHub Desktop.
Save getify/3f05b7106913161f580fd235d0b82097 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