Created
January 29, 2022 19:21
-
-
Save jfet97/107bb63ec05458cef3882afb0b4718dd to your computer and use it in GitHub Desktop.
My first initial encoding of the Id monad with a stack safe interpreter
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 FlatMap = (ma, famb) => ({ | |
ma, | |
famb, | |
tag: 'FlatMap' | |
}) | |
const Pure = (a) => ({ a, tag: 'Pure' }) | |
const expression = FlatMap( | |
FlatMap( | |
Pure(6), | |
n => Pure(n) | |
), | |
n => FlatMap( | |
Pure(24), | |
m => Pure(n + m) | |
) | |
) | |
function interpreter(m) { | |
const stack = [] | |
let curr = m | |
while(true) { | |
switch(curr.tag) { | |
case 'FlatMap': { | |
stack.push(curr.famb) | |
curr = curr.ma | |
break; | |
} | |
case 'Pure': { | |
if(stack.length == 0) return curr.a | |
else { | |
const cont = stack.pop() | |
curr = cont(curr.a) | |
} | |
break; | |
} | |
} | |
} | |
} | |
interpreter(expression) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment