-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmonad.ts
52 lines (40 loc) · 1.09 KB
/
monad.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
export interface Functor<A> {
map<B>( transform: (value: A) => B ): Functor<B>;
}
export interface Monad<A> {
bind<B>( transform: (value: A) => Monad<B> ): Monad<B>;
}
export interface Maybe<T> {
map<U>(fn: (value: T) => U): Maybe<U>;
bind<U>(fn: (value: T) => Maybe<U>): Maybe<U>;
orElse(value: T): T;
}
export class Just<T> implements Maybe<T> {
constructor(private readonly value: T) { }
map<U>(fn: (value: T) => U): Maybe<U> {
return new Just(fn(this.value));
}
bind<U>(fn: (value: T) => Maybe<U>): Maybe<U> {
return fn(this.value);
}
orElse(value: T): T {
return this.value;
}
}
export class Nothing<T> implements Maybe<T> {
map<U>(fn: (value: T) => U): Maybe<U> {
return new Nothing();
}
bind<U>(fn: (value: T) => Maybe<U>): Maybe<U> {
return new Nothing();
}
orElse(value: T): T {
return value;
}
}
export class Either<E, A> {
private constructor(private readonly value: E | A) {}
static left<E, A>(value: E): Either<E, A> {
return new Either<E, A>(value);
}
}