Skip to content

Instantly share code, notes, and snippets.

@awto
Last active June 9, 2018 11:15
Show Gist options
  • Save awto/0352bafa822f0d3594db61fdd4957f3d to your computer and use it in GitHub Desktop.
Save awto/0352bafa822f0d3594db61fdd4957f3d to your computer and use it in GitHub Desktop.
Converting Coroutine to State monads
function* incr() {
return (yield set((yield get) + 1))
}
function* incrX2() {
return (yield* incr()) + (yield* incr())
}
const main = state(incrX2)
// framework
function state(iter) {
const i = iter()[Symbol.iterator]()
return walk()
function walk(arg) {
const step = i.next(arg)
return step.done ?
state => [state, step.value] :
state => {
const [next, value] = step.value(state)
return walk(value)(next)
}
}
}
function set(s) { return _ => [s, s] }
function get(s) { return [s, s] }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment