Skip to content

Instantly share code, notes, and snippets.

@satyr
Forked from igstan/state-monad.coffee
Created April 22, 2011 13:09
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 satyr/936619 to your computer and use it in GitHub Desktop.
Save satyr/936619 to your computer and use it in GitHub Desktop.
State Monad in Co{co,ffeeScript}
push = (value) -> (stack) -> {value, stack: [value]concat stack}
pop = (stack) -> value: stack.0, stack: stack.slice 1
bind = (stackOperation, continuation) -> (stack) ->
result = stackOperation stack
continuation(result.value) result.stack
result = (value) -> (stack) -> {value, stack}
computation1 = do
\ <- bind push 4
\ <- bind push 5
a <- bind pop
b <- bind pop
result a + ":" + b
computation2 = do
\ <- bind push 2
\ <- bind push 3
a <- bind pop
b <- bind pop
result a + ":" + b
composed = do
a <- bind computation1
b <- bind computation2
result a + " " + b
console.log composed([])value
push = (value) -> (stack) -> {value, stack: [value].concat stack}
pop = (stack) -> value: stack[0], stack: stack.slice 1
bind = (stackOperation, continuation) -> (stack) ->
result = stackOperation stack
continuation(result.value) result.stack
result = (value) -> (stack) -> {value, stack}
computation1 = bind \
push(4), -> bind \
push(5), -> bind \
pop, (a) -> bind \
pop, (b) ->
result a + ":" + b
computation2 = bind \
push(2), -> bind \
push(3), -> bind \
pop, (a) -> bind \
pop, (b) ->
result a + ":" + b
composed = bind \
computation1, (a) -> bind \
computation2, (b) ->
result a + " " + b
console.log composed([]).value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment