Created
May 11, 2018 11:35
-
-
Save venil7/a37f04f7bc613323fb73c77a0865b992 to your computer and use it in GitHub Desktop.
Maybe monad in TypeScript
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
class Maybe<T> { | |
constructor(private val: T) { } | |
with<Z>(f: (z: T) => Z): Maybe<Z> { | |
return new Maybe(this.return(f)); | |
} | |
return<Z>(f: (z: T) => Z): Z { | |
try { | |
return (f(this.val)); | |
} catch (err) { | |
return undefined; | |
} | |
} | |
} | |
const obj = { a: { b: { c: 123 } } }; | |
const v = new Maybe(obj) | |
.with(x => x.a.z) | |
.with(x => x.b.h) | |
.return(x => x.c.g); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment