Skip to content

Instantly share code, notes, and snippets.

@joyrexus
Forked from igstan/state-monad.coffee
Created May 28, 2013 15:46
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 joyrexus/5663738 to your computer and use it in GitHub Desktop.
Save joyrexus/5663738 to your computer and use it in GitHub Desktop.
State monad in CoffeeScript
push = (element) -> (stack) ->
newStack = [element].concat stack
{value: element, stack: newStack}
pop = (stack) ->
element = stack[0]
newStack = stack.slice 1
{value: element, stack: newStack}
bind = (stackOperation, continuation) -> (stack) ->
opResult = stackOperation stack
(continuation opResult.value) opResult.stack
result = (value) -> (stack) ->
{value: value, stack: stack}
initialStack = []
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
finalResult = composed initialStack
console.log finalResult.value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment