Skip to content

Instantly share code, notes, and snippets.

@jfet97
Created January 29, 2022 19:21
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 jfet97/107bb63ec05458cef3882afb0b4718dd to your computer and use it in GitHub Desktop.
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
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