public
Last active

State Monad in CoffeeScript

  • Download Gist
state-monad.coffee
CoffeeScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
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

I don't know who you are, but I want to thank you from the bottom of my heart! Thanks to you and your implementation of state monad in language that I actually know (as opposed to Haskell or Clojure) I was able to finally grasp one more kind of monad. I can now say that I understand List monad, Promises monad (I don't know what's it proper name, I mean this: http://blog.jcoglan.com/2011/03/11/promises-are-the-monad-of-asynchronous-programming/), Writer monad and now State monad.

So, many thanks once again! I'd be very happy if you could implement some other types of monads in Coffee :) I found your implementation minimal yet instructive and very readable; I looked at forks of this gist but comments actually made it harder for me to follow.

Thanks! I'm glad you found it useful. I created this gist as additional material for a longer article I wrote while I tried myself to understand monads using JavaScript. http://igstan.ro/posts/2011-05-02-understanding-monads-with-javascript.html

have you considered changing the name of the 'result' variable in 'bind'? it's just that because of coffee's weird scope it might be confusing that there two different 'result' var's here. if the definition of 'result' were to come before 'bind' then they would be the same var

also thanks for making this!

@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.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.