-
-
Save andyhd/1618403 to your computer and use it in GitHub Desktop.
function maybe(value) { | |
var obj = null; | |
function isEmpty() { return value === undefined || value === null } | |
function nonEmpty() { return !isEmpty() } | |
obj = { | |
map: function (f) { return isEmpty() ? obj : maybe(f(value)) }, | |
getOrElse: function (n) { return isEmpty() ? n : value }, | |
isEmpty: isEmpty, | |
nonEmpty: nonEmpty | |
} | |
return obj; | |
} |
Hi all, thanks for share.
But In my opinion this is not a Monad, instead, it is only a Functor.
A monad should has a function called bind
, or, >>=
, which call do with a function having type A->M[A]
For Maybe monad, you will like -
bind: function (f) { return isEmpty() ? obj : f(value) }
Actually, a Monad requires at least two methods: bind and return.
class Monad m where
(>>=) :: m a -> (a -> m b) -> m b -- aka bind
return :: a -> m a
Inspired by this, here's an example using es6 and generators https://gist.github.com/torgeir/7618372
No Martini, no party. No bind, no monad. You may call it flatMap, but fixItOrElse("wrong, wrong, wrong")
@ptnplanet in this case return is maybe(value) itself
I think this is just a functor no?
@andyhd just created something similar to this for node called Giftbox here. Would love to hear your thoughts/feedback! Also motivated by Scala :)
@Muzietto, lol ! how true :)
Check Douglas Crockford's talk in which he explains monads using JavaScript: http://www.youtube.com/watch?v=b0EF0VTs9Dc The Maybe monad is also presented there.