Skip to content

Instantly share code, notes, and snippets.

@jdan
Last active November 11, 2020 18:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jdan/58a9d8ee2e1cbb004e4bbb89dff3c9c8 to your computer and use it in GitHub Desktop.
Save jdan/58a9d8ee2e1cbb004e4bbb89dff3c9c8 to your computer and use it in GitHub Desktop.
maybe as valueOf
let oracle = [];
class Maybe {
constructor(isNothing, value) {
this.isNothing = isNothing;
this.value = value;
}
valueOf() {
oracle.push(this);
}
}
let Nothing = () => new Maybe(true);
let Just = (v) => new Maybe(false, v);
let stringOfMaybe = (m) => (m.isNothing ? "Nothing" : `Just ${m.value}`);
class BindFunction {
constructor(f) {
this.f = f;
}
valueOf() {
let m = oracle.pop();
oracle.push(m.isNothing ? Nothing() : this.f(m.value));
}
}
let double = new BindFunction((a) => Just(a * 2));
let m = Just(5);
let n = Nothing();
console.log("m:", stringOfMaybe(m));
m >>= double;
console.log("m >>= double:", stringOfMaybe(oracle.pop()));
console.log("n:", stringOfMaybe(n));
n >>= double;
console.log("n >>= double:", stringOfMaybe(oracle.pop()));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment