Skip to content

Instantly share code, notes, and snippets.

@igstan
Created April 22, 2011 11:57
  • Star 32 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save igstan/936519 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
@piotrklibert
Copy link

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.

@igstan
Copy link
Author

igstan commented Feb 24, 2012

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

@snoble
Copy link

snoble commented Dec 7, 2012

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!

@igstan
Copy link
Author

igstan commented Dec 11, 2012

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

@weidagang
Copy link

Very Cool!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment