rustica 0.12.0

Rustica is a functional programming library for the Rust language.
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
//! # Either Datatype
//!
//! The `Either` datatype represents values with two possibilities: a value of type `L` (Left) or a value of type `R` (Right).
//! It is a fundamental functional programming construct that is similar to Rust's built-in `Result<T, E>` but without the
//! semantic meaning of success/failure.
//!
//! ## Quick Start
//!
//! Model a computation that can produce one of two values:
//!
//! ```rust
//! use rustica::datatypes::either::Either;
//! use rustica::traits::functor::Functor;
//! use rustica::traits::monad::Monad;
//!
//! // `Either` itself does not encode success/failure, but it is commonly used in an error-like way:
//! // `Left` as the "error"/alternative branch and `Right` as the "success"/preferred branch.
//! let success: Either<String, i32> = Either::Right(42);
//! let error: Either<String, i32> = Either::Left("Something went wrong".to_string());
//!
//! // Transform successful values, preserve errors
//! let doubled = success.fmap(|x| x * 2);
//! assert_eq!(doubled, Either::Right(84));
//!
//! let still_error = error.fmap(|x| x * 2);
//! assert_eq!(still_error, Either::Left("Something went wrong".to_string()));
//!
//! // Chain operations with bind
//! let safe_sqrt = |x: &i32| -> Either<String, f64> {
//!     if *x < 0 {
//!         Either::Left("Cannot take square root of negative number".to_string())
//!     } else {
//!         Either::Right((*x as f64).sqrt())
//!     }
//! };
//!
//! let result = Either::Right(16)
//!     .bind(safe_sqrt)
//!     .fmap(|x| x * 2.0);
//!
//! assert_eq!(result, Either::Right(8.0));
//! ```
//!
//! ## Functional Programming Context
//!
//! In functional programming, the `Either` type is commonly used for:
//!
//! - Representing computations that can produce one of two different types of values
//! - Handling branching logic in a composable way
//! - Implementing error handling without the success/failure semantics of `Result`
//! - Building more complex data structures and control flow mechanisms
//!
//! ## Type Class Implementations
//!
//! The `Either` type implements several important functional programming abstractions:
//!
//! - `Functor`: Maps over the right value with `fmap`
//! - `Applicative`: Applies functions wrapped in `Either` to values wrapped in `Either`
//! - `Monad`: Chains computations that may produce either left or right values
//! - `Alternative`: Provides choice between alternatives (requires `L: Default + Clone`)
//!
//! **Note**: This crate previously provided an `Identity` trait for value extraction, but it is deprecated.
//! Prefer explicit methods like `right_option()`, `left_option()`, pattern matching, or `unwrap()` when you
//! intentionally want the `Right` value.
//!
//! ## Type Class Laws
//!
//! The `Either` type implements the following type class laws. See the documentation for
//! the specific functions (`fmap`, `apply`, `bind`) for examples demonstrating these laws.
//!
//! ### Functor Laws
//!
//! The `Either` type satisfies the functor laws:
//!
//! 1. **Identity Law**: `fmap(id) = id`
//!    - Mapping the identity function over an `Either` returns the original `Either` unchanged.
//!
//! 2. **Composition Law**: `fmap(f . g) = fmap(f) . fmap(g)`
//!    - Mapping a composed function is the same as mapping each function in sequence.
//!    - Note: The functor laws hold for both `Left` and `Right` values (trivially for `Left` values).
//!
//! ### Applicative Laws
//!
//! The `Either` type satisfies the applicative laws:
//!
//! 1. **Identity Law**: `pure(id) <*> v = v`
//!    - Applying the pure identity function to any value returns the original value.
//!
//! 2. **Homomorphism Law**: `pure(f) <*> pure(x) = pure(f(x))`
//!    - Applying a pure function to a pure value is the same as applying the function to the value and then wrapping in `pure`.
//!
//! 3. **Interchange Law**: `u <*> pure(y) = pure($ y) <*> u`
//!    - Where `$ y` is a function that applies its argument to y.
//!
//! 4. **Composition Law**: `pure(.) <*> u <*> v <*> w = u <*> (v <*> w)`
//!    - Composing applicative functions is associative.
//!
//! ### Monad Laws
//!
//! The `Either` type satisfies the monad laws:
//!
//! 1. **Left Identity**: `return a >>= f = f a`
//!    - Binding a function to a pure value is the same as applying the function directly.
//!
//! 2. **Right Identity**: `m >>= return = m`
//!    - Binding the pure function to a monad returns the original monad.
//!
//! 3. **Associativity**: `(m >>= f) >>= g = m >>= (\x -> f x >>= g)`
//!    - Sequential binds can be nested in either direction with the same result.
//!
//! ## Basic Usage
//!
//! ```rust
//! use rustica::datatypes::either::Either;
//! use rustica::prelude::*;
//!
//! // Create Either values
//! let left_value: Either<i32, &str> = Either::left(42);
//! let right_value: Either<i32, &str> = Either::right("hello");
//!
//! // Pattern matching
//! match left_value {
//!     Either::Left(n) => println!("Got left value: {}", n),
//!     Either::Right(s) => println!("Got right value: {}", s),
//! }
//!
//! // Transform values using specific transformers
//! let doubled = left_value.fmap_left(|x| x * 2);  // Either::Left(84)
//!
//! // Functor operations (maps over Right values only)
//! let right_val: Either<&str, i32> = Either::right(42);
//! let mapped = right_val.fmap(|x| x * 2);  // Either::Right(84)
//! ```
//!
//! ## Advanced Usage: Chaining Computations
//!
//! ```rust
//! use rustica::datatypes::either::Either;
//! use rustica::traits::monad::Monad;
//!
//! // Create a function that might fail (return Left) or succeed (return Right)
//! fn safe_divide(a: i32, b: i32) -> Either<String, i32> {
//!     if b == 0 {
//!         Either::left("Division by zero".to_string())
//!     } else {
//!         Either::right(a / b)
//!     }
//! }
//!
//! // Chain computations safely
//! let result = safe_divide(10, 2)
//!     .bind(|x| safe_divide(*x, 1)); // Will succeed with Right(5)
//!     
//! let error_result = safe_divide(10, 2)
//!     .bind(|x| safe_divide(*x, 0)); // Will fail with Left("Division by zero")
//!
//! assert_eq!(result, Either::right(5));
//! assert_eq!(error_result, Either::left("Division by zero".to_string()));
//! ```
//!
//! ## Conversion with Result
//!
//! `Either` can be easily converted to and from `Result`:
//!
//! ```rust
//! use rustica::datatypes::either::Either;
//!
//! // From Result to Either
//! let ok_result: Result<i32, &str> = Ok(42);
//! let either = Either::from_result(ok_result);
//! assert_eq!(either, Either::right(42));
//!
//! // From Either to Result
//! let either: Either<&str, i32> = Either::right(42);
//! let result = either.to_result();
//! assert_eq!(result, Ok(42));
//! ```
//!
//! ## Iterator Support
//!
//! The `Either` type provides **symmetric iterator support** for both `Left` and `Right` values.
//! Both `Left` and `Right` values can be iterated over, yielding at most one item.
//!
//! This design allows `Either<L, R>` to function similarly to `Option<L>` or `Option<R>`
//! in iterator contexts, where the contained value (if present) is treated as the "value of interest".
//!
//! Six iterator types are provided:
//!
//! - `EitherIter<R>` - Consumes the `Either` and iterates over the contained `Right` value
//! - `EitherIterRef<'a, R>` - Provides references to the `Right` value
//! - `EitherIterMut<'a, R>` - Provides mutable references to the `Right` value
//! - `EitherLeftIter<L>` - Consumes the `Either` and iterates over the contained `Left` value
//! - `EitherLeftIterRef<'a, L>` - Provides references to the `Left` value
//! - `EitherLeftIterMut<'a, L>` - Provides mutable references to the `Left` value
//!
//! All iterator implementations yield at most one item, making them similar to `Option::into_iter()`.
//!
//! ```rust
//! use rustica::datatypes::either::Either;
//!
//! // Iterate over Right values
//! let right_val: Either<&str, i32> = Either::right(42);
//! let values: Vec<i32> = right_val.into_iter().collect();
//! assert_eq!(values, vec![42]);
//!
//! // Left values yield empty iterators when using the Right-biased iterator
//! let left_val: Either<&str, i32> = Either::left("error");
//! let values: Vec<i32> = left_val.into_iter().collect();
//! assert!(values.is_empty());
//!
//! // Reference iteration works similarly for Right
//! let right_val: Either<&str, i32> = Either::right(42);
//! let values: Vec<&i32> = (&right_val).into_iter().collect();
//! assert_eq!(values, vec![&42]);
//!
//! // Iterate over Left values
//! let left_val: Either<i32, &str> = Either::left(100);
//! let values: Vec<i32> = left_val.left_iter().collect();
//! assert_eq!(values, vec![100]);
//!
//! // Right values yield empty iterators when using the Left-biased iterator
//! let right_val: Either<i32, &str> = Either::right("success");
//! let values: Vec<i32> = right_val.left_iter().collect();
//! assert!(values.is_empty());
//!
//! // Reference iteration works similarly for Left
//! let left_val: Either<i32, &str> = Either::left(100);
//! let values: Vec<&i32> = left_val.left_iter_ref().collect();
//! assert_eq!(values, vec![&100]);
//! ```
//!
//! ## Safety Considerations
//!
//! Several methods in `Either` can panic and should be used with caution:
//!
//! - `unwrap_left()`, `unwrap_right()`: Panic if called on wrong variant
//! - `left_value()`, `right_value()`: Panic if called on wrong variant  
//! - `left_ref()`, `right_ref()`: Panic if called on wrong variant
//!
//! **Recommended alternatives**: Use pattern matching, `left_option()`, `right_option()`, or the safe `*_or()` methods.

use crate::datatypes::error::EitherError;
use crate::traits::alternative::Alternative;
use crate::traits::applicative::Applicative;
use crate::traits::bifunctor::Bifunctor;
use crate::traits::functor::Functor;
use crate::traits::hkt::{BinaryHKT, HKT};
use crate::traits::monad::Monad;
use crate::traits::pure::Pure;
use quickcheck::{Arbitrary, Gen};

/// The `Either` type represents values with two possibilities: a value of type `L` or a value of type `R`.
/// This is similar to `Result<T, E>` but without the semantic meaning of success/failure.
///
/// # Type Parameters
///
/// * `L`: The type of the left value
/// * `R`: The type of the right value
///
/// See the module-level documentation for examples and more information.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Either<L, R> {
    /// Contains a value of type `L`
    Left(L),
    /// Contains a value of type `R`
    Right(R),
}

impl<L, R> Either<L, R> {
    /// Creates a new `Either::Left` containing the given value.
    ///
    /// Left represents the first possibility of the Either type.
    ///
    /// # Usage
    ///
    /// Use this constructor to create an `Either` instance holding a `Left` value.
    ///
    /// ```
    /// # use rustica::datatypes::either::Either;
    /// let e: Either<i32, String> = Either::left(42);
    /// assert!(e.is_left());
    /// ```
    #[inline]
    pub const fn left(l: L) -> Self {
        Either::Left(l)
    }

    /// Creates a new `Either::Right` containing the given value.
    ///
    /// Right represents the second possibility of the Either type.
    ///
    /// # Usage
    ///
    /// Use this constructor to create an `Either` instance holding a `Right` value.
    ///
    /// ```
    /// # use rustica::datatypes::either::Either;
    /// let e: Either<i32, String> = Either::right("hello".to_string());
    /// assert!(e.is_right());
    /// ```
    #[inline]
    pub const fn right(r: R) -> Self {
        Either::Right(r)
    }

    /// Returns `true` if this is a `Left` value.
    ///
    /// # Usage
    ///
    /// Check if an `Either` is `Left` without consuming it or panicking.
    /// Useful for conditional logic based on the variant.
    ///
    /// ```
    /// # use rustica::datatypes::either::Either;
    /// let left: Either<i32, &str> = Either::Left(1);
    /// assert!(left.is_left());
    /// let right: Either<i32, &str> = Either::Right("test");
    /// assert!(!right.is_left());
    /// ```
    #[inline]
    pub const fn is_left(&self) -> bool {
        matches!(self, Either::Left(_))
    }

    /// Returns `true` if this is a `Right` value.
    ///
    /// # Usage
    ///
    /// Check if an `Either` is `Right` without consuming it or panicking.
    /// Useful for conditional logic based on the variant.
    ///
    /// ```
    /// # use rustica::datatypes::either::Either;
    /// let right: Either<i32, &str> = Either::Right("test");
    /// assert!(right.is_right());
    /// let left: Either<i32, &str> = Either::Left(1);
    /// assert!(!left.is_right());
    /// ```
    #[inline]
    pub const fn is_right(&self) -> bool {
        matches!(self, Either::Right(_))
    }

    /// Maps a function over the left value, leaving a right value unchanged.
    ///
    /// This is similar to `Result::map_err` but for `Either`.
    ///
    /// # Usage
    ///
    /// Use `fmap_left` to apply a transformation to the `Left` value if present,
    /// while leaving a `Right` value untouched. This is useful for changing the
    /// type or value of the `Left` case, often an error or alternative type.
    ///
    /// ```
    /// # use rustica::datatypes::either::Either;
    /// let left_val: Either<i32, String> = Either::Left(10);
    /// let mapped = left_val.fmap_left(|x| x * 2);
    /// assert_eq!(mapped, Either::Left(20));
    ///
    /// let right_val: Either<i32, String> = Either::Right("hello".to_string());
    /// let mapped_right = right_val.fmap_left(|x| x * 2); // f is not called
    /// assert_eq!(mapped_right, Either::Right("hello".to_string()));
    /// ```
    #[inline]
    pub fn fmap_left<T, F>(self, f: F) -> Either<T, R>
    where
        F: Fn(L) -> T,
    {
        match self {
            Either::Left(l) => Either::Left(f(l)),
            Either::Right(r) => Either::Right(r),
        }
    }

    /// Maps a function over the right value, leaving a left value unchanged.
    ///
    /// This is similar to `Result::map` but for `Either`. It is the primary
    /// way to transform the `Right` variant and is fundamental to `Either`'s
    /// role as a `Functor` (see `Functor::fmap_owned` for the general version).
    ///
    /// # Usage
    ///
    /// Use `fmap_right` to apply a transformation to the `Right` value without
    /// affecting a `Left` value. For example, if you have an `Either<Error, Data>`,
    /// you can use `fmap_right` to process `Data` while propagating `Error`.
    ///
    /// ```
    /// # use rustica::datatypes::either::Either;
    /// let right_val: Either<String, i32> = Either::Right(10);
    /// let mapped = right_val.fmap_right(|x| x * 2);
    /// assert_eq!(mapped, Either::Right(20));
    ///
    /// let left_val: Either<String, i32> = Either::Left("error".to_string());
    /// let mapped_left = left_val.fmap_right(|x| x * 2); // f is not called
    /// assert_eq!(mapped_left, Either::Left("error".to_string()));
    /// ```
    #[inline]
    pub fn fmap_right<T, F>(self, mut f: F) -> Either<L, T>
    where
        F: FnMut(R) -> T,
    {
        match self {
            Either::Left(l) => Either::Left(l),
            Either::Right(r) => Either::Right(f(r)),
        }
    }

    /// Extracts the left value, panicking if this is a `Right`.
    ///
    /// # Usage
    ///
    /// Use this method when you are certain that the `Either` contains a `Left`
    /// value and a panic is an acceptable outcome if this assumption is wrong.
    /// This is often used in tests or when a `Left` value is a precondition
    /// for subsequent logic. For a non-panicking alternative, consider `left_option`
    /// or pattern matching.
    ///
    /// # Panics
    ///
    /// Panics if called on a `Right` value.
    #[inline]
    pub fn unwrap_left(self) -> L {
        match self {
            Either::Left(l) => l,
            Either::Right(_) => panic!("called unwrap_left on Right value"),
        }
    }

    /// Extracts the right value, panicking if this is a `Left`.
    ///
    /// This method delegates to `right_value`.
    ///
    /// # Usage
    ///
    /// Use this method when you are certain that the `Either` contains a `Right`
    /// value and a panic is an acceptable outcome if this assumption is wrong.
    /// This is often used in tests or when a `Right` value is a precondition
    /// for subsequent logic. For a non-panicking alternative, consider `right_option`
    /// or pattern matching.
    ///
    /// # Panics
    ///
    /// Panics if called on a `Left` value.
    #[inline]
    pub fn unwrap_right(self) -> R {
        match self {
            Either::Right(r) => r,
            Either::Left(_) => panic!("called unwrap_right on Left value"),
        }
    }

    /// Unwraps an either, yielding the content of a `Right` or panicking.
    ///
    /// This is the standard `unwrap()` method that extracts the `Right` value,
    /// following Rust's convention where `unwrap()` extracts the "success" value.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::datatypes::either::Either;
    ///
    /// let right: Either<String, i32> = Either::Right(42);
    /// let left: Either<String, i32> = Either::Left("error".to_string());
    ///
    /// assert_eq!(right.unwrap(), 42);
    /// // left.unwrap() would panic
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if called on a `Left` value.
    #[inline]
    pub fn unwrap(self) -> R {
        match self {
            Either::Right(r) => r,
            Either::Left(_) => panic!("called `Either::unwrap()` on a `Left` value"),
        }
    }

    /// Unwraps an either, yielding the content of a `Right` or a default value.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::datatypes::either::Either;
    ///
    /// let right: Either<String, i32> = Either::Right(42);
    /// let left: Either<String, i32> = Either::Left("error".to_string());
    ///
    /// assert_eq!(right.unwrap_or(0), 42);
    /// assert_eq!(left.unwrap_or(0), 0);
    /// ```
    #[inline]
    pub fn unwrap_or(self, default: R) -> R {
        match self {
            Either::Right(r) => r,
            Either::Left(_) => default,
        }
    }

    /// Returns the contained `Left` value, consuming the `self` value.
    ///
    /// Because this function consumes the original `Either`, there is no need to clone
    /// the content if `L` is not `Copy`. This can be more efficient than `unwrap_left`
    /// in such cases, though `unwrap_left` also consumes `self`.
    /// The main distinction is often stylistic or historical.
    ///
    /// # Usage
    ///
    /// Similar to `unwrap_left`, use this when you expect a `Left` value and
    /// want to consume the `Either` to get it. A panic occurs if it's `Right`.
    ///
    /// # Panics
    ///
    /// Panics if the value is a `Right`.
    #[inline]
    pub fn left_value(self) -> L
    where
        Self: Sized,
    {
        match self {
            Either::Left(l) => l,
            Either::Right(_) => panic!("called left_value on Right value"),
        }
    }

    /// Returns the contained `Right` value, consuming the `self` value.
    ///
    /// Because this function consumes the original `Either`, there is no need to clone
    /// the content if `R` is not `Copy`. This can be more efficient than methods
    /// that might require cloning if `self` were borrowed.
    ///
    /// # Usage
    ///
    /// Similar to `unwrap_right`, use this when you expect a `Right` value and
    /// want to consume the `Either` to get it. A panic occurs if it's `Left`.
    ///
    /// # Panics
    ///
    /// Panics if the value is a `Left`.
    #[inline]
    pub fn right_value(self) -> R {
        match self {
            Either::Right(r) => r,
            Either::Left(_) => panic!("called right_value on Left value"),
        }
    }

    /// Returns a reference to the `Left` value.
    ///
    /// # Usage
    ///
    /// Use this to get an immutable reference to the `Left` value without consuming
    /// the `Either`. This is useful when you need to inspect the `Left` value but
    /// keep the `Either` instance for later use. Panics if the `Either` is `Right`.
    ///
    /// # Panics
    ///
    /// Panics if the value is a `Right`.
    #[inline]
    pub fn left_ref(&self) -> &L {
        match self {
            Either::Left(l) => l,
            Either::Right(_) => panic!("Called left_ref on an Either::Right"),
        }
    }

    /// Returns a reference to the `Right` value.
    ///
    /// # Usage
    ///
    /// Use this to get an immutable reference to the `Right` value without consuming
    /// the `Either`. This is useful when you need to inspect the `Right` value but
    /// keep the `Either` instance for later use. Panics if the `Either` is `Left`.
    ///
    /// # Panics
    ///
    /// Panics if the value is a `Left`.
    #[inline]
    pub fn right_ref(&self) -> &R {
        self.into_iter()
            .next()
            .expect("Called right_ref() on a Left value")
    }

    /// Returns the contained `Right` value or a default.
    ///
    /// Similar to `Result::unwrap_or` but for `Either`.
    /// Consumes `self` and returns the `Right` value if present, otherwise returns
    /// the provided `default`.
    ///
    /// # Usage
    ///
    /// Use this method to extract the `Right` value if it exists, or fall back to a
    /// default value if it's a `Left`. This avoids panics.
    ///
    /// ```
    /// # use rustica::datatypes::either::Either;
    /// let right: Either<String, i32> = Either::Right(100);
    /// assert_eq!(right.right_or(0), 100);
    ///
    /// let left: Either<String, i32> = Either::Left("error".to_string());
    /// assert_eq!(left.right_or(0), 0);
    /// ```
    #[inline]
    pub fn right_or(self, default: R) -> R {
        self.into_iter().next().unwrap_or(default)
    }

    /// Returns the contained `Left` value or a default.
    ///
    /// Similar to `Result::err().unwrap_or()` but for `Either`.
    /// Consumes `self` and returns the `Left` value if present, otherwise returns
    /// the provided `default`.
    ///
    /// # Usage
    ///
    /// Use this method to extract the `Left` value if it exists, or fall back to a
    /// default value if it's a `Right`. This avoids panics.
    ///
    /// ```
    /// # use rustica::datatypes::either::Either;
    /// let left: Either<i32, String> = Either::Left(42);
    /// assert_eq!(left.left_or(0), 42);
    ///
    /// let right: Either<i32, String> = Either::Right("ok".to_string());
    /// assert_eq!(right.left_or(0), 0);
    /// ```
    #[inline]
    pub fn left_or(self, default: L) -> L {
        match self {
            Either::Left(l) => l,
            Either::Right(_) => default,
        }
    }

    /// Returns the contained `Right` value as an Option.
    ///
    /// Returns `Some(R)` for `Right(R)` values and `None` for `Left(L)` values.
    /// Consumes `self`.
    ///
    /// # Usage
    ///
    /// Convert an `Either` into an `Option<R>`, discarding the `Left` value.
    /// This is useful for integrating with Option-based APIs or when you only
    /// care about the `Right` case and want to treat `Left` as absence of value.
    ///
    /// ```
    /// # use rustica::datatypes::either::Either;
    /// let right: Either<String, i32> = Either::Right(10);
    /// assert_eq!(right.right_option(), Some(10));
    ///
    /// let left: Either<String, i32> = Either::Left("error".to_string());
    /// assert_eq!(left.right_option(), None);
    /// ```
    #[inline]
    pub fn right_option(self) -> Option<R> {
        self.into_iter().next()
    }

    /// Converts this `Either` to a `Result`.
    ///
    /// `Either::Left(L)` becomes `Result::Err(L)` and `Either::Right(R)` becomes `Result::Ok(R)`.
    /// Consumes `self`.
    ///
    /// # Usage
    ///
    /// Use this to bridge `Either` with Rust's standard `Result` type, especially
    /// when `Either` is used to represent a computation that can fail (where `Left`
    /// typically holds an error type) and you want to leverage `Result`'s error
    /// handling mechanisms (e.g., the `?` operator).
    ///
    /// ```
    /// # use rustica::datatypes::either::Either;
    /// let right_either: Either<String, i32> = Either::Right(100);
    /// assert_eq!(right_either.to_result(), Ok(100));
    ///
    /// let left_either: Either<String, i32> = Either::Left("failed".to_string());
    /// assert_eq!(left_either.to_result(), Err("failed".to_string()));
    /// ```
    #[inline]
    pub fn to_result(self) -> Result<R, L> {
        crate::error::either_to_result(self)
    }

    /// Creates an `Either` from a `Result`.
    ///
    /// `Result::Err(L)` becomes `Either::Left(L)` and `Result::Ok(R)` becomes `Either::Right(R)`.
    ///
    /// # Usage
    ///
    /// Use this to convert a standard `Result` into an `Either`. This is useful
    /// when interfacing with functions that return `Result` but you want to work
    /// with `Either`'s more general two-possibility semantics without the inherent
    /// success/failure implication of `Result`.
    ///
    /// ```
    /// # use rustica::datatypes::either::Either;
    /// let ok_result: Result<i32, String> = Ok(100);
    /// assert_eq!(Either::from_result(ok_result), Either::Right(100));
    ///
    /// let err_result: Result<i32, String> = Err("oops".to_string());
    /// assert_eq!(Either::from_result(err_result), Either::Left("oops".to_string()));
    /// ```
    #[inline]
    pub fn from_result(result: Result<R, L>) -> Self {
        crate::error::result_to_either(result)
    }

    /// Returns an iterator over the left value, consuming self.
    pub fn left_iter(self) -> EitherLeftIter<L> {
        match self {
            Either::Left(l) => EitherLeftIter { left: Some(l) },
            Either::Right(_) => EitherLeftIter { left: None },
        }
    }

    /// Returns an iterator over a reference to the left value.
    pub fn left_iter_ref(&self) -> EitherLeftIterRef<'_, L> {
        match self {
            Either::Left(l) => EitherLeftIterRef { left: Some(l) },
            Either::Right(_) => EitherLeftIterRef { left: None },
        }
    }

    /// Returns an iterator over a mutable reference to the left value.
    pub fn left_iter_mut(&mut self) -> EitherLeftIterMut<'_, L> {
        match self {
            Either::Left(l) => EitherLeftIterMut { left: Some(l) },
            Either::Right(_) => EitherLeftIterMut { left: None },
        }
    }

    /// Returns the contained `Left` value as an Option.
    ///
    /// Returns `Some(L)` for `Left(L)` values and `None` for `Right(R)` values.
    /// Consumes `self`.
    ///
    /// # Usage
    ///
    /// Convert an `Either` into an `Option<L>`, discarding the `Right` value.
    /// This is useful when you only care about the `Left` case and want to treat
    /// `Right` as absence of the `Left` type.
    ///
    /// ```
    /// # use rustica::datatypes::either::Either;
    /// let left: Either<i32, String> = Either::Left(42);
    /// assert_eq!(left.left_option(), Some(42));
    ///
    /// let right: Either<i32, String> = Either::Right("ok".to_string());
    /// assert_eq!(right.left_option(), None);
    /// ```
    pub fn left_option(self) -> Option<L> {
        self.left_iter().next()
    }

    /// Returns a mutable reference to the `Left` value, panicking if not present.
    pub fn left_mut(&mut self) -> &mut L {
        self.left_iter_mut()
            .next()
            .expect("Called left_mut() on a Right value")
    }

    /// Safely extracts the left value.
    ///
    /// This is the safe alternative to `unwrap_left()` that returns
    /// a proper error type instead of panicking.
    ///
    /// # Returns
    ///
    /// * `Ok(L)` - The left value if this is `Either::Left`
    /// * `Err(EitherError::ExpectedLeft)` - If this is `Either::Right`
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::datatypes::either::Either;
    /// use rustica::datatypes::error::EitherError;
    ///
    /// let left: Either<i32, &str> = Either::Left(42);
    /// assert_eq!(left.try_unwrap_left(), Ok(42));
    ///
    /// let right: Either<i32, &str> = Either::Right("hello");
    /// assert_eq!(right.try_unwrap_left(), Err(EitherError::ExpectedLeft));
    /// ```
    #[inline]
    pub fn try_unwrap_left(self) -> Result<L, EitherError> {
        match self {
            Either::Left(l) => Ok(l),
            Either::Right(_) => Err(EitherError::ExpectedLeft),
        }
    }

    /// Safely extracts the right value.
    ///
    /// This is the safe alternative to `unwrap_right()` and `unwrap()` that returns
    /// a proper error type instead of panicking.
    ///
    /// # Returns
    ///
    /// * `Ok(R)` - The right value if this is `Either::Right`
    /// * `Err(EitherError::ExpectedRight)` - If this is `Either::Left`
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::datatypes::either::Either;
    /// use rustica::datatypes::error::EitherError;
    ///
    /// let right: Either<&str, i32> = Either::Right(42);
    /// assert_eq!(right.try_unwrap_right(), Ok(42));
    ///
    /// let left: Either<&str, i32> = Either::Left("error");
    /// assert_eq!(left.try_unwrap_right(), Err(EitherError::ExpectedRight));
    /// ```
    #[inline]
    pub fn try_unwrap_right(self) -> Result<R, EitherError> {
        match self {
            Either::Right(r) => Ok(r),
            Either::Left(_) => Err(EitherError::ExpectedRight),
        }
    }

    /// Safely gets a reference to the left value.
    ///
    /// This is the safe alternative to `left_ref()` that returns
    /// a proper error type instead of panicking.
    ///
    /// # Returns
    ///
    /// * `Ok(&L)` - A reference to the left value if this is `Either::Left`
    /// * `Err(EitherError::ExpectedLeft)` - If this is `Either::Right`
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::datatypes::either::Either;
    /// use rustica::datatypes::error::EitherError;
    ///
    /// let left: Either<i32, &str> = Either::Left(42);
    /// assert_eq!(left.try_left_ref(), Ok(&42));
    ///
    /// let right: Either<i32, &str> = Either::Right("hello");
    /// assert_eq!(right.try_left_ref(), Err(EitherError::ExpectedLeft));
    /// ```
    #[inline]
    pub fn try_left_ref(&self) -> Result<&L, EitherError> {
        match self {
            Either::Left(l) => Ok(l),
            Either::Right(_) => Err(EitherError::ExpectedLeft),
        }
    }

    /// Safely gets a reference to the right value.
    ///
    /// This is the safe alternative to `right_ref()` that returns
    /// a proper error type instead of panicking.
    ///
    /// # Returns
    ///
    /// * `Ok(&R)` - A reference to the right value if this is `Either::Right`
    /// * `Err(EitherError::ExpectedRight)` - If this is `Either::Left`
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::datatypes::either::Either;
    /// use rustica::datatypes::error::EitherError;
    ///
    /// let right: Either<&str, i32> = Either::Right(42);
    /// assert_eq!(right.try_right_ref(), Ok(&42));
    ///
    /// let left: Either<&str, i32> = Either::Left("error");
    /// assert_eq!(left.try_right_ref(), Err(EitherError::ExpectedRight));
    /// ```
    #[inline]
    pub fn try_right_ref(&self) -> Result<&R, EitherError> {
        match self {
            Either::Right(r) => Ok(r),
            Either::Left(_) => Err(EitherError::ExpectedRight),
        }
    }
}

/// An iterator over the left value of an `Either<L, R>`.
pub struct EitherLeftIter<L> {
    left: Option<L>,
}

impl<L> Iterator for EitherLeftIter<L> {
    type Item = L;
    fn next(&mut self) -> Option<L> {
        self.left.take()
    }
}

/// An iterator over a reference to the left value of an `Either<L, R>`.
pub struct EitherLeftIterRef<'a, L> {
    left: Option<&'a L>,
}

impl<'a, L> Iterator for EitherLeftIterRef<'a, L> {
    type Item = &'a L;
    fn next(&mut self) -> Option<&'a L> {
        self.left.take()
    }
}

/// An iterator over a mutable reference to the left value of an `Either<L, R>`.
pub struct EitherLeftIterMut<'a, L> {
    left: Option<&'a mut L>,
}

impl<'a, L> Iterator for EitherLeftIterMut<'a, L> {
    type Item = &'a mut L;
    fn next(&mut self) -> Option<&'a mut L> {
        self.left.take()
    }
}

impl<L, R> HKT for Either<L, R> {
    type Source = R;
    type Output<T> = Either<L, T>;
}

impl<L: Clone, R: Clone> Functor for Either<L, R> {
    #[inline]
    fn fmap<B, F>(&self, f: F) -> Self::Output<B>
    where
        F: Fn(&Self::Source) -> B,
    {
        match self {
            Either::Left(l) => Either::Left(l.clone()),
            Either::Right(r) => Either::Right(f(r)),
        }
    }

    #[inline]
    fn fmap_owned<B, F>(self, f: F) -> Self::Output<B>
    where
        F: Fn(Self::Source) -> B,
    {
        match self {
            Either::Left(l) => Either::Left(l),
            Either::Right(r) => Either::Right(f(r)),
        }
    }
}

impl<L, R> Pure for Either<L, R> {
    #[inline]
    fn pure<T: Clone>(value: &T) -> Self::Output<T> {
        Either::Right(value.clone())
    }
}

impl<L: Clone, R: Clone> Applicative for Either<L, R> {
    fn apply<A, B>(&self, value: &Self::Output<A>) -> Self::Output<B>
    where
        Self::Source: Fn(&A) -> B,
    {
        match (self, value) {
            (Either::Right(func), Either::Right(a)) => Either::Right(func(a)),
            (Either::Left(l), _) => Either::Left(l.clone()),
            (_, Either::Left(l)) => Either::Left(l.clone()),
        }
    }

    fn lift2<A, B, C, F>(f: F, fa: &Self::Output<A>, fb: &Self::Output<B>) -> Self::Output<C>
    where
        F: Fn(&A, &B) -> C,
        A: Clone,
        B: Clone,
        C: Clone,
        Self: Sized,
    {
        match (fa, fb) {
            (Either::Right(a), Either::Right(b)) => Either::Right(f(a, b)),
            (Either::Left(l), _) => Either::Left(l.clone()),
            (_, Either::Left(l)) => Either::Left(l.clone()),
        }
    }

    fn lift3<A, B, C, D, F>(
        f: F, fa: &Self::Output<A>, fb: &Self::Output<B>, fc: &Self::Output<C>,
    ) -> Self::Output<D>
    where
        F: Fn(&A, &B, &C) -> D,
        A: Clone,
        B: Clone,
        C: Clone,
        D: Clone,
        Self: Sized,
    {
        match (fa, fb, fc) {
            (Either::Right(a), Either::Right(b), Either::Right(c)) => Either::Right(f(a, b, c)),
            (Either::Left(l), _, _) => Either::Left(l.clone()),
            (_, Either::Left(l), _) => Either::Left(l.clone()),
            (_, _, Either::Left(l)) => Either::Left(l.clone()),
        }
    }

    fn apply_owned<T, B>(self, value: Self::Output<T>) -> Self::Output<B>
    where
        Self::Source: Fn(T) -> B,
        T: Clone,
        B: Clone,
    {
        match (self, value) {
            (Either::Right(f), Either::Right(x)) => Either::Right(f(x)),
            (Either::Left(l), _) => Either::Left(l),
            (_, Either::Left(l)) => Either::Left(l),
        }
    }

    fn lift2_owned<T, U, V, F>(f: F, fa: Self::Output<T>, fb: Self::Output<U>) -> Self::Output<V>
    where
        F: Fn(T, U) -> V,
        T: Clone,
        U: Clone,
        V: Clone,
        Self: Sized,
    {
        match (fa, fb) {
            (Either::Right(x), Either::Right(y)) => Either::Right(f(x, y)),
            (Either::Left(l), _) => Either::Left(l),
            (_, Either::Left(l)) => Either::Left(l),
        }
    }

    fn lift3_owned<T, U, V, Q, F>(
        f: F, fa: Self::Output<T>, fb: Self::Output<U>, fc: Self::Output<V>,
    ) -> Self::Output<Q>
    where
        F: Fn(T, U, V) -> Q,
        T: Clone,
        U: Clone,
        V: Clone,
        Q: Clone,
        Self: Sized,
    {
        match (fa, fb, fc) {
            (Either::Right(x), Either::Right(y), Either::Right(z)) => Either::Right(f(x, y, z)),
            (Either::Left(l), _, _) => Either::Left(l),
            (_, Either::Left(l), _) => Either::Left(l),
            (_, _, Either::Left(l)) => Either::Left(l),
        }
    }
}

impl<L: Clone, R: Clone> Monad for Either<L, R> {
    #[inline]
    fn bind<B, F>(&self, f: F) -> Self::Output<B>
    where
        F: Fn(&Self::Source) -> Self::Output<B>,
    {
        match self {
            Either::Left(l) => Either::Left(l.clone()),
            Either::Right(r) => f(r),
        }
    }

    #[inline]
    fn join<B>(&self) -> Self::Output<B>
    where
        Self::Source: Into<Self::Output<B>>,
    {
        match self {
            Either::Left(l) => Either::Left(l.clone()),
            Either::Right(r) => r.clone().into(),
        }
    }

    #[inline]
    fn bind_owned<U, F>(self, f: F) -> Self::Output<U>
    where
        F: FnOnce(Self::Source) -> Self::Output<U>,
        Self: Sized,
    {
        match self {
            Either::Left(l) => Either::Left(l),
            Either::Right(r) => f(r),
        }
    }

    #[inline]
    fn join_owned<U>(self) -> Self::Output<U>
    where
        Self::Source: Into<Self::Output<U>>,
        Self: Sized,
    {
        match self {
            Either::Left(l) => Either::Left(l),
            Either::Right(r) => r.into(),
        }
    }
}

impl<L, R> BinaryHKT for Either<L, R> {
    type Source2 = L;
    type BinaryOutput<NewR, NewL> = Either<NewL, NewR>;

    fn map_second<F, NewL>(&self, f: F) -> Either<NewL, R>
    where
        F: Fn(&L) -> NewL,
        R: Clone,
    {
        match self {
            Either::Left(l) => Either::Left(f(l)),
            Either::Right(r) => Either::Right(r.clone()),
        }
    }

    fn map_second_owned<F, NewL>(self, f: F) -> Either<NewL, R>
    where
        F: Fn(L) -> NewL,
    {
        match self {
            Either::Left(l) => Either::Left(f(l)),
            Either::Right(r) => Either::Right(r),
        }
    }
}

impl<L: Clone, R: Clone> Bifunctor for Either<L, R> {
    fn first<C, F>(&self, f: F) -> Self::BinaryOutput<C, Self::Source2>
    where
        F: Fn(&Self::Source) -> C,
        C: Clone,
    {
        match self {
            Either::Left(l) => Either::Left(l.clone()),
            Either::Right(r) => Either::Right(f(r)),
        }
    }

    fn second<D, G>(&self, g: G) -> Self::BinaryOutput<Self::Source, D>
    where
        G: Fn(&Self::Source2) -> D,
        D: Clone,
    {
        match self {
            Either::Left(l) => Either::Left(g(l)),
            Either::Right(r) => Either::Right(r.clone()),
        }
    }

    fn bimap<C, D, F, G>(&self, f: F, g: G) -> Self::BinaryOutput<C, D>
    where
        F: Fn(&Self::Source) -> C,
        G: Fn(&Self::Source2) -> D,
        C: Clone,
        D: Clone,
    {
        match self {
            Either::Left(l) => Either::Left(g(l)),
            Either::Right(r) => Either::Right(f(r)),
        }
    }
}

/// Implementation of `Alternative` for `Either`, which provides choice between alternatives.
///
/// # Type Parameters
///
/// * `L`: The left type, which must implement `Default + Clone`. The `Default` requirement is needed
///   to create empty/failure values using `L::default()`.
/// * `R`: The right type, which must implement `Clone` for all operations.
///
/// # Implementation Notes
///
/// - `empty_alt<B>()` returns `Either::Left(L::default())`, representing a failure or empty value.
/// - `alt` chooses between two `Either` values, preferring `Right` values over `Left` values.
///
/// # Examples
///
/// ```rust
/// use rustica::datatypes::either::Either;
/// use rustica::traits::alternative::Alternative;
///
/// // Empty produces a Left with the default value
/// let empty = Either::<String, i32>::empty_alt::<i32>(); // Either::Left(String::default())
///
/// // Alt prefers Right values (success) over Left values (failure)
/// let a: Either<String, i32> = Either::right(42);
/// let b: Either<String, i32> = Either::left("error".to_string());
/// assert_eq!(a.alt(&b), Either::right(42)); // First Right wins
/// assert_eq!(b.alt(&a), Either::right(42)); // Prefers Right over Left
/// ```
impl<L: Default + Clone, R: Clone> Alternative for Either<L, R> {
    /// Returns an empty element of the `Alternative` instance as `Either::Left(L::default())`.
    ///
    /// # Type Parameters
    ///
    /// * `B`: The right type of the resulting `Either` (can differ from `R`)
    ///
    /// # Requirements
    ///
    /// Requires `L: Default` to create the default value for the `Left` variant.
    #[inline]
    fn empty_alt<B>() -> Self::Output<B> {
        Either::Left(L::default())
    }

    /// Chooses between two `Either` values, preferring `Right` values over `Left` values.
    /// If `self` is `Right`, it is returned; otherwise, `other` is returned.
    #[inline]
    fn alt(&self, other: &Self) -> Self {
        match self {
            Either::Right(_) => self.clone(),
            Either::Left(_) => other.clone(),
        }
    }

    /// Creates an `Either` based on a boolean condition.
    /// Returns `Either::Right(())` if the condition is true, otherwise returns `Either::Left(L::default())`.
    ///
    /// # Requirements
    ///
    /// Requires `L: Default` to create the default value for the `Left` variant when the condition is false.
    fn guard(condition: bool) -> Self::Output<()> {
        if condition {
            Either::Right(())
        } else {
            Either::Left(L::default())
        }
    }

    /// Converts a single value to a collection containing that value.
    /// Returns `Either::Right(vec![x])` if `self` is `Right(x)`,
    /// otherwise returns `Either::Left(L::default())` if `self` is `Left`.
    ///
    /// # Requirements
    ///
    /// Requires `L: Default` to create the default value for the `Left` variant.
    /// Requires `R: Clone` to clone the value for the vector.
    #[inline]
    fn many(&self) -> Self::Output<Vec<Self::Source>>
    where
        Self::Source: Clone,
    {
        match self {
            Either::Right(x) => Either::Right(vec![x.clone()]),
            Either::Left(_) => Either::Left(L::default()),
        }
    }
}

// Iterator support for Either
/// An iterator over the right value of an `Either<L, R>`.
pub struct EitherIter<R> {
    inner: Option<R>,
}

impl<L, R> IntoIterator for Either<L, R> {
    type Item = R;
    type IntoIter = EitherIter<R>;
    /// Converts the `Either` into an iterator over the right value.
    ///
    /// If the value is `Right`, yields the contained value. If `Left`, yields nothing.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::datatypes::either::Either;
    /// let e: Either<&str, i32> = Either::right(42);
    /// let v: Vec<_> = e.into_iter().collect();
    /// assert_eq!(v, vec![42]);
    /// let e: Either<&str, i32> = Either::left("err");
    /// let v: Vec<_> = e.into_iter().collect();
    /// assert!(v.is_empty());
    /// ```
    fn into_iter(self) -> Self::IntoIter {
        match self {
            Either::Right(r) => EitherIter { inner: Some(r) },
            Either::Left(_) => EitherIter { inner: None },
        }
    }
}

impl<R> Iterator for EitherIter<R> {
    type Item = R;
    fn next(&mut self) -> Option<R> {
        self.inner.take()
    }
}

/// An iterator over a reference to the right value of an `Either<L, R>`.
pub struct EitherIterRef<'a, R> {
    inner: Option<&'a R>,
}

impl<'a, L, R> IntoIterator for &'a Either<L, R> {
    type Item = &'a R;
    type IntoIter = EitherIterRef<'a, R>;
    /// Converts a reference to `Either` into an iterator over a reference to the right value.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::datatypes::either::Either;
    /// let e: Either<&str, i32> = Either::right(42);
    /// let v: Vec<_> = (&e).into_iter().collect();
    /// assert_eq!(v, vec![&42]);
    /// let e: Either<&str, i32> = Either::left("err");
    /// let v: Vec<_> = (&e).into_iter().collect::<Vec<_>>();
    /// assert!(v.is_empty());
    /// ```
    fn into_iter(self) -> Self::IntoIter {
        match self {
            Either::Right(r) => EitherIterRef { inner: Some(r) },
            Either::Left(_) => EitherIterRef { inner: None },
        }
    }
}

impl<'a, R> Iterator for EitherIterRef<'a, R> {
    type Item = &'a R;
    fn next(&mut self) -> Option<&'a R> {
        self.inner.take()
    }
}

/// An iterator over a mutable reference to the right value of an `Either<L, R>`.
pub struct EitherIterMut<'a, R> {
    inner: Option<&'a mut R>,
}

impl<'a, L, R> IntoIterator for &'a mut Either<L, R> {
    type Item = &'a mut R;
    type IntoIter = EitherIterMut<'a, R>;
    /// Converts a mutable reference to `Either` into an iterator over a mutable reference to the right value.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::datatypes::either::Either;
    /// let mut e: Either<&str, i32> = Either::right(42);
    /// for v in &mut e {
    ///     *v += 1;
    /// }
    /// assert_eq!(e, Either::right(43));
    /// ```
    fn into_iter(self) -> Self::IntoIter {
        match self {
            Either::Right(r) => EitherIterMut { inner: Some(r) },
            Either::Left(_) => EitherIterMut { inner: None },
        }
    }
}

impl<'a, R> Iterator for EitherIterMut<'a, R> {
    type Item = &'a mut R;
    fn next(&mut self) -> Option<&'a mut R> {
        self.inner.take()
    }
}

impl<L, R> Arbitrary for Either<L, R>
where
    L: Arbitrary,
    R: Arbitrary,
{
    fn arbitrary(g: &mut Gen) -> Self {
        let left = L::arbitrary(g);
        let right = R::arbitrary(g);
        if bool::arbitrary(g) {
            Either::Left(left)
        } else {
            Either::Right(right)
        }
    }
}