Created
January 24, 2017 10:11
-
-
Save alendit/0db15eea6d3239def61ee833fbb7a443 to your computer and use it in GitHub Desktop.
HKT in typescript don't work. But why?
This file contains 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<F, A> { | |
map: <B>(this: Functor<F, A>, f: (a: A) => B) => Functor<F, B> | |
} | |
class Maybe<A> implements Functor<Maybe<A>, A> { | |
private constructor(public value: A) { } | |
static Nothing<A>() { return new Maybe<A>(undefined); } | |
static Just<A>(value: A) { return new Maybe<A>(value); } | |
map<B>(this: Maybe<A>, f: ((a: A) => B)): Maybe<B> { | |
if (this.value === undefined) return Maybe.Nothing<B>(); | |
return Maybe.Just(f(this.value)); | |
} | |
// // Strangely enough, this typechecks, too | |
// map<B>(this: Maybe<A>, f: ((a: A) => B)): List<B> { | |
// if (this.value === undefined) return new List<B>([]); | |
// return new List([f(this.value)]); | |
// } | |
toString() { | |
if (this.value === undefined) return 'undefined'; | |
return this.value.toString(); | |
} | |
} | |
class List<A> implements Functor<List<A>, A> { | |
array: A[]; | |
constructor(as: A[]) { | |
this.array = as; | |
} | |
map <B>(this: List<A>, f: ((a: A) => B)): List<B> { | |
return new List<B>(this.array.map(f)); | |
} | |
toString() { | |
return this.array.toString(); | |
} | |
} | |
const l1 = new List(['aaa', 'aa', 'a']); | |
const j1 = Maybe.Just(20); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment