Skip to content

Instantly share code, notes, and snippets.

@krstffr
Created September 11, 2019 13:00
Show Gist options
  • Save krstffr/17e9e040015142447c15eb1fb8eb6b96 to your computer and use it in GitHub Desktop.
Save krstffr/17e9e040015142447c15eb1fb8eb6b96 to your computer and use it in GitHub Desktop.
typescript mabye monad, playing around
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