Monads in CoffeeScript
by Alessandro Vernet
HTML
<script src="http://jashkenas.github.com/coffee-script/extras/coffee-script.js"></script>
<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<ol id="result"></ol>
<script type="text/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) ->
result = stackOperation stack
(continuation result.value) result.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
finalResult = computation1 initialStack
console.log finalResult.value
</script>