Skip to content

Instantly share code, notes, and snippets.

@igstan
Last active December 18, 2015 05:49
Show Gist options
  • Save igstan/5735974 to your computer and use it in GitHub Desktop.
Save igstan/5735974 to your computer and use it in GitHub Desktop.
// `unit` is `return` from Haskell
// `bind` is `>>=` from Haskell, or `flatMap` from Scala
var None = {
bind: function (fn) { return this; },
unit: function (v) { return Option(v); },
getOrElse: function (elseValue) { return elseValue; }
};
var Some = function (value) {
return {
bind: function (fn) { return fn.call(this, value); },
unit: function (v) { return Option(v); },
getOrElse: function (_) { return value; }
}
};
var Option = function (value) {
return (value === null || value === undefined) ? None : Some(value);
};
var n = Option(5).bind(function (n) { return this.unit(n + 1); })
.bind(function (n) { return this.unit(n + 2); })
// .bind(function (n) { return this.unit(null); })
.bind(function (n) { return this.unit(n + 3); })
.getOrElse("something returned None along the way");
console.log(n === 11);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment