Created
April 22, 2011 11:57
-
-
Save igstan/936519 to your computer and use it in GitHub Desktop.
State Monad in CoffeeScript
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
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
@snoble I didn't and for a very simple reason. At the time I wasn't aware of this weird scoping CoffeeScript has. I'll edit the gist. Thanks for your suggestion.