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
//! The State monad transformer, adding stateful computations to any monad.
//!
//! `StateT` allows combining state operations with effects provided by the base monad.
//! For example, it can be combined with `Option` to create stateful computations that
//! may fail, or with `Result` to create stateful computations that may produce errors.
//!
//! # Examples
//!
//! ```rust
//! use rustica::transformers::StateT;
//! use rustica::prelude::*;
//!
//! // Create a StateT over Option that increments the state and returns it
//! let state_t: StateT<i32, Option<(i32, i32)>, i32> =
//!     StateT::new(|s: i32| Some((s + 1, s)));
//!
//! // Run with an initial state
//! let result = state_t.run_state(10);
//! assert_eq!(result, Some((11, 10)));
//! ```
//!
//! ## State Manipulation and Composition
//!
//! ```rust
//! use rustica::transformers::StateT;
//! use rustica::prelude::*;
//!
//! // Define a more complex state type
//! #[derive(Debug, Clone, PartialEq)]
//! struct Counter {
//!     value: i32,
//!     increments: i32,
//! }
//!
//! // Create a state that increments the counter value
//! let increment: StateT<Counter, Option<(Counter, i32)>, i32> = StateT::new(|mut s: Counter| {
//!     s.value += 1;
//!     s.increments += 1;
//!     Some((s.clone(), s.value))
//! });
//!
//! // Create a StateT that doubles the counter value and returns the previous value
//! let double: StateT<Counter, Option<(Counter, i32)>, i32> = StateT::new(|mut s: Counter| {
//!     let prev = s.value;
//!     s.value *= 2;
//!     s.increments += 1;
//!     Some((s.clone(), prev))
//! });
//!
//! // Compose state operations
//! let inc_and_double = increment.bind_with(
//!     move |_| double.clone(),
//!     |m, f| m.and_then(|(s, _)| f((s, 0)))
//! );
//!
//! // Run with an initial state
//! let result = inc_and_double.run_state(Counter { value: 5, increments: 0 });
//!
//! // After incrementing, value = 6, then we double to 12
//! // The final result is ((Counter{value: 12, increments: 2}, 6))
//! // where 6 is the value after increment (returned by double)
//! assert_eq!(result.map(|(s, v)| (s.value, s.increments, v)), Some((12, 2, 6)));
//! ```

use std::sync::Arc;

use crate::error::{ComposableError, ComposableResult, IntoErrorContext};
use crate::traits::monad::Monad;
use crate::transformers::MonadTransformer;

/// Type alias for a function that transforms a state-value pair to another state-value pair
pub type StateValueMapper<S, A, B> = Box<dyn Fn((S, A)) -> (S, B) + Send + Sync>;

/// Type alias for a function that combines two state-value pairs into a new state-value pair
pub type StateCombiner<S, A, B, C> = Box<dyn Fn((S, A), (S, B)) -> (S, C) + Send + Sync>;

/// A monad transformer that adds state capabilities to a base monad.
///
/// The `StateT` type takes three type parameters:
/// - `S`: The state type
/// - `M`: The base monad type, which wraps a tuple of state and value
/// - `A`: The value type
///
/// # Examples
///
/// ```rust
/// use rustica::transformers::StateT;
/// use rustica::prelude::*;
///
/// // Create a state transformer over Result that counts characters
/// let count_chars: StateT<usize, Result<(usize, usize), &str>, usize> = StateT::new(|state: usize| {
///     Ok((state + 1, state))
/// });
///
/// // Run with a specific initial state
/// let result = count_chars.run_state(5);
/// assert_eq!(result, Ok((6, 5)));
/// ```
pub enum StateT<S, M, A> {
    Pure(A),
    LiftM(M),
    Effect(Arc<dyn Fn(S) -> M + Send + Sync>),
}

impl<S, M, A> Clone for StateT<S, M, A>
where
    S: 'static,
    M: Clone + 'static,
    A: Clone + 'static,
{
    fn clone(&self) -> Self {
        match self {
            StateT::Pure(a) => StateT::Pure(a.clone()),
            StateT::LiftM(m) => StateT::LiftM(m.clone()),
            StateT::Effect(f) => StateT::Effect(Arc::clone(f)),
        }
    }
}

impl<S, M, A> StateT<S, M, A>
where
    S: 'static,
    M: 'static,
    A: 'static,
{
    /// Creates a new `StateT` transformer.
    ///
    /// This constructor wraps a state transition function in the `StateT`
    /// transformer. The provided function takes an initial state and
    /// produces a monadic value that contains both the updated state and
    /// the computed result.
    ///
    /// # Parameters
    ///
    /// * `f` - Function from state to the underlying monad containing `(state, value)`
    ///
    /// # Returns
    ///
    /// A new `StateT` instance encapsulating the provided state transition.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::transformers::StateT;
    ///
    /// // A simple counter that increments the state and returns the old value
    /// let counter: StateT<i32, Option<(i32, i32)>, i32> = StateT::new(|s: i32| {
    ///     Some((s + 1, s))
    /// });
    ///
    /// assert_eq!(counter.run_state(0), Some((1, 0)));
    /// ```
    pub fn new<F>(f: F) -> Self
    where
        F: Fn(S) -> M + Send + Sync + 'static,
    {
        StateT::Effect(Arc::new(f))
    }

    /// Runs the state transformer with a specific initial state.
    ///
    /// # Parameters
    ///
    /// * `state` - The initial state to run with
    ///
    /// # Returns
    ///
    /// The resulting monadic value containing the new state and result
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::transformers::StateT;
    /// use rustica::prelude::*;
    /// use std::collections::HashMap;
    ///
    /// // Create a state that counts word frequencies
    /// let count_word: StateT<HashMap<String, i32>, Option<(HashMap<String, i32>, i32)>, i32> =
    ///     StateT::new(|mut state: HashMap<String, i32>| {
    ///         let word = "hello".to_string();
    ///         let count = state.entry(word).or_insert(0);
    ///         *count += 1;
    ///         let result = *count;
    ///         Some((state, result))
    ///     });
    ///
    /// // Run with an empty HashMap
    /// let mut map = HashMap::new();
    /// let result1 = count_word.run_state(map);
    ///
    /// // Extract the state and result
    /// let (new_state, count) = result1.unwrap();
    /// assert_eq!(count, 1);
    ///
    /// // Run again with the updated state
    /// let result2 = count_word.run_state(new_state);
    /// assert_eq!(result2.map(|(_, c)| c), Some(2));
    /// ```
    pub fn run_state(&self, state: S) -> M
    where
        M: Clone,
        A: Clone,
    {
        match self {
            StateT::Pure(_) => panic!("Cannot run Pure StateT without a base monad"),
            StateT::LiftM(m) => m.clone(),
            StateT::Effect(f) => f(state),
        }
    }

    /// Creates a `StateT` that returns the current state without modifying it.
    ///
    /// # Parameters
    ///
    /// * `pure` - A function that lifts a value into the base monad
    ///
    /// # Returns
    ///
    /// A new `StateT` that returns the current state
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::transformers::StateT;
    /// use rustica::prelude::*;
    ///
    /// // Create a StateT that gets the current state
    /// let get_state = StateT::<i32, Option<(i32, i32)>, i32>::get(Some);
    ///
    /// // Run with a specific state
    /// let result = get_state.run_state(42);
    /// assert_eq!(result, Some((42, 42)));
    /// ```
    pub fn get<P>(pure: P) -> StateT<S, M, S>
    where
        P: Fn((S, S)) -> M + Send + Sync + 'static,
        S: Clone + Send + Sync,
    {
        StateT::new(move |s: S| pure((s.clone(), s)))
    }

    /// Creates a `StateT` that replaces the current state and returns the old state.
    ///
    /// # Parameters
    ///
    /// * `new_state` - The new state to set
    /// * `pure` - Function to lift a value into the base monad
    ///
    /// # Returns
    ///
    /// A `StateT` that updates the state
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::transformers::StateT;
    /// use rustica::prelude::*;
    ///
    /// // Create a StateT that sets a new state and returns the old one
    /// let put_state = StateT::<i32, Result<(i32, i32), &str>, i32>::put(100, |t| Ok(t));
    ///
    /// // Run with a specific state
    /// let result = put_state.run_state(42);
    /// assert_eq!(result, Ok((100, 42)));
    /// ```
    pub fn put<P>(new_state: S, pure: P) -> StateT<S, M, S>
    where
        P: Fn((S, S)) -> M + Send + Sync + 'static,
        S: Clone + Send + Sync,
    {
        StateT::new(move |s: S| pure((new_state.clone(), s)))
    }

    /// Creates a `StateT` that modifies the current state with a function.
    ///
    /// # Parameters
    ///
    /// * `f` - Function to modify the state
    /// * `pure` - Function to lift a value into the base monad
    ///
    /// # Returns
    ///
    /// A `StateT` that modifies the state
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::transformers::StateT;
    /// use rustica::prelude::*;
    ///
    /// // Create a StateT that doubles the current state
    /// let modify_state = StateT::<i32, Option<(i32, ())>, ()>::modify(|s| s * 2, |t| Some(t));
    ///
    /// // Run with a specific state
    /// let result = modify_state.run_state(21);
    /// assert_eq!(result, Some((42, ())));
    /// ```
    pub fn modify<F, P>(f: F, pure: P) -> StateT<S, M, ()>
    where
        F: Fn(S) -> S + Send + Sync + 'static,
        P: Fn((S, ())) -> M + Send + Sync + 'static,
    {
        StateT::new(move |s: S| pure((f(s), ())))
    }

    /// Maps a function over the values inside this StateT.
    ///
    /// This is a specialized implementation that works with monads that have a map function.
    ///
    /// # Parameters
    ///
    /// * `f` - Function to apply to the values
    /// * `map_fn` - Function that knows how to map over the base monad
    ///
    /// # Returns
    ///
    /// A new StateT with the function applied to its values
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::transformers::StateT;
    /// use rustica::prelude::*;
    ///
    /// // Create a state transformer over Option
    /// let state_t: StateT<i32, Option<(i32, i32)>, i32> = StateT::new(|s: i32| {
    ///     Some((s + 1, s * 2))
    /// });
    ///
    /// // Map over the value using fmap_with
    /// let doubled_state = state_t.fmap_with(
    ///     |n: i32| n + 10,
    ///     |m: Option<(i32, i32)>, f: Box<dyn Fn((i32, i32)) -> (i32, i32) + Send + Sync>| m.map(f)
    /// );
    ///
    /// assert_eq!(doubled_state.run_state(5), Some((6, 20)));
    /// ```
    pub fn fmap_with<F, B, MapFn>(&self, f: F, map_fn: MapFn) -> StateT<S, M, B>
    where
        F: Fn(A) -> B + Send + Sync + Clone + 'static,
        MapFn: Fn(M, StateValueMapper<S, A, B>) -> M + Send + Sync + 'static,
        S: Clone + Send + Sync + 'static,
        M: Clone + 'static,
        A: Clone + 'static,
        B: 'static,
    {
        match self {
            StateT::Pure(a) => {
                let b = f(a.clone());
                StateT::Pure(b)
            },
            StateT::LiftM(m) => StateT::LiftM(map_fn(m.clone(), {
                let f_clone = f.clone();
                let mapper: StateValueMapper<S, A, B> =
                    Box::new(move |(state, a)| (state, f_clone(a)));
                mapper
            })),
            StateT::Effect(run_fn) => {
                let run_fn = Arc::clone(run_fn);
                StateT::new(move |s: S| {
                    let f_clone = f.clone();
                    let mapper: StateValueMapper<S, A, B> =
                        Box::new(move |(state, a)| (state, f_clone(a)));

                    map_fn(run_fn(s), mapper)
                })
            },
        }
    }

    /// Binds this StateT with a function that produces another StateT.
    ///
    /// This is the monadic bind operation, which allows sequencing operations that depend
    /// on the result of previous operations.
    ///
    /// # Parameters
    ///
    /// * `f` - Function that takes a value and returns a new StateT
    /// * `bind_fn` - Function that knows how to perform bind on the base monad
    ///
    /// # Returns
    ///
    /// A new StateT representing the sequenced computation
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::transformers::StateT;
    /// use rustica::prelude::*;
    ///
    /// // Create a state that increments and returns the new value
    /// let increment: StateT<i32, Option<(i32, i32)>, i32> =
    ///     StateT::new(|s: i32| Some((s + 1, s + 1)));
    ///
    /// // Create a function that takes the output and produces another state transformer
    /// let validate = |n: i32| {
    ///     StateT::new(move |s: i32| {
    ///         if n > 10 {
    ///             Some((s, n * 2))
    ///         } else {
    ///             Some((s, n))
    ///         }
    ///     })
    /// };
    ///
    /// // Compose using bind_with
    /// let inc_and_validate: StateT<i32, Option<(i32, i32)>, i32> = increment.bind_with(
    ///     validate,
    ///     |m: Option<(i32, i32)>, f| m.and_then(|(s, a)| f((s, a)))
    /// );
    ///
    /// assert_eq!(inc_and_validate.run_state(5), Some((6, 6))); // <= 10, returns as-is
    /// assert_eq!(inc_and_validate.run_state(10), Some((11, 22))); // > 10, doubles
    /// ```
    pub fn bind_with<F, B, BindFn, N>(&self, f: F, bind_fn: BindFn) -> StateT<S, N, B>
    where
        F: Fn(A) -> StateT<S, N, B> + Send + Sync + Clone + 'static,
        BindFn: Fn(M, Box<dyn Fn((S, A)) -> N + Send + Sync>) -> N + Send + Sync + 'static,
        S: Clone + Send + Sync + 'static,
        M: Clone + Send + Sync + 'static,
        A: Clone + 'static,
        N: Clone + 'static,
        B: Clone + 'static,
    {
        match self {
            StateT::Pure(a) => f(a.clone()),
            StateT::LiftM(m) => {
                let m_clone = m.clone();
                let f_clone = f.clone();

                StateT::new(move |_: S| {
                    let f_for_closure = f_clone.clone();
                    let binder: Box<dyn Fn((S, A)) -> N + Send + Sync> =
                        Box::new(move |(state, a)| {
                            let next_state_t = f_for_closure(a);
                            next_state_t.run_state(state)
                        });

                    bind_fn(m_clone.clone(), binder)
                })
            },
            StateT::Effect(run_fn) => {
                let run_fn = Arc::clone(run_fn);
                let f_clone = f.clone();

                StateT::new(move |s: S| {
                    let f_for_closure = f_clone.clone();
                    let binder: Box<dyn Fn((S, A)) -> N + Send + Sync> =
                        Box::new(move |(state, a)| {
                            let next_state_t = f_for_closure(a);
                            next_state_t.run_state(state)
                        });

                    bind_fn(run_fn(s), binder)
                })
            },
        }
    }

    /// Combines this StateT with another using a binary function.
    ///
    /// This is useful for combining the results of two state operations that have the same state type.
    ///
    /// # Parameters
    ///
    /// * `other` - Another StateT to combine with
    /// * `f` - Function to combine the results
    /// * `combine_fn` - Function that knows how to combine values in the base monad
    ///
    /// # Returns
    ///
    /// A new StateT with the combined results
    pub fn combine_with<B, C, F, CombineFn>(
        &self, other: &StateT<S, M, B>, f: F, combine_fn: CombineFn,
    ) -> StateT<S, M, C>
    where
        F: Fn(A, B) -> C + Send + Sync + Clone + 'static,
        CombineFn: Fn(M, M, StateCombiner<S, A, B, C>) -> M + Send + Sync + 'static,
        S: Clone + Send + Sync + 'static,
        M: Clone + 'static,
        A: Clone + 'static,
        B: Clone + 'static,
        C: 'static,
    {
        match (self, other) {
            (StateT::Pure(a), StateT::Pure(b)) => {
                let c = f(a.clone(), b.clone());
                StateT::Pure(c)
            },
            (StateT::LiftM(m1), StateT::LiftM(m2)) => {
                let combiner: StateCombiner<S, A, B, C> = Box::new(move |(s1, a), (_, b)| {
                    let f_clone = f.clone();
                    (s1, f_clone(a, b))
                });
                StateT::LiftM(combine_fn(m1.clone(), m2.clone(), combiner))
            },
            (StateT::Effect(self_run_fn), StateT::Effect(other_run_fn)) => {
                let self_run_fn = Arc::clone(self_run_fn);
                let other_run_fn = Arc::clone(other_run_fn);

                StateT::new(move |s: S| {
                    let f_clone = f.clone();
                    let combiner: StateCombiner<S, A, B, C> =
                        Box::new(move |(_, a), (state, b)| {
                            let f_clone = f_clone.clone();
                            (state, f_clone(a, b))
                        });

                    combine_fn(self_run_fn(s.clone()), other_run_fn(s), combiner)
                })
            },
            _ => panic!("Cannot combine StateT variants of different types"),
        }
    }

    /// Creates a new `StateT` transformer with a pure value.
    ///
    /// This method lifts a pure value into the `StateT` monad without changing
    /// the current state. It's the analog of `State::pure`.
    ///
    /// # Parameters
    ///
    /// * `a` - The value to lift into the StateT
    /// * `pure_fn` - A function that lifts a tuple into the base monad
    ///
    /// # Returns
    ///
    /// A new `StateT` containing the value and preserving the state
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::transformers::StateT;
    ///
    /// // Create a StateT with a pure value
    /// let state_t = StateT::<i32, Option<(i32, String)>, String>::pure("hello".to_string(), Some);
    ///
    /// // Running with any state just returns the value and preserves the state
    /// assert_eq!(state_t.run_state(42), Some((42, "hello".to_string())));
    /// ```
    pub fn pure<P>(a: A, pure_fn: P) -> Self
    where
        P: Fn((S, A)) -> M + Send + Sync + 'static,
        A: Clone + Send + Sync,
    {
        StateT::new(move |s| pure_fn((s, a.clone())))
    }

    /// Runs the state computation and returns only the final state, discarding the value.
    ///
    /// # Parameters
    ///
    /// * `s` - The initial state
    /// * `extract_state_fn` - Function that knows how to extract the state from the monadic result
    ///
    /// # Returns
    ///
    /// The final state after running the computation
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::transformers::StateT;
    ///
    /// // Create a state that increments the state
    /// let state_t = StateT::<i32, Option<(i32, String)>, String>::new(|s| {
    ///     Some((s + 1, format!("Value: {}", s)))
    /// });
    ///
    /// // Run and extract only the state
    /// let result = state_t.exec_state(42, |opt| opt.map(|(s, _)| s));
    /// assert_eq!(result, Some(43));
    /// ```
    pub fn exec_state<F, B>(&self, s: S, extract_state_fn: F) -> B
    where
        F: FnOnce(M) -> B,
        M: Clone,
        A: Clone,
    {
        extract_state_fn(self.run_state(s))
    }

    /// Applies a function inside a StateT to a value inside another StateT.
    ///
    /// This is the applicative apply operation for StateT, allowing you to
    /// apply a function in a stateful context to a value in a stateful context.
    ///
    /// # Parameters
    ///
    /// * `other` - A StateT containing the value to apply the function to
    /// * `apply_fn` - A function that knows how to apply functions in the base monad
    ///
    /// # Returns
    ///
    /// A new StateT containing the result of applying the function to the value
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::transformers::StateT;
    ///
    /// // Define a function that adds state to its argument
    /// let fn_state: StateT<i32, Option<(i32, i32)>, i32> = StateT::new(|s: i32| {
    ///     Some((s + 1, 10))
    /// });
    ///
    /// // Define a state holding a value
    /// let value_state: StateT<i32, Option<(i32, i32)>, i32> = StateT::new(|s: i32| {
    ///     Some((s * 2, 5))
    /// });
    ///
    /// // Apply the function to the value
    /// let result: StateT<i32, Option<(i32, i32)>, i32> = fn_state.apply(value_state, |f_result, v_result| {
    ///     match (f_result, v_result) {
    ///         (Some((s1, f)), Some((s2, v))) => {
    ///             Some((s2, f + v)) // Using the second state, add the values
    ///         },
    ///         _ => None
    ///     }
    /// });
    ///
    /// // Run with state 10
    /// // fn_state: returns (11, 10)
    /// // value_state: returns (20, 5)
    /// // apply: returns (20, 10 + 5) = (20, 15)
    /// assert_eq!(result.run_state(10), Some((20, 15)));
    /// ```
    pub fn apply<B, C, ApplyFn>(&self, other: StateT<S, M, B>, apply_fn: ApplyFn) -> StateT<S, M, C>
    where
        A: Clone + Send + Sync + 'static,
        B: Clone + Send + Sync + 'static,
        C: Clone + Send + Sync + 'static,
        S: Clone + Send + Sync + 'static,
        M: Clone + Send + Sync + 'static,
        ApplyFn: Fn(M, M) -> M + Send + Sync + 'static,
    {
        match (self, &other) {
            (StateT::Pure(f), StateT::Pure(v)) => {
                let f_clone = f.clone();
                let v_clone = v.clone();
                StateT::new(move |s: S| {
                    let f_state = StateT::Pure(f_clone.clone());
                    let v_state = StateT::Pure(v_clone.clone());
                    let f_result = f_state.run_state(s.clone());
                    let v_result = v_state.run_state(s);
                    apply_fn(f_result, v_result)
                })
            },
            (StateT::LiftM(m1), StateT::LiftM(m2)) => {
                StateT::LiftM(apply_fn(m1.clone(), m2.clone()))
            },
            (StateT::Effect(self_run), StateT::Effect(other_run)) => {
                let self_run = Arc::clone(self_run);
                let other_run = Arc::clone(other_run);

                StateT::new(move |s: S| apply_fn(self_run(s.clone()), other_run(s)))
            },
            _ => {
                let self_run = match self {
                    StateT::Pure(_) | StateT::LiftM(_) => {
                        let self_clone = self.clone();
                        Arc::new(move |s: S| self_clone.run_state(s))
                            as Arc<dyn Fn(S) -> M + Send + Sync>
                    },
                    StateT::Effect(run) => Arc::clone(run),
                };

                let other_run = match &other {
                    StateT::Pure(_) | StateT::LiftM(_) => {
                        let other_clone = other.clone();
                        Arc::new(move |s: S| other_clone.run_state(s))
                            as Arc<dyn Fn(S) -> M + Send + Sync>
                    },
                    StateT::Effect(run) => Arc::clone(run),
                };

                StateT::new(move |s: S| apply_fn(self_run(s.clone()), other_run(s)))
            },
        }
    }

    /// Joins a nested StateT structure, flattening it to a single level.
    ///
    /// This is useful when working with operations that return StateT instances
    /// inside StateT, allowing you to flatten the nested structure.
    ///
    /// # Parameters
    ///
    /// * `join_fn` - Function that knows how to join/flatten the base monad
    ///
    /// # Returns
    ///
    /// A flattened StateT instance
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::transformers::StateT;
    ///
    /// // Create a nested StateT (StateT inside StateT)
    /// let nested: StateT<i32, Option<(i32, StateT<i32, Option<(i32, i32)>, i32>)>, StateT<i32, Option<(i32, i32)>, i32>> =
    ///     StateT::new(|s: i32| {
    ///         let inner = StateT::new(move |inner_s: i32| {
    ///             Some((inner_s * 2, inner_s + s))
    ///         });
    ///         Some((s + 1, inner))
    ///     });
    ///
    /// // Flatten the structure
    /// let flattened = nested.join(|m| {
    ///     m.and_then(|(outer_s, inner_state_t)| {
    ///         inner_state_t.run_state(outer_s)
    ///     })
    /// });
    ///
    /// // Run the flattened computation
    /// // With initial state 10:
    /// // 1. outer: (11, inner_state_t)
    /// // 2. inner_state_t with state 11: (22, 21)
    /// assert_eq!(flattened.run_state(10), Some((22, 21)));
    /// ```
    pub fn join<JoinFn, OuterM>(&self, join_fn: JoinFn) -> StateT<S, OuterM, A>
    where
        A: Clone + Send + Sync + 'static,
        M: Clone + 'static,
        JoinFn: Fn(M) -> OuterM + Send + Sync + 'static,
        OuterM: 'static,
    {
        match self {
            StateT::Pure(inner_state_t) => StateT::Pure(inner_state_t.clone()),
            StateT::LiftM(m) => StateT::LiftM(join_fn(m.clone())),
            StateT::Effect(run_fn) => {
                let run_fn = Arc::clone(run_fn);
                StateT::new(move |s: S| join_fn(run_fn(s)))
            },
        }
    }
}

impl<S, M, A> MonadTransformer for StateT<S, M, A>
where
    S: Clone + Send + Sync + 'static,
    M: Monad<Source = (S, A)> + Send + Sync + Clone + 'static,
    A: Clone + Send + Sync + 'static,
{
    type BaseMonad = M;

    #[inline]
    fn lift(base: M) -> Self {
        StateT::new(move |_: S| base.clone())
    }
}

impl<S, E, A> StateT<S, Result<(S, A), E>, A>
where
    S: Clone + 'static,
    E: 'static,
    A: Send + Sync + 'static,
{
    /// Runs the state transformer and converts errors to [`ComposableError`] for standardized error handling.
    ///
    /// This method executes the state transformer with the given initial state and converts
    /// any errors to the standardized [`ComposableError`] type, providing consistent error handling
    /// across the library.
    ///
    /// # Parameters
    ///
    /// * `state` - Initial state
    ///
    /// # Returns
    ///
    /// Result containing either the state-value pair or a [`ComposableError`]
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::transformers::StateT;
    ///
    /// // Create a StateT that may fail with division
    /// let safe_div: StateT<i32, Result<(i32, i32), String>, i32> = StateT::new(|s: i32| {
    ///     if s == 0 {
    ///         Err("Division by zero".to_string())
    ///     } else {
    ///         Ok((s, 100 / s))
    ///     }
    /// });
    ///
    /// // Convert regular errors to [`ComposableError`]
    /// let result = safe_div.try_run_state(4);
    /// assert!(result.is_ok());
    /// assert_eq!(result.unwrap(), (4, 25)); // 100/4 = 25
    ///
    /// // With error
    /// let result = safe_div.try_run_state(0);
    /// assert!(result.is_err());
    /// assert_eq!(result.unwrap_err().core_error(), "Division by zero");
    /// ```
    pub fn try_run_state(&self, state: S) -> ComposableResult<(S, A), E>
    where
        A: Clone,
        E: Clone,
    {
        match self {
            StateT::Pure(_) => panic!("Cannot run Pure StateT without proper context"),
            StateT::LiftM(result) => match result.as_ref() {
                Ok((s, a)) => Ok((s.clone(), a.clone())),
                Err(e) => Err(ComposableError::new(e.clone())),
            },
            StateT::Effect(run_fn) => run_fn(state).map_err(ComposableError::new),
        }
    }

    /// Runs the state transformer with context information for better error reporting.
    ///
    /// This method is similar to `try_run_state` but allows for adding context to the error,
    /// which can provide more information about what was happening when the error occurred.
    ///
    /// # Parameters
    ///
    /// * `state` - Initial state
    /// * `context` - Context information to include with errors
    ///
    /// # Returns
    ///
    /// Result containing either the state-value pair or a [`ComposableError`] with context
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::transformers::StateT;
    ///
    /// // Create a StateT that may fail with division
    /// let safe_div: StateT<i32, Result<(i32, i32), String>, i32> = StateT::new(|s: i32| {
    ///     if s == 0 {
    ///         Err("Division by zero".to_string())
    ///     } else {
    ///         Ok((s, 100 / s))
    ///     }
    /// });
    ///
    /// // Run with context
    /// let result = safe_div.try_run_state_with_context(4, "processing user input");
    /// assert!(result.is_ok());
    /// assert_eq!(result.unwrap(), (4, 25)); // 100/4 = 25
    ///
    /// // With error and context
    /// let result = safe_div.try_run_state_with_context(0, "processing user input");
    /// assert!(result.is_err());
    /// let error = result.unwrap_err();
    /// assert_eq!(error.core_error(), "Division by zero");
    /// assert_eq!(error.context(), vec!["processing user input".to_string()]);
    /// ```
    pub fn try_run_state_with_context<C>(&self, state: S, context: C) -> ComposableResult<(S, A), E>
    where
        C: IntoErrorContext,
        A: Clone,
        E: Clone,
    {
        let context = context.into_error_context();
        match self {
            StateT::Pure(_) => panic!("Cannot run Pure StateT without proper context"),
            StateT::LiftM(result) => match result.as_ref() {
                Ok((s, a)) => Ok((s.clone(), a.clone())),
                Err(e) => Err(ComposableError::new(e.clone()).with_context(context.clone())),
            },
            StateT::Effect(run_fn) => {
                run_fn(state).map_err(|e| ComposableError::new(e).with_context(context.clone()))
            },
        }
    }

    /// Maps a function over the error contained in this StateT.
    ///
    /// This method transforms the error type of the StateT, allowing for conversion
    /// between different error types while preserving the structure of the StateT.
    ///
    /// # Parameters
    ///
    /// * `f` - Function to apply to the error
    ///
    /// # Returns
    ///
    /// A new StateT with the mapped error
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::transformers::StateT;
    ///
    /// // Create a StateT with a string error
    /// let state_t: StateT<i32, Result<(i32, i32), String>, i32> = StateT::new(|s: i32| {
    ///     if s == 0 {
    ///         Err("Division by zero".to_string())
    ///     } else {
    ///         Ok((s, 100 / s))
    ///     }
    /// });
    ///
    /// // Map the error to a different type
    /// let mapped = state_t.map_error(|e: String| e.len() as i32);
    ///
    /// // Now the error is an i32 (the length of the original error string)
    /// let result = mapped.run_state(0);
    /// assert_eq!(result, Err(16)); // "Division by zero" has length 16
    /// ```
    pub fn map_error<F, E2>(&self, f: F) -> StateT<S, Result<(S, A), E2>, A>
    where
        F: Fn(E) -> E2 + Send + Sync + 'static,
        E2: 'static,
        A: Clone,
        E: Clone,
    {
        match self {
            StateT::Pure(a) => StateT::Pure(a.clone()),
            StateT::LiftM(result) => {
                let mapped_result = match result.as_ref() {
                    Ok((s, a)) => Ok((s.clone(), a.clone())),
                    Err(e) => Err(f(e.clone())),
                };
                StateT::LiftM(mapped_result)
            },
            StateT::Effect(run_fn) => {
                let run_fn = Arc::clone(run_fn);
                StateT::new(move |s: S| run_fn(s).map_err(&f))
            },
        }
    }

    /// Runs the state transformer and returns only the value as a [`ComposableResult`].
    ///
    /// This method is similar to `try_run_state` but discards the final state and
    /// only returns the computed value.
    ///
    /// # Parameters
    ///
    /// * `state` - Initial state
    ///
    /// # Returns
    ///
    /// Result containing either the computed value or a [`ComposableError`]
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::transformers::StateT;
    ///
    /// let safe_div: StateT<i32, Result<(i32, i32), String>, i32> = StateT::new(|s: i32| {
    ///     if s == 0 {
    ///         Err("Division by zero".to_string())
    ///     } else {
    ///         Ok((s, 100 / s))
    ///     }
    /// });
    ///
    /// let result = safe_div.try_eval_state(4);
    /// assert_eq!(result, Ok(25)); // 100/4 = 25
    ///
    /// let result = safe_div.try_eval_state(0);
    /// assert!(result.is_err());
    /// assert_eq!(result.unwrap_err().core_error(), "Division by zero");
    /// ```
    pub fn try_eval_state(&self, state: S) -> ComposableResult<A, E>
    where
        A: Clone,
        E: Clone,
    {
        self.try_run_state(state).map(|(_, a)| a)
    }

    /// Runs the state transformer with context and returns only the value as a [`ComposableResult`].
    ///
    /// This method is similar to `try_run_state_with_context` but discards the final state
    /// and only returns the computed value.
    ///
    /// # Parameters
    ///
    /// * `state` - Initial state
    /// * `context` - Context information to include with errors
    ///
    /// # Returns
    ///
    /// Result containing either the computed value or a [`ComposableError`] with context
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::transformers::StateT;
    ///
    /// let safe_div: StateT<i32, Result<(i32, i32), String>, i32> = StateT::new(|s: i32| {
    ///     if s == 0 {
    ///         Err("Division by zero".to_string())
    ///     } else {
    ///         Ok((s, 100 / s))
    ///     }
    /// });
    ///
    /// let result = safe_div.try_eval_state_with_context(4, "processing user input");
    /// assert_eq!(result, Ok(25)); // 100/4 = 25
    ///
    /// let result = safe_div.try_eval_state_with_context(0, "processing user input");
    /// assert!(result.is_err());
    /// let error = result.unwrap_err();
    /// assert_eq!(error.core_error(), "Division by zero");
    /// assert_eq!(error.context(), vec!["processing user input".to_string()]);
    /// ```
    pub fn try_eval_state_with_context<C>(&self, state: S, context: C) -> ComposableResult<A, E>
    where
        C: IntoErrorContext,
        A: Clone,
        E: Clone,
    {
        self.try_run_state_with_context(state, context)
            .map(|(_, a)| a)
    }

    /// Runs the state transformer and returns only the final state as a [`ComposableResult`].
    ///
    /// This method is similar to `try_run_state` but discards the computed value and
    /// only returns the final state.
    ///
    /// # Parameters
    ///
    /// * `state` - Initial state
    ///
    /// # Returns
    ///
    /// Result containing either the final state or a [`ComposableError`]
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::transformers::StateT;
    ///
    /// let safe_div: StateT<i32, Result<(i32, i32), String>, i32> = StateT::new(|s: i32| {
    ///     if s == 0 {
    ///         Err("Division by zero".to_string())
    ///     } else {
    ///         Ok((s + 1, 100 / s))
    ///     }
    /// });
    ///
    /// let result = safe_div.try_exec_state(4);
    /// assert_eq!(result, Ok(5)); // initial state 4 + 1 = 5
    ///
    /// let result = safe_div.try_exec_state(0);
    /// assert!(result.is_err());
    /// assert_eq!(result.unwrap_err().core_error(), "Division by zero");
    /// ```
    pub fn try_exec_state(&self, state: S) -> ComposableResult<S, E>
    where
        A: Clone,
        E: Clone,
    {
        self.try_run_state(state).map(|(s, _)| s)
    }
}

use crate::datatypes::id::Id;

impl<S, A> StateT<S, Id<(S, A)>, A>
where
    S: Clone + Send + Sync + 'static,
    A: Clone + Send + Sync + 'static,
{
    /// Converts this `StateT<S, Id<(S, A)>, A>` into a `State<S, A>`.
    ///
    /// This method allows you to convert a state transformer with the identity monad as its base
    /// back into a regular `State` monad. This is useful when you want to drop the transformer
    /// context and work with the simpler state monad.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::transformers::StateT;
    /// use rustica::datatypes::id::Id;
    /// use rustica::datatypes::state::State;
    ///
    /// // Create a StateT with Id as the monad
    /// let state_t: StateT<i32, Id<(i32, i32)>, i32> = StateT::new(|s: i32| {
    ///     Id::new((s * 2, s + 1))
    /// });
    ///
    /// // Convert to State
    /// let state: State<i32, i32> = state_t.to_state();
    ///
    /// // The behavior should be identical
    /// assert_eq!(state.run_state(21), (22, 42));
    /// ```
    pub fn to_state(self) -> crate::datatypes::state::State<S, A> {
        crate::datatypes::state::State::new(move |s: S| {
            let result = self.run_state(s.clone());
            let (new_state, value) = result.unwrap().clone();
            (value, new_state)
        })
    }

    /// Converts a `State<S, A>` into a `StateT<S, Id<(S, A)>, A>`.
    ///
    /// This method allows you to lift a regular state monad into the transformer context
    /// with the identity monad as the base. This is useful for composing stateful computations
    /// with other monad transformers.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::datatypes::state::State;
    /// use rustica::datatypes::id::Id;
    /// use rustica::transformers::StateT;
    ///
    /// // Create a State
    /// let state = State::new(|s: i32| (s * 2, s + 1));
    ///
    /// // Convert to StateT
    /// let state_t: StateT<i32, Id<(i32, i32)>, i32> = StateT::from_state(state);
    ///
    /// // The behavior should be identical
    /// assert_eq!(state_t.run_state(21).unwrap(), (22, 42));
    /// ```
    pub fn from_state(state: crate::datatypes::state::State<S, A>) -> Self {
        StateT::new(move |s: S| {
            let (a, s2) = state.run_state(s);
            Id::new((s2, a))
        })
    }
}