Created
April 27, 2011 19:08
-
-
Save jneen/944950 to your computer and use it in GitHub Desktop.
the Maybe monad
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
Maybe = require './Maybe' | |
Maybe(1) # => Maybe(1) | |
Maybe({a: 1})('a') # => Maybe(1) | |
Maybe({a: 1})('a').value # => 1 | |
Maybe({a: 1})('b') # => Nothing | |
Maybe({a: 1})('b')('c')('d')('e') # => Nothing | |
obj = {a: 1, setA: (val) -> @a = val; this} | |
Maybe(obj)('setA', 2)('a') # => Maybe(2) | |
Maybe(obj)('setA') # => Maybe(obj.setA) | |
Maybe(obj)('setA')._(3) # => Maybe(obj) | |
obj.a # => 3 |
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
maybeToString = () -> | |
if @value? | |
"Maybe(#{@value.toString()})" | |
else | |
'Nothing' | |
maybeSend = (args...) -> | |
value = @value | |
if typeof value is 'function' | |
Maybe value(args...) | |
else | |
Nothing | |
Maybe = (value) -> | |
console.log "Maybe(#{value})" | |
maybe = (slot, args...) -> | |
console.log "(#{value}):maybe(#{slot})" | |
unless value? | |
return Nothing | |
newValue = value[slot] | |
if typeof newValue is 'function' | |
console.log "bind:(#{newValue}):(#{value})" | |
newValue = newValue.bind(value) | |
maybeNewValue = Maybe newValue | |
if args.length | |
maybeNewValue = maybeNewValue.send(args...) | |
return maybeNewValue | |
maybe.value = value | |
maybe.toString = maybeToString | |
maybe._ = maybe.send = maybeSend | |
maybe | |
exports.Maybe = Maybe | |
Nothing = exports.Nothing = Maybe.Nothing = Maybe() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment