Skip to content

Instantly share code, notes, and snippets.

@andyhd
Created January 16, 2012 01:02
Show Gist options
  • Save andyhd/1618403 to your computer and use it in GitHub Desktop.
Save andyhd/1618403 to your computer and use it in GitHub Desktop.
Maybe monad in Javascript
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;
}
@andyhd
Copy link
Author

andyhd commented Jan 16, 2012

No, I've seen it and it looks a lot more LISPy than Scala, but I haven't tried it yet.

@0atman
Copy link

0atman commented Jan 16, 2012

Yeah, it's a minimal dialect. Have you read this? http://www.defmacro.org/ramblings/lisp.html
I didn't "get" LISP till I read it.

@andyhd
Copy link
Author

andyhd commented Jan 16, 2012

Cheers, that's a nice article. I think I already get LISP, but it never hurts to double check. I'm still not 100% on monads.

@0atman
Copy link

0atman commented Jan 16, 2012

The revelation for me was the similarities to XML!

@josesaldana
Copy link

Hi Andy,

Thank you very much for sharing this with us. I just wanted to ask you if it would be ok for you if I use this code in a commercial web app.

Thanks again,
Jose

@mloskot
Copy link

mloskot commented Jan 22, 2013

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.

@nielinjie
Copy link

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) }

@ptnplanet
Copy link

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

@torgeir
Copy link

torgeir commented Nov 23, 2013

Inspired by this, here's an example using es6 and generators https://gist.github.com/torgeir/7618372

@Muzietto
Copy link

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

@dan-weaver
Copy link

I think this is just a functor no?

@nitindhar7
Copy link

@andyhd just created something similar to this for node called Giftbox here. Would love to hear your thoughts/feedback! Also motivated by Scala :)

@jhegedus42
Copy link

@Muzietto, lol ! how true :)

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