Created
May 24, 2013 20:17
-
-
Save joyrexus/5646225 to your computer and use it in GitHub Desktop.
Maybe 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
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