Last active
August 29, 2015 14:19
-
-
Save vsavkin/976edbaabe18322c41ab to your computer and use it in GitHub Desktop.
Poor Man's Do Notation Using Generators
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
// First, let's define the two constructors of the Maybe monad | |
function Just(value) { | |
this.just = value; | |
} | |
function Nothing() { | |
} | |
function just(value) { | |
return new Just(value); | |
} | |
var nothing = new Nothing(); | |
// The maybe wrapper | |
function maybe(genF) { | |
function mreturn(value) { | |
return (value instanceof Just || value instanceof Nothing) ? value : just(value); | |
} | |
var gen = genF(); | |
var curr = gen.next(undefined); | |
while(! curr.done) { | |
var v = mreturn(curr.value); | |
if (v instanceof Just) { | |
curr = gen.next(v.just); | |
} else { | |
return v; | |
} | |
} | |
return mreturn(curr.value); | |
} | |
//Example o using `maybe` | |
// () -> Maybe Number | |
function getMaybeA() { | |
return just(3); | |
} | |
// Number -> Maybe Number | |
function getMaybeB(value) { | |
return just(value + 7); | |
} | |
// () -> Maybe Number | |
function getMaybeAB() { | |
// looks almost like do notation in Haskell :) | |
return maybe(function*() { | |
var a = yield getMaybeA(); | |
var b = yield getMaybeB(a); | |
return a + b; | |
}); | |
} | |
console.log(getMaybeAB()); //prints Just 13 | |
// If https://github.com/jhusain/compositional-functions gets approved, | |
// the example will look as follows: | |
maybe function getMaybeAB() { | |
var a = await getMaybeA(); | |
var b = await getMaybeB(a); | |
return a + b; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment