Skip to content

Instantly share code, notes, and snippets.

@mykolaharmash
Created December 4, 2019 14:11
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 mykolaharmash/7344ab047b49e6cf2d48915f39aee689 to your computer and use it in GitHub Desktop.
Save mykolaharmash/7344ab047b49e6cf2d48915f39aee689 to your computer and use it in GitHub Desktop.
basic monad example
function square (x) {
return [x * x, () => console.log(x * x)]
}
function feet (x) {
return [x * 3.28084, () => console.log(x * 3.28084)]
}
function compose (fn1, fn2) {
return (x) => fn2(fn1(x))
}
function bind (fn) {
return ([x, prevEffect]) => {
const [result, effect] = fn(x)
return [result, () => { prevEffect(); effect()}]
}
}
function unit(x) {
return [x, () => {}]
}
const squareFeet = compose(unit, compose(bind(feet), bind(square)))
const meters = 5
const [result, effect] = squareFeet(meters)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment