Skip to content

Instantly share code, notes, and snippets.

@Twisol
Created December 24, 2013 06:57
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 Twisol/8109708 to your computer and use it in GitHub Desktop.
Save Twisol/8109708 to your computer and use it in GitHub Desktop.
Maybe monad via ES6 generators (via Traceur)
var Nothing = function Nothing() {};
var Just = function Just(x) { this.value = x; };
function runMaybe(f) {
var result = f.next();
while (!result.done) {
var value = result.value;
switch (value.constructor) {
case Nothing:
return result.value;
case Just:
result = f.next(value.value);
break;
default: // fmap fallback behavior
result = f.next(value);
break;
}
}
return result.value;
}
function tryDouble(x) {
return new Just(2*x);
}
function lookup(obj, key) {
if (key in obj) {
return new Just(obj[key]);
} else {
return new Nothing();
}
}
function* test(obj) {
var x = yield lookup(obj, "stuff");
var y = yield tryDouble(x);
return new Just(x + y);
}
// runMaybe(test({stuff: 42}))
//=> Just {value: 126}
//
// runMaybe(test({notstuff: 42}))
//=> Nothing {}
@Twisol
Copy link
Author

Twisol commented Dec 24, 2013

Just having some fun with generators. I don't think you can do a List monad like in Haskell, since you'd need to be able to run everything after the yield multiple times, so generators can't help with monads that need to do that kind of thing...

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