Last active
June 1, 2017 14:14
-
-
Save AyaMorisawa/357266229b4730279a1a to your computer and use it in GitHub Desktop.
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
interface Functor<A> { | |
map<B>(f: (a: A) => B): Functor<B>; | |
} | |
interface Monad<A> extends Functor<A> { | |
map<B>(f: (a: A) => B): Monad<B>; | |
bind<B>(f: (a: A) => Monad<B>): Monad<B>; | |
} | |
interface Eq<A> { | |
equals(a: A): boolean; | |
} | |
interface Maybe<A> extends Monad<A>, Eq<Maybe<A>> { | |
map<B>(f: (a: A) => B): Maybe<B>; | |
bind<B>(f: (a: A) => Maybe<B>): Maybe<B>; | |
equals(a: Maybe<A>): boolean; | |
} | |
class Just<A> implements Maybe<A> { | |
constructor(public value: A) { | |
} | |
map<B>(f: (a: A) => B): Just<B> { | |
return new Just<B>(f(this.value)); | |
} | |
bind<B>(f: (a: A) => Maybe<B>): Maybe<B> { | |
return f(this.value); | |
} | |
equals(a: Maybe<A>): boolean { | |
return (a instanceof Just) && (this.value === a.value); | |
} | |
} | |
class Nothing<A> implements Maybe<A> { | |
constructor() { | |
} | |
map<B>(f: (a: A) => B): Nothing<B> { | |
return new Nothing<B>(); | |
} | |
bind<B>(f: (a: A) => Maybe<B>): Maybe<B> { | |
return new Nothing<B>(); | |
} | |
equals(a: Maybe<A>): boolean { | |
return a instanceof Nothing; | |
} | |
} | |
const a = (<Maybe<number>>new Just(20)) | |
.map(x => x * 2) | |
.map(x => x + 10); | |
if (a instanceof Just) { | |
document.write(a.value); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment