-
Notifications
You must be signed in to change notification settings - Fork 448
/
Either.kt
1482 lines (1411 loc) · 47.5 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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
@file:JvmMultifileClass
@file:JvmName("EitherKt")
@file:OptIn(ExperimentalContracts::class)
package arrow.core
import arrow.core.Either.Left
import arrow.core.Either.Right
import arrow.core.Either.Right.Companion.unit
import arrow.core.raise.Raise
import arrow.core.raise.either
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract
import kotlin.experimental.ExperimentalTypeInference
import kotlin.jvm.JvmMultifileClass
import kotlin.jvm.JvmName
import kotlin.jvm.JvmStatic
public typealias EitherNel<E, A> = Either<NonEmptyList<E>, A>
/**
* <!--- TEST_NAME EitherKnitTest -->
*
* In day-to-day programming, it is fairly common to find ourselves writing functions that can fail.
* For instance, querying a service may result in a connection issue, or some unexpected JSON response.
*
* To communicate these errors, it has become common practice to throw exceptions; however,
* exceptions are not tracked in any way, shape, or form by the compiler. To see what
* kind of exceptions (if any) a function may throw, we have to dig through the source code.
* Then, to handle these exceptions, we have to make sure we catch them at the call site. This
* all becomes even more unwieldy when we try to compose exception-throwing procedures.
*
* ```kotlin
* import arrow.core.andThen
*
* //sampleStart
* val throwsSomeStuff: (Int) -> Double = {x -> x.toDouble()}
* val throwsOtherThings: (Double) -> String = {x -> x.toString()}
* val moreThrowing: (String) -> List<String> = {x -> listOf(x)}
* val magic = throwsSomeStuff.andThen(throwsOtherThings).andThen(moreThrowing)
* //sampleEnd
* fun main() {
* println ("magic = $magic")
* }
* ```
* <!--- KNIT example-either-01.kt -->
*
* Assume we happily throw exceptions in our code. Looking at the types of the functions above, any could throw a number of exceptions -- we do not know. When we compose, exceptions from any of the constituent
* functions can be thrown. Moreover, they may throw the same kind of exception
* (e.g., `IllegalArgumentException`) and, thus, it gets tricky tracking exactly where an exception came from.
*
* How then do we communicate an error? By making it explicit in the data type we return.
*
*
* ```kotlin
* import arrow.core.Either
*
* val left: Either<String, Int> =
* //sampleStart
* Either.Left("Something went wrong")
* //sampleEnd
* fun main() {
* println(left)
* }
* ```
* <!--- KNIT example-either-02.kt -->
*
* Because `Either` is right-biased, it is possible to define a Monad instance for it.
*
* Since we only ever want the computation to continue in the case of [Right] (as captured by the right-bias nature),
* we fix the left type parameter and leave the right one free.
*
* So, the map and flatMap methods are right-biased:
*
* ```kotlin
* import arrow.core.Either
* import arrow.core.flatMap
*
* //sampleStart
* val right: Either<String, Int> = Either.Right(5)
* val value = right.flatMap{ Either.Right(it + 1) }
* //sampleEnd
* fun main() {
* println("value = $value")
* }
* ```
* <!--- KNIT example-either-03.kt -->
*
* ```kotlin
* import arrow.core.Either
* import arrow.core.flatMap
*
* //sampleStart
* val left: Either<String, Int> = Either.Left("Something went wrong")
* val value = left.flatMap{ Either.Right(it + 1) }
* //sampleEnd
* fun main() {
* println("value = $value")
* }
* ```
* <!--- KNIT example-either-04.kt -->
*
* ## Using Either instead of exceptions
*
* As a running example, we will have a series of functions that will:
*
* * Parse a string into an integer
* * Calculate the reciprocal
* * Convert the reciprocal into a string
*
* Using exception-throwing code, we could write something like this:
*
* ```kotlin
* import arrow.core.Either
* import arrow.core.flatMap
*
* //sampleStart
* fun parse(s: String): Int =
* if (s.matches(Regex("-?[0-9]+"))) s.toInt()
* else throw NumberFormatException("$s is not a valid integer.")
*
* fun reciprocal(i: Int): Double =
* if (i == 0) throw IllegalArgumentException("Cannot take reciprocal of 0.")
* else 1.0 / i
*
* fun stringify(d: Double): String = d.toString()
* //sampleEnd
* ```
* <!--- KNIT example-either-05.kt -->
*
* Instead, let's make the fact that some of our functions can fail explicit in the return type.
*
* ```kotlin
* import arrow.core.Either
* import arrow.core.flatMap
* import arrow.core.left
* import arrow.core.right
*
* //sampleStart
* // Either Style
* fun parse(s: String): Either<NumberFormatException, Int> =
* if (s.matches(Regex("-?[0-9]+"))) Either.Right(s.toInt())
* else Either.Left(NumberFormatException("$s is not a valid integer."))
*
* fun reciprocal(i: Int): Either<IllegalArgumentException, Double> =
* if (i == 0) Either.Left(IllegalArgumentException("Cannot take reciprocal of 0."))
* else Either.Right(1.0 / i)
*
* fun stringify(d: Double): String = d.toString()
*
* fun magic(s: String): Either<Exception, String> =
* parse(s).flatMap { reciprocal(it) }.map { stringify(it) }
* //sampleEnd
* ```
* <!--- KNIT example-either-06.kt -->
*
* These calls to `parse` return a [Left] and [Right] value
*
* ```kotlin
* import arrow.core.Either
*
* fun parse(s: String): Either<NumberFormatException, Int> =
* if (s.matches(Regex("-?[0-9]+"))) Either.Right(s.toInt())
* else Either.Left(NumberFormatException("$s is not a valid integer."))
*
* //sampleStart
* val notANumber = parse("Not a number")
* val number2 = parse("2")
* //sampleEnd
* fun main() {
* println("notANumber = $notANumber")
* println("number2 = $number2")
* }
* ```
* <!--- KNIT example-either-07.kt -->
*
* Now, using combinators like `flatMap` and `map`, we can compose our functions together.
*
* ```kotlin
* import arrow.core.Either
* import arrow.core.flatMap
*
* fun parse(s: String): Either<NumberFormatException, Int> =
* if (s.matches(Regex("-?[0-9]+"))) Either.Right(s.toInt())
* else Either.Left(NumberFormatException("$s is not a valid integer."))
*
* fun reciprocal(i: Int): Either<IllegalArgumentException, Double> =
* if (i == 0) Either.Left(IllegalArgumentException("Cannot take reciprocal of 0."))
* else Either.Right(1.0 / i)
*
* fun stringify(d: Double): String = d.toString()
*
* fun magic(s: String): Either<Exception, String> =
* parse(s).flatMap{ reciprocal(it) }.map{ stringify(it) }
*
* //sampleStart
* val magic0 = magic("0")
* val magic1 = magic("1")
* val magicNotANumber = magic("Not a number")
* //sampleEnd
* fun main() {
* println("magic0 = $magic0")
* println("magic1 = $magic1")
* println("magicNotANumber = $magicNotANumber")
* }
* ```
* <!--- KNIT example-either-08.kt -->
*
* In the following exercise, we pattern-match on every case in which the `Either` returned by `magic` can be in.
* Note the `when` clause in the [Left] - the compiler will complain if we leave that out because it knows that,
* given the type `Either[Exception, String]`, there can be inhabitants of [Left] that are not
* `NumberFormatException` or `IllegalArgumentException`. You should also notice that we are using
* [SmartCast](https://kotlinlang.org/docs/reference/typecasts.html#smart-casts) for accessing [Left] and [Right]
* values.
*
* ```kotlin
* import arrow.core.Either
* import arrow.core.flatMap
*
* fun parse(s: String): Either<NumberFormatException, Int> =
* if (s.matches(Regex("-?[0-9]+"))) Either.Right(s.toInt())
* else Either.Left(NumberFormatException("$s is not a valid integer."))
*
* fun reciprocal(i: Int): Either<IllegalArgumentException, Double> =
* if (i == 0) Either.Left(IllegalArgumentException("Cannot take reciprocal of 0."))
* else Either.Right(1.0 / i)
*
* fun stringify(d: Double): String = d.toString()
*
* fun magic(s: String): Either<Exception, String> =
* parse(s).flatMap{ reciprocal(it) }.map{ stringify(it) }
*
* //sampleStart
* val x = magic("2")
* val value = when(x) {
* is Either.Left -> when (x.value) {
* is NumberFormatException -> "Not a number!"
* is IllegalArgumentException -> "Can't take reciprocal of 0!"
* else -> "Unknown error"
* }
* is Either.Right -> "Got reciprocal: ${x.value}"
* }
* //sampleEnd
* fun main() {
* println("value = $value")
* }
* ```
* <!--- KNIT example-either-09.kt -->
*
* Instead of using exceptions as our error value, let's instead enumerate explicitly the things that
* can go wrong in our program.
*
* ```kotlin
* import arrow.core.Either
* import arrow.core.flatMap
* //sampleStart
* // Either with ADT Style
*
* sealed class Error {
* object NotANumber : Error()
* object NoZeroReciprocal : Error()
* }
*
* fun parse(s: String): Either<Error, Int> =
* if (s.matches(Regex("-?[0-9]+"))) Either.Right(s.toInt())
* else Either.Left(Error.NotANumber)
*
* fun reciprocal(i: Int): Either<Error, Double> =
* if (i == 0) Either.Left(Error.NoZeroReciprocal)
* else Either.Right(1.0 / i)
*
* fun stringify(d: Double): String = d.toString()
*
* fun magic(s: String): Either<Error, String> =
* parse(s).flatMap{reciprocal(it)}.map{ stringify(it) }
* //sampleEnd
* ```
* <!--- KNIT example-either-10.kt -->
*
* For our little module, we enumerate any and all errors that can occur. Then, instead of using
* exception classes as error values, we use one of the enumerated cases. Now, when we pattern match,
* we are able to comphrensively handle failure without resulting in an `else` branch; moreover,
* since Error is sealed, no outside code can add additional subtypes that we might fail to handle.
*
* ```kotlin
* import arrow.core.Either
* import arrow.core.flatMap
*
* sealed class Error {
* object NotANumber : Error()
* object NoZeroReciprocal : Error()
* }
*
* fun parse(s: String): Either<Error, Int> =
* if (s.matches(Regex("-?[0-9]+"))) Either.Right(s.toInt())
* else Either.Left(Error.NotANumber)
*
* fun reciprocal(i: Int): Either<Error, Double> =
* if (i == 0) Either.Left(Error.NoZeroReciprocal)
* else Either.Right(1.0 / i)
*
* fun stringify(d: Double): String = d.toString()
*
* fun magic(s: String): Either<Error, String> =
* parse(s).flatMap{ reciprocal(it) }.map{ stringify(it) }
*
* //sampleStart
* val x = magic("2")
* val value = when(x) {
* is Either.Left -> when (x.value) {
* is Error.NotANumber -> "Not a number!"
* is Error.NoZeroReciprocal -> "Can't take reciprocal of 0!"
* }
* is Either.Right -> "Got reciprocal: ${x.value}"
* }
* //sampleEnd
* fun main() {
* println("value = $value")
* }
* ```
* <!--- KNIT example-either-11.kt -->
*
* ## Either.catch exceptions
*
* Sometimes you do need to interact with code that can potentially throw exceptions. In such cases, you should mitigate the possibility that an exception can be thrown. You can do so by using the `catch` function.
*
* Example:
*
* ```kotlin
* import arrow.core.Either
*
* //sampleStart
* fun potentialThrowingCode(): String = throw RuntimeException("Blow up!")
*
* suspend fun makeSureYourLogicDoesNotHaveSideEffects(): Either<Error, String> =
* Either.catch { potentialThrowingCode() }.mapLeft { Error.SpecificError }
* //sampleEnd
* suspend fun main() {
* println("makeSureYourLogicDoesNotHaveSideEffects().isLeft() = ${makeSureYourLogicDoesNotHaveSideEffects().isLeft()}")
* }
*
* sealed class Error {
* object SpecificError : Error()
* }
* ```
* <!--- KNIT example-either-12.kt -->
*
* ## Syntax
*
* Either can also map over the [Left] value with `mapLeft`, which is similar to map, but applies on left instances.
*
* ```kotlin
* import arrow.core.Either
*
* //sampleStart
* val r : Either<Int, Int> = Either.Right(7)
* val rightMapLeft = r.mapLeft {it + 1}
* val l: Either<Int, Int> = Either.Left(7)
* val leftMapLeft = l.mapLeft {it + 1}
* //sampleEnd
* fun main() {
* println("rightMapLeft = $rightMapLeft")
* println("leftMapLeft = $leftMapLeft")
* }
* ```
* <!--- KNIT example-either-13.kt -->
*
* `Either<A, B>` can be transformed to `Either<B,A>` using the `swap()` method.
*
* ```kotlin
* import arrow.core.Either.Left
* import arrow.core.Either
*
* //sampleStart
* val r: Either<String, Int> = Either.Right(7)
* val swapped = r.swap()
* //sampleEnd
* fun main() {
* println("swapped = $swapped")
* }
* ```
* <!--- KNIT example-either-14.kt -->
*
* For using Either's syntax on arbitrary data types.
* This will make possible to use the `left()`, `right()`, `getOrElse()` methods:
*
* ```kotlin
* import arrow.core.right
*
* val right7 =
* //sampleStart
* 7.right()
* //sampleEnd
* fun main() {
* println(right7)
* }
* ```
* <!--- KNIT example-either-15.kt -->
*
* ```kotlin
* import arrow.core.left
*
* val leftHello =
* //sampleStart
* "hello".left()
* //sampleEnd
* fun main() {
* println(leftHello)
* }
* ```
* <!--- KNIT example-either-16.kt -->
*
* ```kotlin
* import arrow.core.left
* import arrow.core.getOrElse
*
* //sampleStart
* val x = "hello".left()
* val value = x.getOrElse { "$it world!" }
* //sampleEnd
* fun main() {
* println("value = $value")
* }
* ```
* <!--- KNIT example-either-17.kt -->
*
* Another operation is `fold`. This operation will extract the value from the Either, or provide a default if the value is [Left]
*
* ```kotlin
* import arrow.core.Either
* import arrow.core.right
*
* //sampleStart
* val x : Either<Int, Int> = 7.right()
* val fold = x.fold({ 1 }, { it + 3 })
* //sampleEnd
* fun main() {
* println("fold = $fold")
* }
* ```
* <!--- KNIT example-either-18.kt -->
*
* ```kotlin
* import arrow.core.Either
* import arrow.core.left
*
* //sampleStart
* val y : Either<Int, Int> = 7.left()
* val fold = y.fold({ 1 }, { it + 3 })
* //sampleEnd
* fun main() {
* println("fold = $fold")
* }
* ```
* <!--- KNIT example-either-19.kt -->
*
* The `getOrHandle()` operation allows the transformation of an `Either.Left` value to a `Either.Right` using
* the value of [Left]. This can be useful when mapping to a single result type is required like `fold()`, but without
* the need to handle `Either.Right` case.
*
* As an example, we want to map an `Either<Throwable, Int>` to a proper HTTP status code:
*
* ```kotlin
* import arrow.core.Either
* import arrow.core.getOrElse
*
* //sampleStart
* val r: Either<Throwable, Int> = Either.Left(NumberFormatException())
* val httpStatusCode = r.getOrElse {
* when(it) {
* is NumberFormatException -> 400
* else -> 500
* }
* }
* //sampleEnd
* fun main() {
* println("httpStatusCode = $httpStatusCode")
* }
* ```
* <!--- KNIT example-either-20.kt -->
*/
public sealed class Either<out A, out B> {
/**
* Returns `true` if this is a [Left], `false` otherwise.
*/
public fun isLeft(): Boolean {
contract {
returns(true) implies (this@Either is Left<A>)
returns(false) implies (this@Either is Right<B>)
}
return this@Either is Left<A>
}
/**
* Returns `true` if this is a [Right], `false` otherwise.
*/
public fun isRight(): Boolean {
contract {
returns(true) implies (this@Either is Right<B>)
returns(false) implies (this@Either is Left<A>)
}
return this@Either is Right<B>
}
/**
* Returns `false` if [Right]
* or returns the result of the given [predicate] to the [Left] value.
*
* ```kotlin
* import arrow.core.Either
* import arrow.core.Either.Left
* import arrow.core.Either.Right
* import io.kotest.matchers.shouldBe
*
* fun test() {
* Left(12).isLeft { it > 10 } shouldBe true
* Left(7).isLeft { it > 10 } shouldBe false
*
* val right: Either<Int, String> = Right("Hello World")
* right.isLeft { it > 10 } shouldBe false
* }
* ```
* <!--- KNIT example-either-21.kt -->
* <!--- TEST lines.isEmpty() -->
*/
public inline fun isLeft(predicate: (A) -> Boolean): Boolean {
contract { returns(true) implies (this@Either is Left<A>) }
return this@Either is Left<A> && predicate(value)
}
/**
* Returns `false` if [Left]
* or returns the result of the given [predicate] to the [Right] value.
*
* ```kotlin
* import arrow.core.Either
* import arrow.core.Either.Left
* import arrow.core.Either.Right
* import io.kotest.matchers.shouldBe
*
* fun test() {
* Right(12).isRight { it > 10 } shouldBe true
* Right(7).isRight { it > 10 } shouldBe false
*
* val left: Either<String, Int> = Left("Hello World")
* left.isRight { it > 10 } shouldBe false
* }
* ```
* <!--- KNIT example-either-22.kt -->
* <!--- TEST lines.isEmpty() -->
*/
public inline fun isRight(predicate: (B) -> Boolean): Boolean {
contract { returns(true) implies (this@Either is Right<B>) }
return this@Either is Right<B> && predicate(value)
}
/**
* Transform an [Either] into a value of [C].
* Alternative to using `when` to fold an [Either] into a value [C].
*
* ```kotlin
* import arrow.core.Either
* import io.kotest.matchers.shouldBe
* import io.kotest.assertions.fail
*
* fun test() {
* Either.Right(1)
* .fold({ fail("Cannot be left") }, { it + 1 }) shouldBe 2
*
* Either.Left(RuntimeException("Boom!"))
* .fold({ -1 }, { fail("Cannot be right") }) shouldBe -1
* }
* ```
* <!--- KNIT example-either-23.kt -->
* <!--- TEST lines.isEmpty() -->
*
* @param ifLeft transform the [Either.Left] type [A] to [C].
* @param ifRight transform the [Either.Right] type [B] to [C].
* @return the transformed value [C] by applying [ifLeft] or [ifRight] to [A] or [B] respectively.
*/
public inline fun <C> fold(ifLeft: (left: A) -> C, ifRight: (right: B) -> C): C {
contract {
callsInPlace(ifLeft, InvocationKind.AT_MOST_ONCE)
callsInPlace(ifRight, InvocationKind.AT_MOST_ONCE)
}
return when (this) {
is Right -> ifRight(value)
is Left -> ifLeft(value)
}
}
/**
* Swap the generic parameters [A] and [B] of this [Either].
*
* ```kotlin
* import arrow.core.Either
* import io.kotest.matchers.shouldBe
*
* fun test() {
* Either.Left("left").swap() shouldBe Either.Right("left")
* Either.Right("right").swap() shouldBe Either.Left("right")
* }
* ```
* <!--- KNIT example-either-24.kt -->
* <!-- TEST lines.isEmpty() -->
*/
public fun swap(): Either<B, A> =
fold({ Right(it) }, { Left(it) })
/**
* Map, or transform, the right value [B] of this [Either] to a new value [C].
*
* ```kotlin
* import arrow.core.Either
* import io.kotest.matchers.shouldBe
*
* fun test() {
* Either.Right(12).map { _: Int ->"flower" } shouldBe Either.Right("flower")
* Either.Left(12).map { _: Nothing -> "flower" } shouldBe Either.Left(12)
* }
* ```
* <!--- KNIT example-either-25.kt -->
* <!--- TEST lines.isEmpty() -->
*/
public inline fun <C> map(f: (right: B) -> C): Either<A, C> {
contract {
callsInPlace(f, InvocationKind.AT_MOST_ONCE)
}
return flatMap { Right(f(it)) }
}
/**
* Map, or transform, the left value [A] of this [Either] to a new value [C].
*
* ```kotlin
* import arrow.core.Either
* import io.kotest.matchers.shouldBe
*
* fun test() {
* Either.Right(12).mapLeft { _: Nothing -> "flower" } shouldBe Either.Right(12)
* Either.Left(12).mapLeft { _: Int -> "flower" } shouldBe Either.Left("flower")
* }
* ```
* <!--- KNIT example-either-26.kt -->
* <!--- TEST lines.isEmpty() -->
*/
public inline fun <C> mapLeft(f: (A) -> C): Either<C, B> {
contract {
callsInPlace(f, InvocationKind.AT_MOST_ONCE)
}
return fold({ Left(f(it)) }, { Right(it) })
}
/**
* Performs the given [action] on the encapsulated [B] value if this instance represents [Either.Right].
* Returns the original [Either] unchanged.
*
* ```kotlin
* import arrow.core.Either
* import io.kotest.matchers.shouldBe
*
* fun test() {
* Either.Right(1).onRight(::println) shouldBe Either.Right(1)
* }
* ```
* <!--- KNIT example-either-27.kt -->
* <!--- TEST lines.isEmpty() -->
*/
public inline fun onRight(action: (right: B) -> Unit): Either<A, B> {
contract {
callsInPlace(action, InvocationKind.AT_MOST_ONCE)
}
return also { if (it.isRight()) action(it.value) }
}
/**
* Performs the given [action] on the encapsulated [A] if this instance represents [Either.Left].
* Returns the original [Either] unchanged.
*
* ```kotlin
* import arrow.core.Either
* import io.kotest.matchers.shouldBe
*
* fun test() {
* Either.Left(2).onLeft(::println) shouldBe Either.Left(2)
* }
* ```
* <!--- KNIT example-either-28.kt -->
* <!--- TEST lines.isEmpty() -->
*/
public inline fun onLeft(action: (left: A) -> Unit): Either<A, B> {
contract {
callsInPlace(action, InvocationKind.AT_MOST_ONCE)
}
return also { if (it.isLeft()) action(it.value) }
}
/**
* Returns the unwrapped value [B] of [Either.Right] or `null` if it is [Either.Left].
*
* ```kotlin
* import arrow.core.Either
* import io.kotest.matchers.shouldBe
*
* fun test() {
* Either.Right(12).getOrNull() shouldBe 12
* Either.Left(12).getOrNull() shouldBe null
* }
* ```
* <!--- KNIT example-either-29.kt -->
* <!--- TEST lines.isEmpty() -->
*/
public fun getOrNull(): B? {
contract {
returns(null) implies (this@Either is Left<A>)
returnsNotNull() implies (this@Either is Right<B>)
}
return getOrElse { null }
}
/**
* Returns the unwrapped value [A] of [Either.Left] or `null` if it is [Either.Right].
*
* ```kotlin
* import arrow.core.Either
* import io.kotest.matchers.shouldBe
*
* fun test() {
* Either.Right(12).leftOrNull() shouldBe null
* Either.Left(12).leftOrNull() shouldBe 12
* }
* ```
* <!--- KNIT example-either-30.kt -->
* <!--- TEST lines.isEmpty() -->
*/
public fun leftOrNull(): A? {
contract {
returnsNotNull() implies (this@Either is Left<A>)
returns(null) implies (this@Either is Right<B>)
}
return fold(::identity) { null }
}
/**
* Transforms [Either] into [Option],
* where the encapsulated value [B] is wrapped in [Some] when this instance represents [Either.Right],
* or [None] if it is [Either.Left].
*
* ```kotlin
* import arrow.core.Either
* import arrow.core.Some
* import arrow.core.None
* import io.kotest.matchers.shouldBe
*
* fun test() {
* Either.Right(12).getOrNone() shouldBe Some(12)
* Either.Left(12).getOrNone() shouldBe None
* }
* ```
* <!--- KNIT example-either-31.kt -->
* <!--- TEST lines.isEmpty() -->
*/
public fun getOrNone(): Option<B> = fold({ None }, { Some(it) })
/**
* The left side of the disjoint union, as opposed to the [Right] side.
*/
public data class Left<out A> constructor(val value: A) : Either<A, Nothing>() {
override fun toString(): String = "Either.Left($value)"
public companion object
}
/**
* The right side of the disjoint union, as opposed to the [Left] side.
*/
public data class Right<out B> constructor(val value: B) : Either<Nothing, B>() {
override fun toString(): String = "Either.Right($value)"
public companion object {
@PublishedApi
internal val unit: Either<Nothing, Unit> = Right(Unit)
}
}
override fun toString(): String = fold(
{ "Either.Left($it)" },
{ "Either.Right($it)" }
)
public fun toIor(): Ior<A, B> =
fold({ Ior.Left(it) }, { Ior.Right(it) })
public companion object {
@JvmStatic
public inline fun <R> catch(f: () -> R): Either<Throwable, R> =
arrow.core.raise.catch({ f().right() }) { it.left() }
@JvmStatic
public inline fun <reified T : Throwable, R> catchOrThrow(f: () -> R): Either<T, R> =
arrow.core.raise.catch<T, Either<T, R>>({ f().right() }) { it.left() }
public inline fun <E, A, B, Z> zipOrAccumulate(
combine: (E, E) -> E,
a: Either<E, A>,
b: Either<E, B>,
transform: (A, B) -> Z,
): Either<E, Z> {
contract { callsInPlace(transform, InvocationKind.AT_MOST_ONCE) }
return zipOrAccumulate(combine, a, b, unit, unit, unit, unit, unit, unit, unit, unit) { aa, bb, _, _, _, _, _, _, _, _ ->
transform(aa, bb)
}
}
public inline fun <E, A, B, C, Z> zipOrAccumulate(
combine: (E, E) -> E,
a: Either<E, A>,
b: Either<E, B>,
c: Either<E, C>,
transform: (A, B, C) -> Z,
): Either<E, Z> {
contract { callsInPlace(transform, InvocationKind.AT_MOST_ONCE) }
return zipOrAccumulate(combine, a, b, c, unit, unit, unit, unit, unit, unit, unit) { aa, bb, cc, _, _, _, _, _, _, _ ->
transform(aa, bb, cc)
}
}
public inline fun <E, A, B, C, D, Z> zipOrAccumulate(
combine: (E, E) -> E,
a: Either<E, A>,
b: Either<E, B>,
c: Either<E, C>,
d: Either<E, D>,
transform: (A, B, C, D) -> Z,
): Either<E, Z> {
contract { callsInPlace(transform, InvocationKind.AT_MOST_ONCE) }
return zipOrAccumulate(combine, a, b, c, d, unit, unit, unit, unit, unit, unit) { aa, bb, cc, dd, _, _, _, _, _, _ ->
transform(aa, bb, cc, dd)
}
}
public inline fun <E, A, B, C, D, EE, Z> zipOrAccumulate(
combine: (E, E) -> E,
a: Either<E, A>,
b: Either<E, B>,
c: Either<E, C>,
d: Either<E, D>,
e: Either<E, EE>,
transform: (A, B, C, D, EE) -> Z,
): Either<E, Z> {
contract { callsInPlace(transform, InvocationKind.AT_MOST_ONCE) }
return zipOrAccumulate(combine, a, b, c, d, e, unit, unit, unit, unit, unit) { aa, bb, cc, dd, ee, _, _, _, _, _ ->
transform(aa, bb, cc, dd, ee)
}
}
public inline fun <E, A, B, C, D, EE, FF, Z> zipOrAccumulate(
combine: (E, E) -> E,
a: Either<E, A>,
b: Either<E, B>,
c: Either<E, C>,
d: Either<E, D>,
e: Either<E, EE>,
f: Either<E, FF>,
transform: (A, B, C, D, EE, FF) -> Z,
): Either<E, Z> {
contract { callsInPlace(transform, InvocationKind.AT_MOST_ONCE) }
return zipOrAccumulate(combine, a, b, c, d, e, f, unit, unit, unit, unit) { aa, bb, cc, dd, ee, ff, _, _, _, _ ->
transform(aa, bb, cc, dd, ee, ff)
}
}
public inline fun <E, A, B, C, D, EE, F, G, Z> zipOrAccumulate(
combine: (E, E) -> E,
a: Either<E, A>,
b: Either<E, B>,
c: Either<E, C>,
d: Either<E, D>,
e: Either<E, EE>,
f: Either<E, F>,
g: Either<E, G>,
transform: (A, B, C, D, EE, F, G) -> Z,
): Either<E, Z> {
contract { callsInPlace(transform, InvocationKind.AT_MOST_ONCE) }
return zipOrAccumulate(combine, a, b, c, d, e, f, g, unit, unit, unit) { aa, bb, cc, dd, ee, ff, gg, _, _, _ ->
transform(aa, bb, cc, dd, ee, ff, gg)
}
}
public inline fun <E, A, B, C, D, EE, F, G, H, Z> zipOrAccumulate(
combine: (E, E) -> E,
a: Either<E, A>,
b: Either<E, B>,
c: Either<E, C>,
d: Either<E, D>,
e: Either<E, EE>,
f: Either<E, F>,
g: Either<E, G>,
h: Either<E, H>,
transform: (A, B, C, D, EE, F, G, H) -> Z,
): Either<E, Z> {
contract { callsInPlace(transform, InvocationKind.AT_MOST_ONCE) }
return zipOrAccumulate(combine, a, b, c, d, e, f, g, h, unit, unit) { aa, bb, cc, dd, ee, ff, gg, hh, _, _ ->
transform(aa, bb, cc, dd, ee, ff, gg, hh)
}
}
public inline fun <E, A, B, C, D, EE, F, G, H, I, Z> zipOrAccumulate(
combine: (E, E) -> E,
a: Either<E, A>,
b: Either<E, B>,
c: Either<E, C>,
d: Either<E, D>,
e: Either<E, EE>,
f: Either<E, F>,
g: Either<E, G>,
h: Either<E, H>,
i: Either<E, I>,
transform: (A, B, C, D, EE, F, G, H, I) -> Z,
): Either<E, Z> {
contract { callsInPlace(transform, InvocationKind.AT_MOST_ONCE) }
return zipOrAccumulate(combine, a, b, c, d, e, f, g, h, i, unit) { aa, bb, cc, dd, ee, ff, gg, hh, ii, _ ->
transform(aa, bb, cc, dd, ee, ff, gg, hh, ii)
}
}
@Suppress("DuplicatedCode")
public inline fun <E, A, B, C, D, EE, F, G, H, I, J, Z> zipOrAccumulate(
combine: (E, E) -> E,
a: Either<E, A>,
b: Either<E, B>,
c: Either<E, C>,
d: Either<E, D>,
e: Either<E, EE>,
f: Either<E, F>,
g: Either<E, G>,
h: Either<E, H>,
i: Either<E, I>,
j: Either<E, J>,
transform: (A, B, C, D, EE, F, G, H, I, J) -> Z,
): Either<E, Z> {
contract { callsInPlace(transform, InvocationKind.AT_MOST_ONCE) }
return if (a is Right && b is Right && c is Right && d is Right && e is Right && f is Right && g is Right && h is Right && i is Right && j is Right) {
Right(transform(a.value, b.value, c.value, d.value, e.value, f.value, g.value, h.value, i.value, j.value))
} else {
var accumulatedError: Any? = EmptyValue
accumulatedError = if (a is Left) a.value else accumulatedError
accumulatedError = if (b is Left) EmptyValue.combine(accumulatedError, b.value, combine) else accumulatedError
accumulatedError = if (c is Left) EmptyValue.combine(accumulatedError, c.value, combine) else accumulatedError
accumulatedError = if (d is Left) EmptyValue.combine(accumulatedError, d.value, combine) else accumulatedError
accumulatedError = if (e is Left) EmptyValue.combine(accumulatedError, e.value, combine) else accumulatedError
accumulatedError = if (f is Left) EmptyValue.combine(accumulatedError, f.value, combine) else accumulatedError
accumulatedError = if (g is Left) EmptyValue.combine(accumulatedError, g.value, combine) else accumulatedError
accumulatedError = if (h is Left) EmptyValue.combine(accumulatedError, h.value, combine) else accumulatedError
accumulatedError = if (i is Left) EmptyValue.combine(accumulatedError, i.value, combine) else accumulatedError
accumulatedError = if (j is Left) EmptyValue.combine(accumulatedError, j.value, combine) else accumulatedError
@Suppress("UNCHECKED_CAST")
(Left(accumulatedError as E))
}
}
public inline fun <E, A, B, Z> zipOrAccumulate(
a: Either<E, A>,
b: Either<E, B>,
transform: (A, B) -> Z,
): Either<NonEmptyList<E>, Z> {
contract { callsInPlace(transform, InvocationKind.AT_MOST_ONCE) }
return zipOrAccumulate(a, b, unit, unit, unit, unit, unit, unit, unit, unit) { aa, bb, _, _, _, _, _, _, _, _ ->
transform(aa, bb)
}
}
public inline fun <E, A, B, C, Z> zipOrAccumulate(
a: Either<E, A>,
b: Either<E, B>,
c: Either<E, C>,
transform: (A, B, C) -> Z,
): Either<NonEmptyList<E>, Z> {
contract { callsInPlace(transform, InvocationKind.AT_MOST_ONCE) }
return zipOrAccumulate(a, b, c, unit, unit, unit, unit, unit, unit, unit) { aa, bb, cc, _, _, _, _, _, _, _ ->
transform(aa, bb, cc)
}
}
public inline fun <E, A, B, C, D, Z> zipOrAccumulate(
a: Either<E, A>,
b: Either<E, B>,
c: Either<E, C>,
d: Either<E, D>,
transform: (A, B, C, D) -> Z,
): Either<NonEmptyList<E>, Z> {
contract { callsInPlace(transform, InvocationKind.AT_MOST_ONCE) }
return zipOrAccumulate(a, b, c, d, unit, unit, unit, unit, unit, unit) { aa, bb, cc, dd, _, _, _, _, _, _ ->
transform(aa, bb, cc, dd)
}
}