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 Nothing() {} | |
function Just(x) { | |
this.valueOf = function(){ return x; }; | |
} | |
Nothing.prototype.map = function(f) { | |
return this; | |
}; | |
Just.prototype.map = function(f) { | |
return new Just(f(this.valueOf())); | |
}; | |
Nothing.prototype.bind = function(f) { | |
return this; | |
}; | |
Just.prototype.bind = function(f) { | |
return f(this.valueOf()); | |
}; | |
var Maybe = { | |
fromPossiblyNullValue: function(x) { | |
return x == null ? new Nothing() : new Just(x); | |
} | |
}; | |
// double only numbers with odd parity | |
function doubleOddNumbers(x) { | |
// safe version of `return x&1 ? x * 2 : null;` | |
return x&1 ? new Just(x * 2) : new Nothing; | |
} | |
var a, safeA; | |
a = null; | |
safeA = Maybe.fromPossiblyNullValue(a); | |
safeA.bind(doubleOddNumbers); // Nothing | |
safeA.bind(doubleOddNumbers).bind(doubleOddNumbers); // Nothing | |
a = 2; | |
safeA = Maybe.fromPossiblyNullValue(a); | |
safeA.bind(doubleOddNumbers); // Nothing | |
safeA.bind(doubleOddNumbers).bind(doubleOddNumbers); // Nothing | |
a = 3; | |
safeA = Maybe.fromPossiblyNullValue(a); | |
safeA.bind(doubleOddNumbers); // Just(6) | |
safeA.bind(doubleOddNumbers).bind(doubleOddNumbers); // Nothing |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment