Last active
November 11, 2020 18:58
-
-
Save jdan/58a9d8ee2e1cbb004e4bbb89dff3c9c8 to your computer and use it in GitHub Desktop.
maybe as valueOf
This file contains hidden or 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
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