Created
September 11, 2019 13:00
-
-
Save krstffr/17e9e040015142447c15eb1fb8eb6b96 to your computer and use it in GitHub Desktop.
typescript mabye monad, playing around
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
type Maybe<A> = { | |
type: string; | |
map: <B>(f: (x: A) => B) => Maybe<B | A>; | |
flatMap: <B>(f: (x: A) => Maybe<B>) => Maybe<B | A>; | |
valueOrDefault: <C>(x: C) => A | C; | |
}; | |
function none<A>(x: A): Maybe<A> { | |
return { | |
type: "none", | |
map: () => none(x), | |
flatMap: () => none(x), | |
valueOrDefault: y => y | |
}; | |
} | |
function some<A>(x: A): Maybe<A> { | |
return { | |
type: "some", | |
map: f => { | |
const res = f(x); | |
return res ? some(res) : none(res); | |
}, | |
flatMap: f => { | |
return f(x); | |
}, | |
valueOrDefault: () => x | |
}; | |
} | |
const getSome = (n: number) => (n === 0 ? none(0) : some(n + 4)); | |
const add1 = (x: number): number => { | |
console.log("adding!!"); | |
return x + 1; | |
}; | |
const test = some(1) | |
.map(add1) | |
.map(add1) | |
.map(add1) | |
.flatMap(getSome) | |
.map(add1); | |
const test2 = getSome(0) | |
.map(x => x - 12) | |
.flatMap(getSome) | |
.map(add1) | |
.map(add1); | |
console.log(test, test2); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment