Created
December 24, 2013 06:57
-
-
Save Twisol/8109708 to your computer and use it in GitHub Desktop.
Maybe monad via ES6 generators (via Traceur)
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
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; | |
} |
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
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 {} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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...