-
Notifications
You must be signed in to change notification settings - Fork 437
/
Either.kt
327 lines (287 loc) · 9.47 KB
/
Either.kt
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
package arrow.core
import arrow.Kind
import arrow.core.Either.Left
import arrow.core.Either.Right
import arrow.higherkind
/**
* Port of https://github.com/scala/scala/blob/v2.12.1/src/library/scala/util/Either.scala
*
* Represents a value of one of two possible types (a disjoint union.)
* An instance of Either is either an instance of [Left] or [Right].
*/
@higherkind
sealed class Either<out A, out B> : EitherOf<A, B> {
/**
* Returns `true` if this is a [Right], `false` otherwise.
* Used only for performance instead of fold.
*/
internal abstract val isRight: Boolean
/**
* Returns `true` if this is a [Left], `false` otherwise.
* Used only for performance instead of fold.
*/
internal abstract val isLeft: Boolean
fun isLeft(): Boolean = isLeft
fun isRight(): Boolean = isRight
/**
* Applies `ifLeft` if this is a [Left] or `ifRight` if this is a [Right].
*
* Example:
* ```
* val result: Either<Exception, Value> = possiblyFailingOperation()
* result.fold(
* { log("operation failed with $it") },
* { log("operation succeeded with $it") }
* )
* ```
*
* @param ifLeft the function to apply if this is a [Left]
* @param ifRight the function to apply if this is a [Right]
* @return the results of applying the function
*/
inline fun <C> fold(ifLeft: (A) -> C, ifRight: (B) -> C): C = when (this) {
is Right -> ifRight(b)
is Left -> ifLeft(a)
}
@Deprecated(DeprecatedUnsafeAccess, ReplaceWith("getOrElse { ifLeft }"))
fun get(): B = when (this) {
is Right -> b
is Left -> throw NoSuchElementException("Disjunction.Left")
}
fun <C> foldLeft(initial: C, rightOperation: (C, B) -> C): C =
fix().let { either ->
when (either) {
is Right -> rightOperation(initial, either.b)
is Left -> initial
}
}
fun <C> foldRight(initial: Eval<C>, rightOperation: (B, Eval<C>) -> Eval<C>): Eval<C> =
fix().let { either ->
when (either) {
is Right -> rightOperation(either.b, initial)
is Left -> initial
}
}
/**
* If this is a `Left`, then return the left value in `Right` or vice versa.
*
* Example:
* ```
* Left("left").swap() // Result: Right("left")
* Right("right").swap() // Result: Left("right")
* ```
*/
fun swap(): Either<B, A> = fold({ Right(it) }, { Left(it) })
/**
* The given function is applied if this is a `Right`.
*
* Example:
* ```
* Right(12).map { "flower" } // Result: Right("flower")
* Left(12).map { "flower" } // Result: Left(12)
* ```
*/
@Suppress("UNCHECKED_CAST")
inline fun <C> map(f: (B) -> C): Either<A, C> =
flatMap { Right(f(it)) }
/**
* The given function is applied if this is a `Left`.
*
* Example:
* ```
* Right(12).mapLeft { "flower" } // Result: Right(12)
* Left(12).mapLeft { "flower" } // Result: Left("flower)
* ```
*/
inline fun <C> mapLeft(f: (A) -> C): Either<C, B> =
fold({ Left(f(it)) }, { Right(it) })
/**
* Map over Left and Right of this Either
*/
inline fun <C, D> bimap(leftOperation: (A) -> C, rightOperation: (B) -> D): Either<C, D> =
fold({ Left(leftOperation(it)) }, { Right(rightOperation(it)) })
/**
* Returns `false` if [Left] or returns the result of the application of
* the given predicate to the [Right] value.
*
* Example:
* ```
* Right(12).exists { it > 10 } // Result: true
* Right(7).exists { it > 10 } // Result: false
*
* val left: Either<Int, Int> = Left(12)
* left.exists { it > 10 } // Result: false
* ```
*/
fun exists(predicate: (B) -> Boolean): Boolean =
fold({ false }, { predicate(it) })
/**
* Returns a [Some] containing the [Right] value
* if it exists or a [None] if this is a [Left].
*
* Example:
* ```
* Right(12).toOption() // Result: Some(12)
* Left(12).toOption() // Result: None
* ```
*/
fun toOption(): Option<B> =
fold({ None }, { Some(it) })
/**
* The left side of the disjoint union, as opposed to the [Right] side.
*/
@Suppress("DataClassPrivateConstructor")
data class Left<out A> @PublishedApi internal constructor(val a: A) : Either<A, Nothing>() {
override val isLeft
get() = true
override val isRight
get() = false
companion object {
inline operator fun <A> invoke(a: A): Either<A, Nothing> = Left(a)
}
}
/**
* The right side of the disjoint union, as opposed to the [Left] side.
*/
@Suppress("DataClassPrivateConstructor")
data class Right<out B> @PublishedApi internal constructor(val b: B) : Either<Nothing, B>() {
override val isLeft
get() = false
override val isRight
get() = true
companion object {
inline operator fun <B> invoke(b: B): Either<Nothing, B> = Right(b)
}
}
companion object {
fun <L> left(left: L): Either<L, Nothing> = Left(left)
fun <R> right(right: R): Either<Nothing, R> = Right(right)
tailrec fun <L, A, B> tailRecM(a: A, f: (A) -> Kind<EitherPartialOf<L>, Either<A, B>>): Either<L, B> {
val ev: Either<L, Either<A, B>> = f(a).fix()
return when (ev) {
is Left -> Left(ev.a)
is Right -> {
val b: Either<A, B> = ev.b
when (b) {
is Left -> tailRecM(b.a, f)
is Right -> Right(b.b)
}
}
}
}
fun <L, R> cond(test: Boolean, ifTrue: () -> R, ifFalse: () -> L): Either<L, R> = if (test) right(ifTrue()) else left(ifFalse())
}
}
fun <L> Left(left: L): Either<L, Nothing> = Either.left(left)
fun <R> Right(right: R): Either<Nothing, R> = Either.right(right)
/**
* Binds the given function across [Either.Right].
*
* @param f The function to bind across [Either.Right].
*/
inline fun <A, B, C> EitherOf<A, B>.flatMap(f: (B) -> Either<A, C>): Either<A, C> =
fix().let {
when (it) {
is Right -> f(it.b)
is Left -> it
}
}
/**
* Returns the value from this [Either.Right] or the given argument if this is a [Either.Left].
*
* Example:
* ```
* Right(12).getOrElse(17) // Result: 12
* Left(12).getOrElse(17) // Result: 17
* ```
*/
inline fun <B> EitherOf<*, B>.getOrElse(default: () -> B): B =
fix().fold({ default() }, ::identity)
/**
* Returns the value from this [Either.Right] or null if this is a [Either.Left].
*
* Example:
* ```
* Right(12).orNull() // Result: 12
* Left(12).orNull() // Result: null
* ```
*/
inline fun <B> EitherOf<*, B>.orNull(): B? =
getOrElse { null }
/**
* Returns the value from this [Either.Right] or allows clients to transform [Either.Left] to [Either.Right] while providing access to
* the value of [Either.Left].
*
* Example:
* ```
* Right(12).getOrHandle { 17 } // Result: 12
* Left(12).getOrHandle { it + 5 } // Result: 17
* ```
*/
inline fun <A, B> EitherOf<A, B>.getOrHandle(default: (A) -> B): B =
fix().fold({ default(it) }, ::identity)
/**
* * Returns [Either.Right] with the existing value of [Either.Right] if this is a [Either.Right] and the given predicate
* holds for the right value.
* * Returns `Left(default)` if this is a [Either.Right] and the given predicate does not
* hold for the right value.
* * Returns [Either.Left] with the existing value of [Either.Left] if this is a [Either.Left].
*
* Example:
* ```
* Right(12).filterOrElse({ it > 10 }, { -1 }) // Result: Right(12)
* Right(7).filterOrElse({ it > 10 }, { -1 }) // Result: Left(-1)
*
* val left: Either<Int, Int> = Left(12)
* left.filterOrElse({ it > 10 }, { -1 }) // Result: Left(12)
* ```
*/
inline fun <A, B> EitherOf<A, B>.filterOrElse(predicate: (B) -> Boolean, default: () -> A): Either<A, B> =
flatMap { if (predicate(it)) Right(it) else Left(default()) }
/**
* * Returns [Either.Right] with the existing value of [Either.Right] if this is an [Either.Right] with a non-null value.
* The returned Either.Right type is not nullable.
* * Returns `Left(default())` if this is an [Either.Right] and the existing value is null
* * Returns [Either.Left] with the existing value of [Either.Left] if this is an [Either.Left].
*
* Example:
* ```
* Right(12).leftIfNull({ -1 }) // Result: Right(12)
* Right(null).leftIfNull({ -1 }) // Result: Left(-1)
*
* Left(12).leftIfNull({ -1 }) // Result: Left(12)
* ```
*/
inline fun <A, B> EitherOf<A, B?>.leftIfNull(crossinline default: () -> A): Either<A, B> =
fix().flatMap { if (it == null) Left(default()) else Right(it) }
/**
* Returns `true` if this is a [Either.Right] and its value is equal to `elem` (as determined by `==`),
* returns `false` otherwise.
*
* Example:
* ```
* Right("something").contains { "something" } // Result: true
* Right("something").contains { "anything" } // Result: false
* Left("something").contains { "something" } // Result: false
* ```
*
* @param elem the element to test.
* @return `true` if the option has an element that is equal (as determined by `==`) to `elem`, `false` otherwise.
*/
fun <A, B> EitherOf<A, B>.contains(elem: B): Boolean =
fix().fold({ false }, { it == elem })
fun <A, B, C> EitherOf<A, B>.ap(ff: EitherOf<A, (B) -> C>): Either<A, C> =
ff.fix().flatMap { f -> fix().map(f) }.fix()
fun <A, B> EitherOf<A, B>.combineK(y: EitherOf<A, B>): Either<A, B> =
when (this) {
is Either.Left -> y.fix()
else -> fix()
}
@Deprecated(DeprecatedAmbiguity, ReplaceWith("Try { body }.toEither()"))
inline fun <T> eitherTry(body: () -> T): Either<Throwable, T> = try {
Right(body())
} catch (t: Throwable) {
Left(t)
}
fun <A> A.left(): Either<A, Nothing> = Either.Left(this)
fun <A> A.right(): Either<Nothing, A> = Either.Right(this)