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
//! # Asynchronous Monad
//!
//! The `AsyncM` datatype represents a *lazy* asynchronous computation that will eventually produce a value of
//! type `A`.
//! It provides a monadic-style interface for composing asynchronous operations in a functional programming style.
//!
//! **Important**: `AsyncM` is a *cold* computation. If it was created with [`AsyncM::new`], the provided
//! closure is invoked each time you call [`AsyncM::try_get`]. The result is not memoized.
//!
//! ## Quick Start
//!
//! ```rust
//! use rustica::datatypes::async_monad::AsyncM;
//!
//! #[tokio::main]
//! async fn main() {
//!     // Create async computations
//!     let value = AsyncM::pure(42);
//!     let delayed = AsyncM::new(|| async {
//!         tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
//!         100
//!     });
//!
//!     // Chain computations with bind
//!     let result = value
//!         .bind(|x| async move { AsyncM::pure(x * 2) })
//!         .bind(|x| async move { AsyncM::pure(x + 10) });
//!
//!     // Run parallel computations
//!     let combined = value.zip(delayed).fmap(|(a, b)| async move { a + b });
//!
//!     // Execute and get results
//!     assert_eq!(result.try_get().await, 94);
//!     assert_eq!(combined.try_get().await, 142);
//! }
//! ```
//!
//! ## Functional Programming Context
//!
//! In functional programming, asynchronous monads are used to:
//!
//! - Represent computations that will complete in the future
//! - Compose and sequence asynchronous operations
//! - Handle asynchronous control flow in a pure functional manner
//! - Abstract away the complexity of async/await patterns
//!
//! Similar constructs in other functional programming languages include:
//!
//! - `IO` in Cats Effect (Scala)
//! - `Task` in Arrow (Kotlin)
//! - `Task` in fp-ts (TypeScript)
//! - `IO` in Haskell libraries like `async`
//!
//! ## Functional Programming Methods
//!
//! The `AsyncM` type provides inherent methods that follow functional programming patterns:
//!
//! - **Functor-like**: `fmap` allows mapping functions over the eventual result
//! - **Applicative-like**: `apply` enables applying functions wrapped in `AsyncM` to values wrapped in `AsyncM`
//! - **Monad-like**: `bind` provides sequencing of asynchronous operations
//!
//! **Note**: These are inherent methods, not trait implementations. `AsyncM` does not implement
//! the `Functor`, `Applicative`, or `Monad` traits, but provides equivalent functionality
//! through its own methods optimized for async operations.
//!
//! **Execution model**: most combinators (`fmap`, `bind`, `zip`, ...) build a new `AsyncM` without running
//! anything immediately. Actual execution happens when you call [`AsyncM::try_get`].
//!
//! ## Basic Usage
//!
//! ```rust
//! use rustica::datatypes::async_monad::AsyncM;
//!
//! #[tokio::main]
//! async fn main() {
//!     // Create a pure value
//!     let async_value = AsyncM::pure(42);
//!     
//!     // Map over the value
//!     let doubled = async_value.clone().fmap(|x| async move { x * 2 });
//!     assert_eq!(doubled.try_get().await, 84);
//!     
//!     // Chain async computations
//!     let result = async_value
//!         .bind(|x| async move { AsyncM::pure(x + 1) })
//!         .fmap(|x| async move { x * 2 });
//!     assert_eq!(result.try_get().await, 86);
//! }
//! ```
//!
//! # Complete Example: Building an Async Pipeline
//!
//! ```rust
//! use rustica::datatypes::async_monad::AsyncM;
//! use tokio;
//!
//! #[derive(Clone)]
//! struct User { id: i32, name: String }
//!
//! #[derive(Clone)]
//! struct Order { user_id: i32, total: f64 }
//!
//! async fn fetch_user(id: i32) -> User {
//!     // Simulate API call
//!     User { id, name: format!("User{}", id) }
//! }
//!
//! async fn fetch_orders(user_id: i32) -> Vec<Order> {
//!     // Simulate API call
//!     vec![Order { user_id, total: 99.99 }]
//! }
//!
//! async fn calculate_discount(orders: &[Order]) -> f64 {
//!     // Business logic
//!     if orders.iter().map(|o| o.total).sum::<f64>() > 100.0 {
//!         0.1
//!     } else {
//!         0.0
//!     }
//! }
//!
//! #[tokio::main]
//! async fn main() {
//!     // Build a pipeline using AsyncM
//!     let pipeline = AsyncM::pure(123)
//!         .fmap(|user_id| fetch_user(user_id))
//!         .bind(|user| {
//!             let user_clone = user.clone();
//!             let user_id = user.id;
//!             async move {
//!                 AsyncM::new(move || fetch_orders(user_id))
//!                     .fmap(move |orders| {
//!                         let value = user_clone.clone();
//!                         async move { (value, orders) }
//!                     })
//!             }
//!         })
//!         .bind(|(user, orders)| async move {
//!             let discount = calculate_discount(&orders).await;
//!             AsyncM::pure(format!(
//!                 "{} gets {}% discount on {} orders",
//!                 user.name,
//!                 discount * 100.0,
//!                 orders.len()
//!             ))
//!         });
//!     
//!     println!("{}", pipeline.try_get().await);
//! }
//!```
//!
//! ## Type Class Laws
//!
//! For computations whose provided closures are pure (no observable side effects) and do not
//! panic, the `AsyncM` combinators behave according to the standard Functor, Applicative, and
//! Monad laws.
//!
//! Note that combinators like `apply`/`zip` may run computations concurrently, which can affect
//! the *ordering* of side effects if your closures perform them.
//!
//! ### Functor Laws
//! - Identity: `fmap id = id`
//! - Composition: `fmap (f . g) = fmap f . fmap g`
//!
//! ### Applicative Laws
//! - Identity: `pure id <*> v = v`
//! - Homomorphism: `pure f <*> pure x = pure (f x)`
//! - Interchange: `u <*> pure y = pure ($ y) <*> u`
//! - Composition: `pure (.) <*> u <*> v <*> w = u <*> (v <*> w)`
//!
//! ### Monad Laws
//! - Left Identity: `pure a >>= f = f a`
//! - Right Identity: `m >>= pure = m`
//! - Associativity: `(m >>= f) >>= g = m >>= (\x -> f x >>= g)`
//!
//! See individual function documentation (e.g., `fmap`, `apply`, `bind`) for specific examples demonstrating these laws.
//!
//! ## Common Pitfalls and Solutions
//!
//! ### Infinite Recursion
//! ```rust,no_run
//! // DON'T: This creates infinite recursion
//! let bad = AsyncM::new(|| async {
//!     let inner = AsyncM::pure(42);
//!     inner.try_get().await // Avoid calling try_get inside AsyncM::new
//! });
//!
//! // DO: Use bind for chaining
//! use rustica::datatypes::async_monad::AsyncM;
//!
//! let good = AsyncM::pure(42)
//!     .bind(|x| async move { AsyncM::pure(x * 2) });
//! ```
//!
//! ### Shared State Issues
//! ```rust
//! # use std::sync::{Arc, Mutex};
//! # use rustica::datatypes::async_monad::AsyncM;
//! // DON'T: Capturing mutable references
//! let mut counter = 0;
//! // let bad = AsyncM::new(|| async { counter += 1; counter }); // Won't compile
//!
//! // DO: Use Arc<Mutex<T>> for shared mutable state
//! let counter = Arc::new(Mutex::new(0));
//! let good = AsyncM::new({
//!     let counter = counter.clone();
//!     move || {
//!         let value = counter.clone();
//!         async move {
//!             let mut c = value.lock().unwrap();
//!             *c += 1;
//!             *c
//!         }
//!     }
//! });
//! ```

use futures::{Future, FutureExt};
use quickcheck::{Arbitrary, Gen};
use std::{marker::PhantomData, panic, pin::Pin, sync::Arc};

/// A type alias for an asynchronous computation that can be sent between threads.
pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;

/// Internal representation of AsyncM, optimized for pure values.
#[derive(Clone)]
enum AsyncMInner<A> {
    /// A pure value with zero Arc overhead
    Pure(Arc<A>),
    /// A lazy computation
    Effect(Arc<dyn Fn() -> BoxFuture<'static, A> + Send + Sync + 'static>),
}

/// The asynchronous monad, which represents a computation that will eventually produce a value.
///
/// `AsyncM` provides a way to work with asynchronous operations in a functional style,
/// allowing composition and sequencing of async computations while maintaining
/// referentially-transparent composition when the provided closures are pure (free of observable
/// side effects).
///
/// # Type Parameters
///
/// * `A` - The type of the value that will be produced by the async computation
///
/// # Examples
///
/// ```rust
/// use rustica::datatypes::async_monad::AsyncM;
/// use tokio;
///
/// #[tokio::main]
/// async fn main() {
///     // Create an async computation
///     let computation: AsyncM<i32> = AsyncM::pure(42);
///     
///     // Run the computation and get the result
///     let result = computation.try_get().await;
///     assert_eq!(result, 42);
///     
///     // Transform the result using fmap
///     let transformed = computation.fmap(|x| async move { x * 2 });
///     assert_eq!(transformed.try_get().await, 84);
/// }
///
/// ```
///
/// # Type Class Laws
///
/// For computations whose provided closures are pure (no observable side effects) and do not
/// panic, `AsyncM` satisfies the following laws:
///
/// ## Functor Laws
/// ```rust
/// # use rustica::datatypes::async_monad::AsyncM;
/// # use tokio;
/// # #[tokio::main]
/// # async fn main() {
/// // Identity: fmap id = id
/// let m = AsyncM::pure(42);
/// let identity = m.clone().fmap(|x| async move { x });
/// assert_eq!(m.try_get().await, identity.try_get().await);
///
/// // Composition: fmap (f . g) = fmap f . fmap g
/// let f = |x: i32| async move { x * 2 };
/// let g = |x: i32| async move { x + 1 };
/// let m = AsyncM::pure(10);
///
/// let composed = m.clone().fmap(|x| async move { (x + 1) * 2 });
/// let chained = m.clone().fmap(g).fmap(f);
/// assert_eq!(composed.try_get().await, chained.try_get().await);
/// # }
/// ```
///
/// ## Applicative Laws
/// ```rust
/// # use rustica::datatypes::async_monad::AsyncM;
/// # use tokio;
/// # #[tokio::main]
/// # async fn main() {
/// // Identity: pure id <*> v = v
/// let v = AsyncM::pure(42);
/// let id_fn = AsyncM::pure(|x: i32| x);
/// assert_eq!(v.clone().apply(id_fn).try_get().await, v.try_get().await);
///
/// // Composition: pure (.) <*> u <*> v <*> w = u <*> (v <*> w)
/// let add_one = AsyncM::pure(|x: i32| x + 1);
/// let mul_two = AsyncM::pure(|x: i32| x * 2);
/// let value = AsyncM::pure(10);
///
/// // Left side: compose functions first
/// let compose = AsyncM::pure(|f: fn(i32) -> i32| {
///     move |g: fn(i32) -> i32| move |x| f(g(x))
/// });
/// // ... (composition example would be complex due to Rust's type system)
/// # }
/// ```
///
/// ## Monad Laws
/// ```rust
/// # use rustica::datatypes::async_monad::AsyncM;
/// # use tokio;
/// # #[tokio::main]
/// # async fn main() {
/// // Left identity: pure a >>= f = f a
/// let a = 42;
/// let f = |x| async move { AsyncM::pure(x * 2) };
///
/// let left = AsyncM::pure(a).bind(f.clone());
/// let right = f(a).await;
/// assert_eq!(left.try_get().await, right.try_get().await);
///
/// // Right identity: m >>= pure = m
/// let m = AsyncM::pure(42);
/// let bound = m.clone().bind(|x| async move { AsyncM::pure(x) });
/// assert_eq!(m.try_get().await, bound.try_get().await);
///
/// // Associativity: (m >>= f) >>= g = m >>= (\x -> f x >>= g)
/// let m = AsyncM::pure(10);
/// let f = |x| async move { AsyncM::pure(x + 1) };
/// let g = |x| async move { AsyncM::pure(x * 2) };
///
/// let left = m.clone().bind(f.clone()).bind(g.clone());
/// let right = m.bind(move |x| async move {
///     f(x).await.bind(g.clone())
/// });
/// assert_eq!(left.try_get().await, right.try_get().await);
/// # }
/// ```
///
/// # Advanced Examples
///
/// ## Error Handling with AsyncM
/// ```rust
/// # use rustica::datatypes::async_monad::AsyncM;
/// # use tokio;
/// # #[tokio::main]
/// # async fn main() {
/// // Chaining fallible operations
/// async fn fetch_user_id() -> Result<i32, String> {
///     Ok(42)
/// }
///
/// async fn fetch_user_name(id: i32) -> Result<String, String> {
///     Ok(format!("User{}", id))
/// }
///
/// let user_info = AsyncM::from_result_or_default(
///     || fetch_user_id(),
///     0
/// ).bind(|id| async move {
///     if id == 0 {
///         AsyncM::pure("Anonymous".to_string())
///     } else {
///         AsyncM::from_result_or_default(
///             move || fetch_user_name(id),
///             "Unknown".to_string()
///         )
///     }
/// });
///
/// println!("User: {}", user_info.try_get().await);
/// # }
/// ```
///
/// ## Parallel Computation Patterns
/// ```rust
/// # use rustica::datatypes::async_monad::AsyncM;
/// # use tokio;
/// # use std::time::{Duration, Instant};
/// # #[tokio::main]
/// # async fn main() {
/// // Parallel API calls
/// let fetch_weather = AsyncM::new(|| async {
///     tokio::time::sleep(Duration::from_millis(100)).await;
///     "Sunny, 22°C"
/// });
///
/// let fetch_news = AsyncM::new(|| async {
///     tokio::time::sleep(Duration::from_millis(150)).await;
///     vec!["Breaking: Rust 2.0 released!", "Tech: AsyncM patterns"]
/// });
///
/// let fetch_stocks = AsyncM::new(|| async {
///     tokio::time::sleep(Duration::from_millis(80)).await;
///     vec![("AAPL", 150.0), ("GOOGL", 2800.0)]
/// });
///
/// // Combine all results in parallel
/// let start = Instant::now();
/// let dashboard = fetch_weather
///     .zip(fetch_news)
///     .zip(fetch_stocks)
///     .fmap(|((weather, news), stocks)| async move {
///         format!(
///             "Weather: {}\nTop News: {}\nStocks: {:?}",
///             weather, news[0], stocks[0]
///         )
///     });
///
/// println!("{}", dashboard.try_get().await);
/// println!("Total time: {:?} (parallel execution)", start.elapsed());
/// # }
/// ```
///
/// ## Resource Management Pattern
/// ```rust
/// # use rustica::datatypes::async_monad::AsyncM;
/// # use tokio;
/// # use std::sync::{Arc, Mutex};
/// # #[tokio::main]
/// # async fn main() {
/// // Safely manage shared resources
/// #[derive(Clone)]
/// struct Database {
///     connections: Arc<Mutex<Vec<String>>>,
/// }
///
/// impl Database {
///     fn query(&self, sql: &str) -> AsyncM<String> {
///         let connections = self.connections.clone();
///         let sql = sql.to_string();
///         
///         AsyncM::new(move || {
///             let connections = connections.clone();
///             let sql = sql.clone();
///             async move {
///                 let mut conns = connections.lock().unwrap();
///                 conns.push(format!("Executed: {}", sql));
///                 format!("Result for: {}", sql)
///             }
///         })
///     }
/// }
///
/// let db = Database {
///     connections: Arc::new(Mutex::new(Vec::new())),
/// };
///
/// // Chain multiple queries
/// let result = db.query("SELECT * FROM users")
///     .bind(move |users| {
///         let db = db.clone();
///         async move {
///             db.query(&format!("SELECT orders FROM orders WHERE user IN ({})", users))
///         }
///     });
///
/// println!("Query result: {}", result.try_get().await);
/// # }
/// ```
#[derive(Clone)]
pub struct AsyncM<A> {
    inner: AsyncMInner<A>,
    _phantom: PhantomData<A>,
}

impl<A: Send + Sync + 'static> AsyncM<A> {
    /// Creates a new async computation from a future-producing function.
    ///
    /// This constructor allows you to create an `AsyncM` from any function that
    /// produces a `Future` when called.
    ///
    /// # Arguments
    ///
    /// * `f` - A function that creates a new future each time it's called
    ///
    /// # Type Parameters
    ///
    /// * `G` - The type of the function that produces futures
    /// * `F` - The type of the future produced by the function
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::datatypes::async_monad::AsyncM;
    /// use tokio;
    /// use std::time::Duration;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     // Create an async computation that produces a value after a delay
    ///     let delayed = AsyncM::new(|| async {
    ///         tokio::time::sleep(Duration::from_millis(10)).await;
    ///         42
    ///     });
    ///     
    ///     assert_eq!(delayed.try_get().await, 42);
    /// }
    /// ```
    #[inline(always)]
    pub fn new<G, F>(f: G) -> Self
    where
        G: Fn() -> F + Send + Sync + 'static,
        F: Future<Output = A> + Send + 'static,
    {
        AsyncM {
            inner: AsyncMInner::Effect(Arc::new(move || f().boxed())),
            _phantom: PhantomData,
        }
    }

    /// Creates a pure async computation that just returns the given value.
    ///
    /// This operation lifts a pure value into the `AsyncM` context without any
    /// asynchronous computation, following the pure value lifting pattern.
    ///
    /// # Arguments
    ///
    /// * `value` - The value to wrap in an async computation
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::datatypes::async_monad::AsyncM;
    /// use tokio;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     // Create a pure async value
    ///     let async_int: AsyncM<i32> = AsyncM::pure(42);
    ///     assert_eq!(async_int.try_get().await, 42);
    ///     
    ///     // Works with any type that implements Send
    ///     let async_string: AsyncM<String> = AsyncM::pure("hello".to_string());
    ///     assert_eq!(async_string.try_get().await, "hello");
    /// }
    /// ```
    #[inline(always)]
    pub fn pure(value: A) -> Self
    where
        A: Clone + Send + Sync + 'static,
    {
        AsyncM {
            inner: AsyncMInner::Pure(Arc::new(value)),
            _phantom: PhantomData,
        }
    }

    /// Executes this async computation and returns its value.
    ///
    /// This method runs the async computation and waits for it to complete.
    ///
    /// Note that this method does not return a `Result`: it will propagate panics from the underlying
    /// future. To convert panics into a default value, use [`AsyncM::recover_with`].
    ///
    /// If this `AsyncM` was created with [`AsyncM::new`], calling `try_get` multiple times will run the
    /// underlying computation multiple times.
    ///
    /// # Returns
    ///
    /// The computed value of type `A`
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::datatypes::async_monad::AsyncM;
    /// use tokio;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let computation = AsyncM::pure(42);
    ///     
    ///     // Run the computation and get the result
    ///     let result = computation.try_get().await;
    ///     assert_eq!(result, 42);
    /// }
    /// ```
    #[inline(always)]
    pub async fn try_get(&self) -> A
    where
        A: Clone,
    {
        match &self.inner {
            AsyncMInner::Pure(value) => (**value).clone(),
            AsyncMInner::Effect(run) => run().await,
        }
    }

    /// Maps a function over the result of this async computation.
    ///
    /// This operation allows transformation of the value inside the `AsyncM` context
    /// while preserving the asynchronous computation structure.
    ///
    /// # Arguments
    ///
    /// * `f` - An async function that transforms `A` into `B`
    ///
    /// # Type Parameters
    ///
    /// * `B` - The type of the result after applying the function
    /// * `F` - The type of the function
    /// * `Fut` - The type of the future returned by the function
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::datatypes::async_monad::AsyncM;
    /// use tokio;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let computation = AsyncM::pure(42);
    ///     
    ///     // Map a function over the async value
    ///     let doubled = computation.clone().fmap(|x| async move { x * 2 });
    ///     assert_eq!(doubled.try_get().await, 84);
    ///     
    ///     // Chain multiple transformations
    ///     let result = computation
    ///         .fmap(|x| async move { x + 10 })
    ///         .fmap(|x| async move { x.to_string() });
    ///     assert_eq!(result.try_get().await, "52");
    /// }
    /// ```
    #[inline(always)]
    pub fn fmap<B, F, Fut>(&self, f: F) -> AsyncM<B>
    where
        B: Send + 'static,
        F: Fn(A) -> Fut + Send + Sync + Clone + 'static,
        Fut: Future<Output = B> + Send + 'static,
        A: Clone,
    {
        // Fast path: Pure → Lazy (avoid double wrapping)
        if let AsyncMInner::Pure(value) = &self.inner {
            let value = Arc::clone(value);
            return AsyncM {
                inner: AsyncMInner::Effect(Arc::new(move || {
                    let f = f.clone();
                    let value = Arc::clone(&value);
                    async move { f((*value).clone()).await }.boxed()
                })),
                _phantom: PhantomData,
            };
        }

        // General path: Lazy → Lazy
        let inner = self.inner.clone();
        AsyncM {
            inner: AsyncMInner::Effect(Arc::new(move || {
                let f = f.clone();
                let inner = inner.clone();
                async move {
                    let a = if let AsyncMInner::Effect(run) = &inner {
                        run().await
                    } else {
                        unreachable!()
                    };
                    f(a).await
                }
                .boxed()
            })),
            _phantom: PhantomData,
        }
    }

    /// Chains this computation with another async computation.
    ///
    /// This is a fundamental sequencing operation that allows
    /// async operations to depend on the results of previous operations.
    ///
    /// # Arguments
    ///
    /// * `f` - An async function that takes the result of this computation and returns a new computation
    ///
    /// # Type Parameters
    ///
    /// * `B` - The type of the result after applying the function
    /// * `F` - The type of the function
    /// * `Fut` - The type of the future returned by the function
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::datatypes::async_monad::AsyncM;
    /// use tokio;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let computation = AsyncM::pure(42);
    ///     
    ///     // Chain with another async computation
    ///     let result = computation.clone().bind(|x| async move {
    ///         // This function returns a new AsyncM
    ///         AsyncM::pure(x + 10)
    ///     });
    ///     assert_eq!(result.try_get().await, 52);
    ///     
    ///     // Chain multiple bind operations
    ///     let result = computation
    ///         .bind(|x| async move { AsyncM::pure(x + 10) })
    ///         .bind(|x| async move { AsyncM::pure(x * 2) });
    ///     assert_eq!(result.try_get().await, 104);
    /// }
    /// ```
    #[inline(always)]
    pub fn bind<B, F, Fut>(&self, f: F) -> AsyncM<B>
    where
        B: Send + Sync + Clone + 'static,
        F: Fn(A) -> Fut + Send + Sync + Clone + 'static,
        Fut: Future<Output = AsyncM<B>> + Send + 'static,
        A: Clone,
    {
        // Fast path: Pure → direct call
        if let AsyncMInner::Pure(value) = &self.inner {
            let value = Arc::clone(value);
            return AsyncM {
                inner: AsyncMInner::Effect(Arc::new(move || {
                    let f = f.clone();
                    let value = Arc::clone(&value);
                    async move {
                        let next = f((*value).clone()).await;
                        // Inline next monad execution
                        match &next.inner {
                            AsyncMInner::Pure(v) => (**v).clone(),
                            AsyncMInner::Effect(run) => run().await,
                        }
                    }
                    .boxed()
                })),
                _phantom: PhantomData,
            };
        }

        // General path: Lazy → Lazy
        let inner = self.inner.clone();
        AsyncM {
            inner: AsyncMInner::Effect(Arc::new(move || {
                let f = f.clone();
                let inner = inner.clone();
                async move {
                    let a = if let AsyncMInner::Effect(run) = &inner {
                        run().await
                    } else {
                        unreachable!()
                    };
                    let next = f(a).await;
                    match &next.inner {
                        AsyncMInner::Pure(v) => (**v).clone(),
                        AsyncMInner::Effect(run) => run().await,
                    }
                }
                .boxed()
            })),
            _phantom: PhantomData,
        }
    }

    /// Applies a wrapped function to this async computation.
    ///
    /// This operation allows application of a function wrapped in `AsyncM` to a value wrapped in `AsyncM`,
    /// following the applicative pattern.
    ///
    /// # Arguments
    ///
    /// * `mf` - An async computation that produces a function
    ///
    /// # Type Parameters
    ///
    /// * `B` - The type of the result after applying the function
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::datatypes::async_monad::AsyncM;
    /// use tokio;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let computation = AsyncM::pure(42);
    ///     
    ///     // Create a function wrapped in AsyncM
    ///     let func = AsyncM::pure(|x: i32| x * 2);
    ///     
    ///     // Apply the wrapped function to the wrapped value
    ///     let result = computation.apply(func);
    ///     assert_eq!(result.try_get().await, 84);
    /// }
    /// ```
    #[inline(always)]
    pub fn apply<B, F>(&self, mf: AsyncM<F>) -> AsyncM<B>
    where
        B: Send + Sync + Clone + 'static,
        F: Fn(A) -> B + Clone + Send + Sync + 'static,
        A: Clone,
    {
        // Ultra-fast path: Pure + Pure → direct apply
        if let (AsyncMInner::Pure(v), AsyncMInner::Pure(f)) = (&self.inner, &mf.inner) {
            let result = (**f).clone()((**v).clone());
            return AsyncM::pure(result);
        }

        let self_inner = self.inner.clone();
        let mf_inner = mf.inner.clone();

        AsyncM {
            inner: AsyncMInner::Effect(Arc::new(move || {
                let self_inner = self_inner.clone();
                let mf_inner = mf_inner.clone();

                async move {
                    // Optimized concurrent execution
                    let (value, func) = tokio::join!(
                        async {
                            match &self_inner {
                                AsyncMInner::Pure(v) => (**v).clone(),
                                AsyncMInner::Effect(run) => run().await,
                            }
                        },
                        async {
                            match &mf_inner {
                                AsyncMInner::Pure(f) => (**f).clone(),
                                AsyncMInner::Effect(run) => run().await,
                            }
                        }
                    );
                    func(value)
                }
                .boxed()
            })),
            _phantom: PhantomData,
        }
    }

    /// Executes an async `Result` and maps errors to a default value.
    ///
    /// This is a lazy operation: the provided function `f` is invoked each time you call
    /// [`AsyncM::try_get`].
    ///
    /// # Arguments
    ///
    /// * `f` - A function that produces a future that returns a Result
    /// * `default_value` - The value to return if the Result is an Err
    ///
    /// # Returns
    ///
    /// An `AsyncM` that yields the `Ok` value, or yields `default_value` if `f()` returns `Err`.
    ///
    /// The error value is discarded.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::datatypes::async_monad::AsyncM;
    /// use tokio;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     // A function that returns a Result in a Future
    ///     async fn divide(a: i32, b: i32) -> Result<i32, &'static str> {
    ///         if b == 0 {
    ///             Err("Cannot divide by zero")
    ///         } else {
    ///             Ok(a / b)
    ///         }
    ///     }
    ///
    ///     // Handle a successful result
    ///     let success = AsyncM::from_result_or_default(|| divide(10, 2), 0);
    ///     assert_eq!(success.try_get().await, 5);
    ///
    ///     // Handle an error with default value
    ///     let failure = AsyncM::from_result_or_default(|| divide(10, 0), 0);
    ///     assert_eq!(failure.try_get().await, 0);
    /// }
    /// ```
    #[inline]
    pub fn from_result_or_default<F, Fut, E>(f: F, default_value: A) -> AsyncM<A>
    where
        F: Fn() -> Fut + Send + Sync + Clone + 'static,
        Fut: Future<Output = Result<A, E>> + Send + 'static,
        E: Send + Sync + 'static,
        A: Clone + Send + Sync + 'static,
    {
        // Store the default value as an Arc to avoid cloning it when constructing the future
        let default_value = Arc::new(default_value);

        AsyncM {
            inner: AsyncMInner::Effect(Arc::new(move || {
                let f = f.clone();
                let default_value = Arc::clone(&default_value);

                async move {
                    match f().await {
                        Ok(value) => value,
                        Err(_) => (*default_value).clone(),
                    }
                }
                .boxed()
            })),
            _phantom: PhantomData,
        }
    }

    /// Maps a function over the result of this async computation, consuming the original.
    ///
    /// This is an ownership-aware version of `fmap` that avoids unnecessary cloning
    /// by taking ownership of `self`.
    ///
    /// # Arguments
    ///
    /// * `f` - An async function that transforms `A` into `B`
    ///
    /// # Type Parameters
    ///
    /// * `B` - The type of the result after applying the function
    /// * `F` - The type of the function
    /// * `Fut` - The type of the future returned by the function
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::datatypes::async_monad::AsyncM;
    /// use tokio;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     // Create an AsyncM and consume it with map_owned
    ///     let result = AsyncM::pure(42)
    ///         .fmap_owned(|x| async move { x * 2 });
    ///     assert_eq!(result.try_get().await, 84);
    /// }
    /// ```
    #[inline]
    pub fn fmap_owned<B, F, Fut>(self, f: F) -> AsyncM<B>
    where
        F: Fn(A) -> Fut + Clone + Send + Sync + 'static,
        Fut: Future<Output = B> + Send + 'static,
        B: Send + 'static,
        A: Clone,
    {
        AsyncM {
            inner: AsyncMInner::Effect(Arc::new(move || {
                let f = f.clone();
                let inner = self.inner.clone();

                async move {
                    let a = match &inner {
                        AsyncMInner::Pure(value) => (**value).clone(),
                        AsyncMInner::Effect(run) => run().await,
                    };
                    f(a).await
                }
                .boxed()
            })),
            _phantom: PhantomData,
        }
    }

    /// Chains this computation with another async computation, consuming the original.
    ///
    /// This is an ownership-aware version of `bind` that avoids unnecessary cloning
    /// by taking ownership of `self`.
    ///
    /// # Arguments
    ///
    /// * `f` - An async function that takes the result of this computation and returns a new computation
    ///
    /// # Type Parameters
    ///
    /// * `B` - The type of the result after applying the function
    /// * `F` - The type of the function
    /// * `Fut` - The type of the future returned by the function
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::datatypes::async_monad::AsyncM;
    /// use tokio;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     // Create an AsyncM and consume it with bind_owned
    ///     let result = AsyncM::pure(42)
    ///         .bind_owned(|x| async move {
    ///             // This function returns a new AsyncM
    ///             AsyncM::pure(x + 10)
    ///         });
    ///     assert_eq!(result.try_get().await, 52);
    /// }
    /// ```
    #[inline]
    pub fn bind_owned<B, F, Fut>(self, f: F) -> AsyncM<B>
    where
        F: Fn(A) -> Fut + Clone + Send + Sync + 'static,
        Fut: Future<Output = AsyncM<B>> + Send + 'static,
        B: Send + Sync + Clone + 'static,
        A: Clone,
    {
        AsyncM {
            inner: AsyncMInner::Effect(Arc::new(move || {
                let f = f.clone();
                let inner = self.inner.clone();

                async move {
                    let a = match &inner {
                        AsyncMInner::Pure(value) => (**value).clone(),
                        AsyncMInner::Effect(run) => run().await,
                    };
                    let mb = f(a).await;
                    match &mb.inner {
                        AsyncMInner::Pure(value) => (**value).clone(),
                        AsyncMInner::Effect(run) => run().await,
                    }
                }
                .boxed()
            })),
            _phantom: PhantomData,
        }
    }

    /// Applies a wrapped function to this async computation, consuming both.
    ///
    /// This is an ownership-aware version of `apply` that avoids unnecessary cloning
    /// by taking ownership of both `self` and the function.
    ///
    /// # Arguments
    ///
    /// * `mf` - An async computation that produces a function
    ///
    /// # Type Parameters
    ///
    /// * `B` - The type of the result after applying the function
    /// * `F` - The type of the function
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::datatypes::async_monad::AsyncM;
    /// use tokio;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let computation = AsyncM::pure(42);
    ///     let func = AsyncM::pure(|x: i32| x * 2);
    ///     
    ///     // Apply the function to the value, consuming both
    ///     let result = computation.apply_owned(func);
    ///     assert_eq!(result.try_get().await, 84);
    /// }
    /// ```
    #[inline]
    pub fn apply_owned<B, F>(self, mf: AsyncM<F>) -> AsyncM<B>
    where
        F: Fn(A) -> B + Clone + Send + Sync + 'static,
        B: Send + Sync + 'static,
        A: Clone,
    {
        AsyncM {
            inner: AsyncMInner::Effect(Arc::new(move || {
                let self_inner = self.inner.clone();
                let mf_inner = mf.inner.clone();

                async move {
                    // Use join to run both futures concurrently
                    let a_fut = async {
                        match &self_inner {
                            AsyncMInner::Pure(v) => (**v).clone(),
                            AsyncMInner::Effect(run) => run().await,
                        }
                    };
                    let f_fut = async {
                        match &mf_inner {
                            AsyncMInner::Pure(f) => (**f).clone(),
                            AsyncMInner::Effect(run) => run().await,
                        }
                    };
                    let (a, f) = tokio::join!(a_fut, f_fut);
                    f(a)
                }
                .boxed()
            })),
            _phantom: PhantomData,
        }
    }

    /// Runs multiple AsyncM operations in parallel and combines their results.
    ///
    /// This function allows you to run two AsyncM operations concurrently and
    /// then combine their results using a provided function.
    ///
    /// # Arguments
    ///
    /// * `other` - Another AsyncM operation to run in parallel
    /// * `f` - A function that combines the results of both operations
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::datatypes::async_monad::AsyncM;
    /// use tokio;
    /// use std::time::Duration;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     // Create two operations that take some time
    ///     let op1 = AsyncM::new(|| async {
    ///         tokio::time::sleep(Duration::from_millis(10)).await;
    ///         42
    ///     });
    ///     
    ///     let op2 = AsyncM::new(|| async {
    ///         tokio::time::sleep(Duration::from_millis(10)).await;
    ///         "hello"
    ///     });
    ///     
    ///     // Run them in parallel and combine results
    ///     let result = op1.zip_with(op2, |a, b| format!("{} {}", b, a));
    ///     assert_eq!(result.try_get().await, "hello 42");
    /// }
    /// ```
    #[inline(always)]
    pub fn zip_with<B, C, F>(self, other: AsyncM<B>, f: F) -> AsyncM<C>
    where
        F: Fn(A, B) -> C + Send + Sync + Clone + 'static,
        B: Send + Sync + Clone + 'static,
        C: Send + Sync + Clone + 'static,
        A: Clone,
    {
        // Ultra-fast path: Pure + Pure → direct combine
        if let (AsyncMInner::Pure(a), AsyncMInner::Pure(b)) = (&self.inner, &other.inner) {
            let result = f.clone()((**a).clone(), (**b).clone());
            return AsyncM::pure(result);
        }

        AsyncM {
            inner: AsyncMInner::Effect(Arc::new(move || {
                let self_inner = self.inner.clone();
                let other_inner = other.inner.clone();
                let f = f.clone();

                async move {
                    let (a, b) = tokio::join!(
                        async {
                            match &self_inner {
                                AsyncMInner::Pure(v) => (**v).clone(),
                                AsyncMInner::Effect(run) => run().await,
                            }
                        },
                        async {
                            match &other_inner {
                                AsyncMInner::Pure(v) => (**v).clone(),
                                AsyncMInner::Effect(run) => run().await,
                            }
                        }
                    );
                    f(a, b)
                }
                .boxed()
            })),
            _phantom: PhantomData,
        }
    }

    /// Zips this AsyncM with another AsyncM, returning a tuple of their results.
    ///
    /// This is a convenience method for zip_with that simply returns the pair.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::datatypes::async_monad::AsyncM;
    /// use tokio;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let a = AsyncM::pure(42);
    ///     let b = AsyncM::pure("hello");
    ///     
    ///     let pair = a.zip(b);
    ///     let (num, str) = pair.try_get().await;
    ///     
    ///     assert_eq!(num, 42);
    ///     assert_eq!(str, "hello");
    /// }
    /// ```
    #[inline]
    pub fn zip<B>(self, other: AsyncM<B>) -> AsyncM<(A, B)>
    where
        B: Send + Sync + Clone + 'static,
        A: Clone,
    {
        self.zip_with(other, |a, b| (a, b))
    }

    /// Recovers from panics in the computation with a default value.
    ///
    /// This method attempts to run the async computation and, if it panics,
    /// returns the provided default value instead.
    ///
    /// This only handles unwind panics (via `catch_unwind`). It does not turn `Result::Err` into
    /// a default value; use [`AsyncM::from_result_or_default`] for that.
    ///
    /// # Arguments
    ///
    /// * `default` - The default value to return if the computation panics
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rustica::datatypes::async_monad::AsyncM;
    /// use tokio;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     // A computation that will panic
    ///     let faulty = AsyncM::new(|| async {
    ///         panic!("This will fail!");
    ///         #[allow(unreachable_code)]
    ///         42
    ///     });
    ///     
    ///     // Recover from the panic with a default value
    ///     let result = faulty.recover_with(0).try_get().await;
    ///     assert_eq!(result, 0);
    ///     
    ///     // A working computation
    ///     let working = AsyncM::pure(42);
    ///     let result = working.recover_with(0).try_get().await;
    ///     assert_eq!(result, 42);
    /// }
    /// ```
    #[inline]
    pub fn recover_with(self, default: A) -> AsyncM<A>
    where
        A: Send + Sync + Clone,
    {
        AsyncM {
            inner: AsyncMInner::Effect(Arc::new(move || {
                let inner = self.inner.clone();
                let default = default.clone();

                async move {
                    // Use std::panic::catch_unwind to handle panics
                    let result = panic::AssertUnwindSafe(async {
                        match &inner {
                            AsyncMInner::Pure(value) => (**value).clone(),
                            AsyncMInner::Effect(run) => run().await,
                        }
                    })
                    .catch_unwind()
                    .await;

                    match result {
                        Ok(value) => value,
                        Err(_) => default,
                    }
                }
                .boxed()
            })),
            _phantom: PhantomData,
        }
    }
}

impl<A: Arbitrary + 'static + Send + Sync> Arbitrary for AsyncM<A> {
    fn arbitrary(g: &mut Gen) -> Self {
        let value = A::arbitrary(g);
        AsyncM::pure(value)
    }
}