Skip to content

Instantly share code, notes, and snippets.

@joyrexus
Created May 24, 2013 20:17
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/5646225 to your computer and use it in GitHub Desktop.
Save joyrexus/5646225 to your computer and use it in GitHub Desktop.
Maybe monad in CoffeeScript.
MONAD = (modifier) ->
prototype = Object.create null
unit = (value) ->
monad = Object.create prototype
monad.bind = (func, args...) -> func(value, args...)
modifier(monad, value) if typeof modifier is 'function'
monad
unit.lift = (name, func) ->
prototype[name] = (args...) ->
unit @bind(func, args...)
unit
unit
PRINT = (args...) -> print x.toUpperCase() for x in args
# id = MONAD().lift('print', PRINT) # construct an identity monad without modifier
# monad = id null
# monad.print() # complains!
modifier = (monad, value) ->
if not value?
monad.is_null = true
monad.bind = -> monad # do nothing w/ bound funcs on null values
maybe = MONAD(modifier) # construct the maybe monad
.lift('print', PRINT)
monad = maybe 'hi!'
monad.print()
monad = maybe null
monad.print() # doesn't complain!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment