Last active
May 6, 2021 19:08
-
-
Save jfet97/c746bd60b8556f7d2fa5e1f81798f7a0 to your computer and use it in GitHub Desktop.
Basic monadic IO implementation
This file contains 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
const IO = (function(io) { | |
io.return = x => () => x; | |
io.unit = io.return; | |
io.of = io.return; | |
io.bind = a => fa => () => fa(a())(); | |
io.flatten = aa => io.bind(aa)(a => io.bind(a)(ar => io.return(ar))); | |
io.join = io.flatten | |
io.takeLeft = a => b => io.bind(a)(ar => io.bind(b)(_ => io.return(ar))); | |
io.takeRight = a => b => io.bind(a)(_ => b); | |
io.pure = io.return; | |
io.ap = af => a => io.bind(af)(f => io.bind(a)(ar => io.return(f(ar)))); | |
io.fmap = f => a => io.ap(io.return(f))(a); | |
io.io = fn => (...args) => io.bind(io.return(args))((args) => io.return(fn(...args))); | |
io.run = a => a(); | |
return Object.freeze(io); | |
})({}); | |
// utils | |
function sequence(ms, M) { | |
return ms.reduce((acc, m) => M.bind(acc)(l => M.bind(m)(mr => M.return(l.concat([mr])))), M.return([])); | |
} | |
function run(m, M) { | |
return M.run(m) | |
} | |
// example: | |
const print = IO.io(console.log) | |
const prompt = IO.io(window.prompt) | |
function doStuffReturnIO(x) { | |
if(typeof +x === "number" && Number.isNaN(+x) === false) { | |
return print(`Ho ricevuto un numero: ${x}`) | |
} else if(typeof x === "string") { | |
return print(`Ho ricevuto una stringa: ${x}`) | |
} else { | |
return print(`Ho ricevuto un boh: `, JSON.stringify(x, null, 4)) | |
} | |
} | |
const readFromUserThenDoStuff = IO.bind(prompt("Inserisci qualcosa :)"))(doStuffReturnIO) | |
const readFromUserThenDoStuff3TimesAfterGreetBeforeByeBye = sequence( | |
[ | |
print("Benvenuto"), | |
readFromUserThenDoStuff, | |
readFromUserThenDoStuff, | |
readFromUserThenDoStuff, | |
print("Alla prossima!"), | |
], | |
IO | |
) | |
IO.run(readFromUserThenDoStuff3TimesAfterGreetBeforeByeBye) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment