Skip to content

Instantly share code, notes, and snippets.

@michaelficarra
Last active August 29, 2015 14:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save michaelficarra/ecdee4b556bcb5c6969a to your computer and use it in GitHub Desktop.
Save michaelficarra/ecdee4b556bcb5c6969a to your computer and use it in GitHub Desktop.
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