Created
December 4, 2019 14:11
-
-
Save mykolaharmash/7344ab047b49e6cf2d48915f39aee689 to your computer and use it in GitHub Desktop.
basic monad example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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