Last active
December 28, 2020 08:42
-
-
Save exbotanical/14d31098dd2a3b04d9e59815d66b1b44 to your computer and use it in GitHub Desktop.
A simple implementation of a Maybe Monad
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
| const identity = x => x; | |
| function Just (v) { | |
| return { map, chain, ap }; | |
| function map (fn) { | |
| return Just(fn(v)) | |
| } | |
| function chain (fn) { | |
| return fn(v); | |
| } | |
| // not really mathematically sound, but not imperative to the endeavor at hand either | |
| function ap (another) { | |
| return another.map(v); | |
| } | |
| } | |
| function Nothing () { | |
| return { map: Nothing, chain: Nothing, ap: Nothing }; | |
| } | |
| const Maybe = { Just, Nothing, of: Just } | |
| function fromNullable (val) { | |
| if (val == null) return Maybe.Nothing(); | |
| return Maybe.of(val); | |
| } | |
| function prop (prop) { | |
| return function (obj) { | |
| return fromNullable(obj[prop]); | |
| } | |
| } | |
| const obj = { | |
| a: { | |
| a: { | |
| a: 1 | |
| } | |
| }, | |
| b: 2, | |
| c: 3 | |
| }; | |
| Maybe.of(obj) | |
| .chain(prop('a')) | |
| .chain(prop('a')) | |
| .chain(prop('a')) | |
| .chain(identity); |
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
| const Sum = x => ({ | |
| x, | |
| concat: other => | |
| Sum(x + other.x) | |
| }); | |
| Sum.empty = () => Sum(0); | |
| const Product = x => ({ | |
| x, | |
| concat: other => | |
| Product(x * other.x) | |
| }); | |
| Product.empty = () => Product(1); | |
| const Any = x => ({ | |
| x, | |
| concat: other => | |
| Any(x || other.x) | |
| }); | |
| Any.empty = () => Any(false); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment