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
//! # Applicative Functors
//!
//! Applicative functors are a concept from category theory that provide a way
//! to apply functions inside a functor context. They sit between functors and monads
//! in the hierarchy of abstractions:
//!
//! ```text
//! Functor -> Applicative -> Monad
//! ```
//!
//! An applicative functor extends a regular functor with the ability to:
//! - Lift a value into the functor context (`pure`)
//! - Apply a function in a context to a value in a context (`apply`)
//!
//! ## Mathematical Definition
//!
//! Applicative functors are functors with additional structure:
//! - `pure`: A -> F A
//! - `apply`: F (A -> B) -> F A -> F B
//!
//! ## Laws
//!
//! For a valid Applicative implementation, the following laws must hold:
//!
//! 1. Identity:
//! ```text
//!    pure(id).apply(v) == v
//! ```
//!
//! 2. Homomorphism:
//! ```text
//!    pure(f).apply(pure(x)) == pure(f(x))
//! ```
//!
//! 3. Interchange:
//! ```text
//!    u.apply(pure(y)) == pure(|f| f(y)).apply(u)
//! ```
//!
//! 4. Composition:
//! ```text
//!    pure(compose).apply(u).apply(v).apply(w) == u.apply(v.apply(w))
//! ```
//!
//! ## Practical Use Cases
//!
//! ### 1. Combining Independent Computations
//!
//! Applicative functors excel at combining independent computations that share a context:
//!
//! ```rust
//! use rustica::traits::applicative::Applicative;
//! use rustica::traits::pure::Pure;
//! use rustica::datatypes::validated::Validated;
//!
//! // Two independent validations
//! let v1: Validated<String, i32> = Validated::valid(5);
//! let v2: Validated<String, i32> = Validated::valid(10);
//!
//! // Combine them with a function
//! let result = Validated::<String, i32>::lift2(|a: &i32, b: &i32| *a + *b, &v1, &v2);
//! ```
//!
//! ### 2. Sequencing Operations
//!
//! Applicatives allow sequencing operations while preserving the context:
//!
//! ```rust
//! use rustica::traits::applicative::Applicative;
//! use rustica::traits::pure::Pure;
//!
//! // Operations that return Option<T>
//! let step1: Option<i32> = Some(10);
//! let step2: Option<i32> = Some(20);
//!
//! // Keep only the result of step2, but both must succeed
//! let result: Option<i32> = Option::<i32>::sequence_right(&step1, &step2);
//! ```
//!
//! ## Relationship to Other Traits
//!
//! - **Functor**: Every Applicative is a Functor. Applicatives can do everything
//!   Functors can, plus more.
//!
//! - **Monad**: Monads are more powerful than Applicatives. Every Monad is an
//!   Applicative, but not every Applicative is a Monad. Applicatives can combine
//!   independent effects, while Monads can sequence dependent effects.
//!
//! ## When to Use Applicative vs Monad
//!
//! - Use **Applicative** when operations are independent of each other and
//!   can be performed in any order, but share a common context.
//!
//! - Use **Monad** when operations depend on the results of previous operations.
//!
use crate::traits::functor::Functor;
use crate::traits::pure::Pure;

/// A trait for applicative functors, which allow function application within a context.
///
/// Applicative functors extend regular functors by providing:
/// 1. Lifting of pure values into the context (via `Pure`)
/// 2. Application of functions that are themselves wrapped in the context (`apply`)
/// 3. Sequential combination of multiple wrapped values (`lift2`, `lift3`)
///
/// ## Mathematical Definition
///
/// Applicative functors are functors with additional structure:
/// - `pure`: A -> F\<A\> (provided by the `Pure` trait)
/// - `apply`: F\<A -> B\> -> F\<A\> -> F\<B\> (the fundamental operation)
///
/// ## Laws
///
/// For a valid Applicative implementation, the following laws must hold:
///
/// ### 1. Identity Law
/// ```text
/// pure(id).apply(v) ≡ v
/// ```
/// Applying the identity function wrapped in the context should be equivalent to the original value.
///
/// ### 2. Homomorphism Law
/// ```text
/// pure(f).apply(pure(x)) ≡ pure(f(x))
/// ```
/// Applying a pure function to a pure value should be equivalent to applying the function directly and then wrapping the result.
///
/// ### 3. Interchange Law
/// ```text
/// u.apply(pure(y)) ≡ pure(|f| f(y)).apply(u)
/// ```
/// The order of evaluation doesn't matter when one operand is pure.
///
/// ### 4. Composition Law
/// ```text
/// pure(compose).apply(u).apply(v).apply(w) ≡ u.apply(v.apply(w))
/// ```
/// Function composition should be associative.
///
/// ## Examples
///
/// ### Basic Usage
/// ```rust
/// use rustica::traits::applicative::Applicative;
/// use rustica::traits::pure::Pure;
///
/// // Apply a function in context to a value in context
/// let func: Option<fn(&i32) -> i32> = Some(|x: &i32| *x * 2);
/// let value: Option<i32> = Some(5);
///
/// let result = Applicative::apply(&func, &value);
/// assert_eq!(result, Some(10));
/// ```
///
/// ### Combining Multiple Values
/// ```rust
/// use rustica::traits::applicative::Applicative;
/// use rustica::traits::pure::Pure;
///
/// let x: Option<i32> = Some(2);
/// let y: Option<i32> = Some(3);
/// let z: Option<i32> = Some(4);
///
/// // Function-first style (mathematical convention)
/// let result = Option::<i32>::lift2(|a: &i32, b: &i32| *a + *b, &x, &y);
/// assert_eq!(result, Some(5));
///
/// let result3 = Option::<i32>::lift3(|a: &i32, b: &i32, c: &i32| *a + *b + *c, &x, &y, &z);
/// assert_eq!(result3, Some(9));
/// ```
///
/// ### Validation Example
/// ```rust
/// use rustica::traits::applicative::Applicative;
/// use rustica::traits::pure::Pure;
/// use rustica::datatypes::validated::Validated;
///
/// let name: Validated<String, &str> = Validated::valid("John");
/// let age: Validated<String, i32> = Validated::valid(30);
///
/// // Combine validations - all must succeed
/// let user = Validated::<String, String>::lift2(
///     |n: &&str, a: &i32| format!("User: {}, Age: {}", n, a),
///     &name,
///     &age
/// );
/// assert!(matches!(user, Validated::Valid(_)));
/// ```
pub trait Applicative: Functor + Pure {
    /// Applies a function wrapped in the applicative context to a value.
    ///
    /// This is the fundamental operation of Applicative functors, with signature:
    /// `F\<A -> B\> -> F\<A\> -> F\<B\>`
    ///
    /// The function is contained within `self` (the applicative context), and is applied
    /// to the value contained within the `value` parameter.
    ///
    /// # Type Parameters
    ///
    /// * `T`: The input type of the value being transformed
    /// * `B`: The result type after applying the function
    ///
    /// # Arguments
    ///
    /// * `value`: A reference to the applicative containing the value to transform
    ///
    /// # Returns
    ///
    /// An applicative containing the result of applying the function to the value
    ///
    /// # Laws
    ///
    /// This method must satisfy the applicative laws:
    /// - Identity: `pure(id).apply(v) ≡ v`
    /// - Homomorphism: `pure(f).apply(pure(x)) ≡ pure(f(x))`
    /// - Interchange: `u.apply(pure(y)) ≡ pure(|f| f(y)).apply(u)`
    /// - Composition: `pure(compose).apply(u).apply(v).apply(w) ≡ u.apply(v.apply(w))`
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::traits::applicative::Applicative;
    /// use rustica::traits::pure::Pure;
    ///
    /// // Function wrapped in Option
    /// let func: Option<fn(&i32) -> i32> = Some(|x: &i32| *x * 2);
    /// let value: Option<i32> = Some(5);
    ///
    /// let result = Applicative::apply(&func, &value);
    /// assert_eq!(result, Some(10));
    ///
    /// // If either is None, result is None
    /// let none_func: Option<fn(&i32) -> i32> = None;
    /// let result2 = Applicative::apply(&none_func, &value);
    /// assert_eq!(result2, None);
    /// ```
    fn apply<T, B>(&self, value: &Self::Output<T>) -> Self::Output<B>
    where
        Self::Source: Fn(&T) -> B,
        B: Clone;

    /// Lifts a binary function to work with two applicative values.
    ///
    /// This method follows the mathematical convention where the function comes first,
    /// matching the curried style used in functional programming languages like Haskell.
    /// It combines two applicative values using a binary function.
    ///
    /// # Type Parameters
    ///
    /// * `A`: The type of the first applicative value
    /// * `B`: The type of the second applicative value  
    /// * `C`: The result type after applying the function
    /// * `F`: The function type that transforms references to `A` and `B` into `C`
    ///
    /// # Arguments
    ///
    /// * `f`: A function to apply to both values (function-first, curried style)
    /// * `fa`: A reference to the first applicative value
    /// * `fb`: A reference to the second applicative value
    ///
    /// # Returns
    ///
    /// An applicative containing the result of applying the function to both values
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::traits::applicative::Applicative;
    /// use rustica::traits::pure::Pure;
    ///
    /// let x: Option<i32> = Some(5);
    /// let y: Option<i32> = Some(3);
    ///
    /// // Function-first style (mathematical convention)
    /// let result: Option<i32> = Option::<i32>::lift2(|a: &i32, b: &i32| *a + *b, &x, &y);
    /// assert_eq!(result, Some(8));
    ///
    /// // If any value is None, the result is None
    /// let none_x: Option<i32> = None;
    /// let result2: Option<i32> = Option::<i32>::lift2(|a: &i32, b: &i32| *a + *b, &none_x, &y);
    /// assert_eq!(result2, None);
    /// ```
    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;

    /// Lifts a ternary function to work with three applicative values.
    ///
    /// This method follows the mathematical convention where the function comes first,
    /// matching the curried style used in functional programming languages like Haskell.
    /// It combines three applicative values using a ternary function.
    ///
    /// # Type Parameters
    ///
    /// * `A`: The type of the first applicative value
    /// * `B`: The type of the second applicative value
    /// * `C`: The type of the third applicative value
    /// * `D`: The result type after applying the function
    /// * `F`: The function type that transforms references to `A`, `B`, and `C` into `D`
    ///
    /// # Arguments
    ///
    /// * `f`: A function to apply to all three values (function-first, curried style)
    /// * `fa`: A reference to the first applicative value
    /// * `fb`: A reference to the second applicative value
    /// * `fc`: A reference to the third applicative value
    ///
    /// # Returns
    ///
    /// An applicative containing the result of applying the function to all three values
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::traits::applicative::Applicative;
    /// use rustica::traits::pure::Pure;
    ///
    /// let x: Option<i32> = Some(2);
    /// let y: Option<i32> = Some(3);
    /// let z: Option<i32> = Some(5);
    ///
    /// // Function-first style (mathematical convention)
    /// let result: Option<i32> = Option::<i32>::lift3(
    ///     |a: &i32, b: &i32, c: &i32| *a + *b + *c,
    ///     &x, &y, &z
    /// );
    /// assert_eq!(result, Some(10));
    /// ```
    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;

    /// Sequences two applicative actions, discarding the left value and keeping the right.
    ///
    /// This method applies two applicative actions in sequence, discarding the result
    /// of the first action and keeping only the result of the second action.
    /// Equivalent to `*>` in Haskell.
    ///
    /// # Type Parameters
    ///
    /// * `A`: The type of the first applicative value
    /// * `B`: The type of the second applicative value
    ///
    /// # Arguments
    ///
    /// * `fa`: A reference to the first applicative value
    /// * `fb`: A reference to the second applicative value
    ///
    /// # Returns
    ///
    /// An applicative containing the value from `fb`
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::traits::applicative::Applicative;
    ///
    /// let x: Option<i32> = Some(1);
    /// let y: Option<i32> = Some(2);
    ///
    /// let result: Option<i32> = Option::<i32>::sequence_right(&x, &y);
    /// assert_eq!(result, Some(2));
    ///
    /// // If either fails, the whole operation fails
    /// let none_x: Option<i32> = None;
    /// let result2: Option<i32> = Option::<i32>::sequence_right(&none_x, &y);
    /// assert_eq!(result2, None);
    /// ```
    #[inline]
    fn sequence_right<A, B>(fa: &Self::Output<A>, fb: &Self::Output<B>) -> Self::Output<B>
    where
        A: Clone,
        B: Clone,
    {
        Self::lift2(|_, b| b.clone(), fa, fb)
    }

    /// Sequences two applicative actions, keeping the left value and discarding the right.
    ///
    /// This method applies two applicative actions in sequence, keeping the result
    /// of the first action and discarding the result of the second action.
    /// Equivalent to `<*` in Haskell.
    ///
    /// # Type Parameters
    ///
    /// * `A`: The type of the first applicative value
    /// * `B`: The type of the second applicative value
    ///
    /// # Arguments
    ///
    /// * `fa`: A reference to the first applicative value
    /// * `fb`: A reference to the second applicative value
    ///
    /// # Returns
    ///
    /// An applicative containing the value from `fa`
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::traits::applicative::Applicative;
    ///
    /// let x: Option<i32> = Some(1);
    /// let y: Option<i32> = Some(2);
    ///
    /// let result: Option<i32> = Option::<i32>::sequence_left(&x, &y);
    /// assert_eq!(result, Some(1));
    ///
    /// // If either fails, the whole operation fails
    /// let none_y: Option<i32> = None;
    /// let result2: Option<i32> = Option::<i32>::sequence_left(&x, &none_y);
    /// assert_eq!(result2, None);
    /// ```
    #[inline]
    fn sequence_left<A, B>(fa: &Self::Output<A>, fb: &Self::Output<B>) -> Self::Output<A>
    where
        A: Clone,
        B: Clone,
    {
        Self::lift2(|a, _| a.clone(), fa, fb)
    }

    /// Applies a binary function to two applicative values.
    ///
    /// This is an alias for `lift2` that may be more intuitive in some contexts.
    /// It follows the same function-first convention as `lift2`.
    ///
    /// # Type Parameters
    ///
    /// * `A`: The type of the first applicative value
    /// * `B`: The type of the second applicative value
    /// * `C`: The result type after applying the function
    /// * `F`: The function type that transforms references to `A` and `B` into `C`
    ///
    /// # Arguments
    ///
    /// * `f`: A function to apply to both values (function-first style)
    /// * `fa`: A reference to the first applicative value
    /// * `fb`: A reference to the second applicative value
    ///
    /// # Returns
    ///
    /// An applicative containing the result of applying the function to both values
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::traits::applicative::Applicative;
    /// use rustica::traits::pure::Pure;
    /// use rustica::datatypes::validated::Validated;
    ///
    /// let v1: Validated<String, i32> = Validated::valid(5);
    /// let v2: Validated<String, i32> = Validated::valid(3);
    ///
    /// let result: Validated<String, i32> = Validated::<String, i32>::ap2(|a: &i32, b: &i32| *a * *b, &v1, &v2);
    /// assert!(matches!(result, Validated::Valid(15)));
    /// ```
    #[inline]
    fn ap2<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::lift2(f, fa, fb)
    }

    /// Applies a function to a value, with both wrapped in an applicative context, taking
    /// ownership of both values.
    ///
    /// This is an ownership-based version of `apply` that avoids unnecessary cloning
    /// when the applicative values are no longer needed. The signature matches the
    /// mathematical definition: F\<A -> B\> -> F\<A\> -> F\<B\>.
    ///
    /// # Type Parameters
    ///
    /// * `T`: The input type of the value being transformed
    /// * `B`: The result type after applying the function
    ///
    /// # Arguments
    ///
    /// * `value`: An applicative containing the value to transform (takes ownership)
    ///
    /// # Returns
    ///
    /// An applicative containing the result of applying the function to the value
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::traits::applicative::Applicative;
    /// use rustica::traits::pure::Pure;
    ///
    /// let func: Option<fn(i32) -> i32> = Some(|x| x * 2);
    /// let value: Option<i32> = Some(5);
    ///
    /// let result = Applicative::apply_owned(func, value);
    /// assert_eq!(result, Some(10));
    /// ```
    fn apply_owned<T, B>(self, value: Self::Output<T>) -> Self::Output<B>
    where
        Self::Source: Fn(T) -> B,
        T: Clone,
        B: Clone;

    /// Lifts a binary function to work with two applicative values, taking
    /// ownership of both values.
    ///
    /// This is an ownership-based version of `lift2` that avoids unnecessary cloning
    /// when the applicative values are no longer needed. It follows the same
    /// function-first convention as `lift2`.
    ///
    /// # Type Parameters
    ///
    /// * `A`: The type of the first applicative value
    /// * `B`: The type of the second applicative value
    /// * `C`: The result type after applying the function
    /// * `F`: The function type that transforms `A` and `B` into `C`
    ///
    /// # Arguments
    ///
    /// * `f`: A function to apply to both values (function-first style)
    /// * `fa`: First applicative value (takes ownership)
    /// * `fb`: Second applicative value (takes ownership)
    ///
    /// # Returns
    ///
    /// An applicative containing the result of applying the function to both values
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::traits::applicative::Applicative;
    /// use rustica::traits::pure::Pure;
    ///
    /// let x: Option<i32> = Some(5);
    /// let y: Option<i32> = Some(3);
    ///
    /// let result: Option<i32> = Option::<i32>::lift2_owned(|a, b| a + b, x, y);
    /// assert_eq!(result, Some(8));
    /// ```
    fn lift2_owned<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;

    /// Lifts a ternary function to work with three applicative values, taking
    /// ownership of all values.
    ///
    /// This is an ownership-based version of `lift3` that avoids unnecessary cloning
    /// when the applicative values are no longer needed. It follows the same
    /// function-first convention as `lift3`.
    ///
    /// # Type Parameters
    ///
    /// * `A`: The type of the first applicative value
    /// * `B`: The type of the second applicative value
    /// * `C`: The type of the third applicative value
    /// * `D`: The result type after applying the function
    /// * `F`: The function type that transforms `A`, `B`, and `C` into `D`
    ///
    /// # Arguments
    ///
    /// * `f`: A function to apply to all three values (function-first style)
    /// * `fa`: First applicative value (takes ownership)
    /// * `fb`: Second applicative value (takes ownership)
    /// * `fc`: Third applicative value (takes ownership)
    ///
    /// # Returns
    ///
    /// An applicative containing the result of applying the function to all three values
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::traits::applicative::Applicative;
    /// use rustica::traits::pure::Pure;
    ///
    /// let x: Option<i32> = Some(2);
    /// let y: Option<i32> = Some(3);
    /// let z: Option<i32> = Some(4);
    ///
    /// let result: Option<i32> = Option::<i32>::lift3_owned(|a, b, c| a + b + c, x, y, z);
    /// assert_eq!(result, Some(9));
    /// ```
    fn lift3_owned<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;

    /// Sequences two applicative actions, keeping only the result of the right one
    /// (discarding the left result).
    ///
    /// This is an ownership-based version of `sequence_right` that avoids unnecessary cloning
    /// when the applicative values are no longer needed.
    ///
    /// # Type Parameters
    ///
    /// * `A`: The type of the first applicative value
    /// * `B`: The type of the second applicative value
    ///
    /// # Arguments
    ///
    /// * `fa`: The first applicative value (takes ownership)
    /// * `fb`: The second applicative value (takes ownership)
    ///
    /// # Returns
    ///
    /// An applicative containing the value from `fb`
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::traits::applicative::Applicative;
    ///
    /// let x: Option<i32> = Some(1);
    /// let y: Option<i32> = Some(2);
    ///
    /// let result: Option<i32> = Option::<i32>::sequence_right_owned(x, y);
    /// assert_eq!(result, Some(2));
    /// ```
    #[inline]
    fn sequence_right_owned<A, B>(fa: Self::Output<A>, fb: Self::Output<B>) -> Self::Output<B>
    where
        A: Clone,
        B: Clone,
    {
        Self::lift2_owned(|_, b| b, fa, fb)
    }

    /// Sequences two applicative actions, keeping only the result of the left one
    /// (discarding the right result).
    ///
    /// This is an ownership-based version of `sequence_left` that avoids unnecessary cloning
    /// when the applicative values are no longer needed.
    ///
    /// # Type Parameters
    ///
    /// * `A`: The type of the first applicative value
    /// * `B`: The type of the second applicative value
    ///
    /// # Arguments
    ///
    /// * `fa`: The first applicative value (takes ownership)
    /// * `fb`: The second applicative value (takes ownership)
    ///
    /// # Returns
    ///
    /// An applicative containing the value from `fa`
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::traits::applicative::Applicative;
    ///
    /// let x: Option<i32> = Some(1);
    /// let y: Option<i32> = Some(2);
    ///
    /// let result: Option<i32> = Option::<i32>::sequence_left_owned(x, y);
    /// assert_eq!(result, Some(1));
    /// ```
    #[inline]
    fn sequence_left_owned<A, B>(fa: Self::Output<A>, fb: Self::Output<B>) -> Self::Output<A>
    where
        A: Clone,
        B: Clone,
    {
        Self::lift2_owned(|a, _| a, fa, fb)
    }
}

// Implementation for Option
impl<A> Applicative for Option<A> {
    #[inline]
    fn apply<T, B>(&self, value: &Self::Output<T>) -> Self::Output<B>
    where
        Self::Source: Fn(&T) -> B,
        B: Clone,
    {
        match (self, value) {
            (Some(func), Some(a)) => Some(func(a)),
            _ => None,
        }
    }

    #[inline]
    fn lift2<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) {
            (Some(a), Some(b)) => Some(f(a, b)),
            _ => None,
        }
    }

    #[inline]
    fn lift3<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) {
            (Some(a), Some(b), Some(c)) => Some(f(a, b, c)),
            _ => None,
        }
    }

    #[inline]
    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) {
            (Some(func), Some(a)) => Some(func(a)),
            _ => None,
        }
    }

    #[inline]
    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) {
            (Some(a), Some(b)) => Some(f(a, b)),
            _ => None,
        }
    }

    #[inline]
    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) {
            (Some(a), Some(b), Some(c)) => Some(f(a, b, c)),
            _ => None,
        }
    }
}

// Implementation for Result
impl<A: Clone, E: std::fmt::Debug + Clone> Applicative for Result<A, E> {
    #[inline]
    fn apply<T, B>(&self, value: &Self::Output<T>) -> Self::Output<B>
    where
        Self::Source: Fn(&T) -> B,
        B: Clone,
    {
        match (self, value) {
            (Ok(func), Ok(a)) => Ok(func(a)),
            (Err(e), _) => Err(e.clone()),
            (_, Err(e)) => Err(e.clone()),
        }
    }

    #[inline]
    fn lift2<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) {
            (Ok(a), Ok(b)) => Ok(f(a, b)),
            (Err(e), _) => Err(e.clone()),
            (_, Err(e)) => Err(e.clone()),
        }
    }

    #[inline]
    fn lift3<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) {
            (Ok(a), Ok(b), Ok(c)) => Ok(f(a, b, c)),
            (Err(e), _, _) => Err(e.clone()),
            (_, Err(e), _) => Err(e.clone()),
            (_, _, Err(e)) => Err(e.clone()),
        }
    }

    #[inline]
    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) {
            (Ok(func), Ok(a)) => Ok(func(a)),
            (Err(e), _) => Err(e),
            (_, Err(e)) => Err(e),
        }
    }

    #[inline]
    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) {
            (Ok(a), Ok(b)) => Ok(f(a, b)),
            (Err(e), _) => Err(e),
            (_, Err(e)) => Err(e),
        }
    }

    #[inline]
    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) {
            (Ok(a), Ok(b), Ok(c)) => Ok(f(a, b, c)),
            (Err(e), _, _) => Err(e),
            (_, Err(e), _) => Err(e),
            (_, _, Err(e)) => Err(e),
        }
    }
}

// Implementation for Vec
impl<A: Clone> Applicative for Vec<A> {
    #[inline]
    fn apply<T, B>(&self, value: &Self::Output<T>) -> Self::Output<B>
    where
        Self::Source: Fn(&T) -> B,
        B: Clone,
    {
        let mut result = Vec::new();
        for func in self {
            for val in value {
                result.push(func(val));
            }
        }
        result
    }

    #[inline]
    fn lift2<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,
    {
        let mut result = Vec::with_capacity(fa.len() * fb.len());
        for a in fa {
            for b in fb {
                result.push(f(a, b));
            }
        }
        result
    }

    #[inline]
    fn lift3<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,
    {
        let mut result = Vec::with_capacity(fa.len() * fb.len() * fc.len());
        for ((a, b), c) in fa
            .iter()
            .flat_map(|a| fb.iter().map(move |b| (a, b)))
            .flat_map(|(a, b)| fc.iter().map(move |c| ((a, b), c)))
        {
            result.push(f(a, b, c));
        }
        result
    }

    // Ownership-based implementations for better performance
    #[inline]
    fn apply_owned<T, B>(self, value: Self::Output<T>) -> Self::Output<B>
    where
        Self::Source: Fn(T) -> B,
        T: Clone,
        B: Clone,
    {
        let mut result = Vec::new();
        for func in self {
            for val in value.clone() {
                result.push(func(val));
            }
        }
        result
    }

    #[inline]
    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,
    {
        let mut result = Vec::with_capacity(fa.len() * fb.len());
        for a in fa {
            for b in fb.clone() {
                result.push(f(a.clone(), b));
            }
        }
        result
    }

    #[inline]
    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,
    {
        let mut result = Vec::with_capacity(fa.len() * fb.len() * fc.len());
        for a in fa.into_iter() {
            for b in fb.clone() {
                for c in fc.clone() {
                    result.push(f(a.clone(), b.clone(), c.clone()));
                }
            }
        }
        result
    }
}