/
Maybe.ts
129 lines (109 loc) · 2.62 KB
/
Maybe.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
/**
* @tsplus type Nothing
*/
export interface Nothing {
readonly _tag: "Nothing"
}
export interface Just<A> {
readonly _tag: "Just"
readonly value: A
}
/**
* @tsplus type Maybe
*/
export type Maybe<A> = Nothing | Just<A>
/**
* @tsplus type MaybeOps
*/
export interface MaybeOps { }
export const Maybe: MaybeOps = {}
/**
* @tsplus unify Maybe
*/
export function unifyMaybe<X extends Maybe<any>>(self: X): Maybe<
[X] extends [Maybe<infer A>] ? A : never
> {
return self
}
/**
* @tsplus static MaybeOps nothing
*/
export const nothing = (): Maybe<never> => {
return { _tag: "Nothing" }
}
/**
* @tsplus static MaybeOps just
*/
export const just = <A>(value: A): Maybe<A> => {
return { _tag: "Just", value }
}
/**
* @tsplus fluent Maybe match
*/
export const match_ = <A, B, C>(self: Maybe<A>, onNothing: () => B, onJust: (a: A) => C): B | C => {
return self._tag === "Nothing" ? onNothing() : onJust(self.value);
}
/**
* @tsplus operator Maybe +
* @tsplus fluent Maybe zip
*/
export function zip_<A, B>(self: Maybe<A>, that: Maybe<B>): Maybe<readonly [A, B]> {
throw new Error("unimplemented")
}
/**
* @tsplus fluent Maybe isJust
*/
export function isJust<A>(self: Maybe<A>): self is Just<A> {
return self._tag === "Just";
}
/**
* @tsplus fluent Maybe isNothing
*/
export function isNothing<A>(self: Maybe<A>): self is Nothing {
return self._tag === "Nothing";
}
/**
* @tsplus fluent Maybe assertJust
*/
export function assertJust<A>(self: Maybe<A>): asserts self is Just<A> {
if(self._tag !== "Just") {
throw new Error("Not Just");
}
}
/**
* @tsplus getter Maybe value
*/
export function value<A>(self: Maybe<A>) {
return self._tag === "Just" ? self.value : void 0
}
/**
* @tsplus fluent Nothing assertJust
*/
export function assertJustNothing(self: Nothing): never {
throw new Error("Not Just");
}
// /**
// * @tsplus getter Maybe value
// */
// export function get<A>(self: Maybe<A>): A | undefined {
// return self._tag === "Just" ? self.value : undefined
// }
export const result = Maybe.just(0).match(() => 0, () => 1)
export const op = Maybe.just(0) + Maybe.just(1)
/**
* @tsplus pipeable Maybe map
*/
export function map<A, B>(f: (a: A) => B) {
return (self: Maybe<A>): Maybe<B> => self.isJust() ? Maybe.just(f(self.value)) : Maybe.nothing()
}
/**
* @tsplus pipeable Maybe flatMap
*/
export function flatMap<A, B>(f: (a: A) => Maybe<B>) {
return (self: Maybe<A>): Maybe<B> => self.isJust() ? f(self.value) : Maybe.nothing()
}
export const useDo = Do(($) => {
const x = $(Maybe.just(0))
const y = $(Maybe.just(1))
return x + y
})