1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
//! Stack-safe fallible computation type with guaranteed safety for unlimited recursion depth.
//!
//! Wraps [`Trampoline<Result<A, E>>`](crate::types::Trampoline) with ergonomic combinators for error handling. Provides complete stack safety for fallible computations that may recurse deeply.
//!
//! ### Examples
//!
//! ```
//! use fp_library::types::*;
//!
//! let task: TryTrampoline<i32, String> =
//! TryTrampoline::ok(10).map(|x| x * 2).bind(|x| TryTrampoline::ok(x + 5));
//!
//! assert_eq!(task.evaluate(), Ok(25));
//! ```
#[fp_macros::document_module]
mod inner {
use {
crate::{
classes::{
Deferrable,
LazyConfig,
Monoid,
Semigroup,
},
types::{
Lazy,
Thunk,
Trampoline,
TryLazy,
},
},
core::ops::ControlFlow,
fp_macros::*,
std::fmt,
};
/// A lazy, stack-safe computation that may fail with an error.
///
/// This is [`Trampoline<Result<A, E>>`] with ergonomic combinators.
///
/// ### When to Use
///
/// Use `TryTrampoline` for stack-safe fallible recursion. It provides unlimited recursion
/// depth without stack overflow, but requires `'static` types and does not have HKT brands.
/// For lightweight fallible deferred computation with HKT support, use
/// [`TryThunk`](crate::types::TryThunk). For memoized fallible computation, use
/// [`TryLazy`](crate::types::TryLazy).
///
/// ### Algebraic Properties
///
/// `TryTrampoline` forms a monad over the success type `A` (with `E` fixed):
/// - `TryTrampoline::ok(a).bind(f).evaluate() == f(a).evaluate()` (left identity).
/// - `task.bind(TryTrampoline::ok).evaluate() == task.evaluate()` (right identity).
/// - `task.bind(f).bind(g).evaluate() == task.bind(|a| f(a).bind(g)).evaluate()` (associativity).
///
/// On the error channel, `bind` short-circuits: if the computation produces `Err(e)`,
/// the continuation `f` is never called and the error propagates directly.
///
/// ### Limitations
///
/// **`'static` constraint**: Both `A` and `E` must be `'static` because the
/// underlying [`Trampoline`] uses [`Free<ThunkBrand, A>`](crate::types::Free),
/// which erases types via [`Box<dyn Any>`] and therefore requires `'static`.
/// For fallible deferred computation with borrowed references and lifetime
/// polymorphism, use [`TryThunk`](crate::types::TryThunk).
///
/// **No HKT brand**: `TryTrampoline` does not have a corresponding brand type.
/// The `'static` constraint inherited from `Free` makes it impossible to
/// implement the `Kind` trait, which requires lifetime polymorphism (`for<'a>`).
/// Use [`TryThunk`](crate::types::TryThunk) when HKT integration is needed.
///
/// **`!Send`**: `TryTrampoline` is not `Send` because the underlying
/// [`Thunk`](crate::types::Thunk) stores a `Box<dyn FnOnce()>` without a `Send`
/// bound. For thread-safe fallible deferred computation, use
/// [`TrySendThunk`](crate::types::TrySendThunk) (not stack-safe) or
/// [`ArcTryLazy`](crate::types::ArcTryLazy) (memoized).
///
/// **Not memoized**: Each call to [`evaluate`](TryTrampoline::evaluate) re-runs
/// the entire computation. For memoized fallible computation, wrap in
/// [`TryLazy`](crate::types::TryLazy).
///
/// # Drop behavior
///
/// Dropping a `TryTrampoline` dismantles its inner
/// [`Trampoline<Result<A, E>>`](Trampoline) chain iteratively. Each suspended
/// thunk in the chain is evaluated during drop to access the next node. Be aware
/// that dropping a partially-evaluated `TryTrampoline` may trigger deferred
/// computations.
#[document_type_parameters("The type of the success value.", "The type of the error value.")]
///
pub struct TryTrampoline<A: 'static, E: 'static>(
/// The internal `Trampoline` wrapping a `Result`.
Trampoline<Result<A, E>>,
);
#[document_type_parameters("The type of the success value.", "The type of the error value.")]
#[document_parameters("The fallible trampoline computation.")]
impl<A: 'static, E: 'static> TryTrampoline<A, E> {
/// Creates a successful `TryTrampoline`.
#[document_signature]
///
#[document_parameters("The success value.")]
///
#[document_returns("A `TryTrampoline` representing success.")]
///
#[document_examples]
///
/// ```
/// use fp_library::types::*;
///
/// let task: TryTrampoline<i32, String> = TryTrampoline::ok(42);
/// assert_eq!(task.evaluate(), Ok(42));
/// ```
#[inline]
pub fn ok(a: A) -> Self {
TryTrampoline(Trampoline::pure(Ok(a)))
}
/// Creates a successful `TryTrampoline`.
///
/// This is an alias for [`ok`](TryTrampoline::ok), provided for consistency
/// with other types in the library.
#[document_signature]
///
#[document_parameters("The success value.")]
///
#[document_returns("A `TryTrampoline` representing success.")]
///
#[document_examples]
///
/// ```
/// use fp_library::types::*;
///
/// let task: TryTrampoline<i32, String> = TryTrampoline::pure(42);
/// assert_eq!(task.evaluate(), Ok(42));
/// ```
pub fn pure(a: A) -> Self {
Self::ok(a)
}
/// Unwraps the newtype to expose the inner `Trampoline<Result<A, E>>`.
#[document_signature]
///
#[document_returns("The inner `Trampoline<Result<A, E>>`.")]
///
#[document_examples]
///
/// ```
/// use fp_library::types::*;
///
/// let task: TryTrampoline<i32, String> = TryTrampoline::ok(42);
/// let inner: Trampoline<Result<i32, String>> = task.into_inner();
/// assert_eq!(inner.evaluate(), Ok(42));
/// ```
pub fn into_inner(self) -> Trampoline<Result<A, E>> {
self.0
}
/// Creates a failed `TryTrampoline`.
#[document_signature]
///
#[document_parameters("The error value.")]
///
#[document_returns("A `TryTrampoline` representing failure.")]
///
#[document_examples]
///
/// ```
/// use fp_library::types::*;
///
/// let task: TryTrampoline<i32, String> = TryTrampoline::err("error".to_string());
/// assert_eq!(task.evaluate(), Err("error".to_string()));
/// ```
#[inline]
pub fn err(e: E) -> Self {
TryTrampoline(Trampoline::pure(Err(e)))
}
/// Creates a lazy `TryTrampoline` that may fail.
#[document_signature]
///
#[document_parameters("The closure to execute.")]
///
#[document_returns("A `TryTrampoline` that executes `f` when run.")]
///
#[document_examples]
///
/// ```
/// use fp_library::types::*;
///
/// let task: TryTrampoline<i32, String> = TryTrampoline::new(|| Ok(42));
/// assert_eq!(task.evaluate(), Ok(42));
/// ```
#[inline]
pub fn new(f: impl FnOnce() -> Result<A, E> + 'static) -> Self {
TryTrampoline(Trampoline::new(f))
}
/// Defers the construction of a `TryTrampoline`.
///
/// Use this for stack-safe recursion.
#[document_signature]
///
#[document_parameters("A thunk that returns the next step.")]
///
#[document_returns("A `TryTrampoline` that executes `f` to get the next step.")]
///
#[document_examples]
///
/// Stack-safe recursion:
///
/// ```
/// use fp_library::types::*;
///
/// fn factorial(
/// n: i32,
/// acc: i32,
/// ) -> TryTrampoline<i32, String> {
/// if n < 0 {
/// TryTrampoline::err("Negative input".to_string())
/// } else if n == 0 {
/// TryTrampoline::ok(acc)
/// } else {
/// TryTrampoline::defer(move || factorial(n - 1, n * acc))
/// }
/// }
///
/// let task = factorial(5, 1);
/// assert_eq!(task.evaluate(), Ok(120));
/// ```
///
/// ```
/// use fp_library::types::*;
///
/// let task: TryTrampoline<i32, String> = TryTrampoline::defer(|| TryTrampoline::ok(42));
/// assert_eq!(task.evaluate(), Ok(42));
/// ```
#[inline]
pub fn defer(f: impl FnOnce() -> TryTrampoline<A, E> + 'static) -> Self {
TryTrampoline(Trampoline::defer(move || f().0))
}
/// Maps over the success value.
#[document_signature]
///
#[document_type_parameters("The type of the new success value.")]
///
#[document_parameters("The function to apply to the success value.")]
///
#[document_returns("A new `TryTrampoline` with the transformed success value.")]
///
#[document_examples]
///
/// ```
/// use fp_library::types::*;
///
/// let task: TryTrampoline<i32, String> = TryTrampoline::ok(10).map(|x| x * 2);
/// assert_eq!(task.evaluate(), Ok(20));
/// ```
#[inline]
pub fn map<B: 'static>(
self,
func: impl FnOnce(A) -> B + 'static,
) -> TryTrampoline<B, E> {
TryTrampoline(self.0.map(|result| result.map(func)))
}
/// Maps over the error value.
#[document_signature]
///
#[document_type_parameters("The type of the new error value.")]
///
#[document_parameters("The function to apply to the error value.")]
///
#[document_returns("A new `TryTrampoline` with the transformed error value.")]
///
#[document_examples]
///
/// ```
/// use fp_library::types::*;
///
/// let task: TryTrampoline<i32, String> =
/// TryTrampoline::err("error".to_string()).map_err(|e| e.to_uppercase());
/// assert_eq!(task.evaluate(), Err("ERROR".to_string()));
/// ```
#[inline]
pub fn map_err<E2: 'static>(
self,
func: impl FnOnce(E) -> E2 + 'static,
) -> TryTrampoline<A, E2> {
TryTrampoline(self.0.map(|result| result.map_err(func)))
}
/// Maps over both the success and error values simultaneously.
#[document_signature]
///
#[document_type_parameters(
"The type of the new success value.",
"The type of the new error value."
)]
///
#[document_parameters(
"The function to apply to the success value.",
"The function to apply to the error value."
)]
///
#[document_returns("A new `TryTrampoline` with both sides transformed.")]
///
#[document_examples]
///
/// ```
/// use fp_library::types::*;
///
/// let ok_task: TryTrampoline<i32, String> = TryTrampoline::ok(10);
/// let mapped = ok_task.bimap(|x| x * 2, |e| e.len());
/// assert_eq!(mapped.evaluate(), Ok(20));
///
/// let err_task: TryTrampoline<i32, String> = TryTrampoline::err("hello".to_string());
/// let mapped = err_task.bimap(|x| x * 2, |e| e.len());
/// assert_eq!(mapped.evaluate(), Err(5));
/// ```
#[inline]
pub fn bimap<B: 'static, F: 'static>(
self,
f: impl FnOnce(A) -> B + 'static,
g: impl FnOnce(E) -> F + 'static,
) -> TryTrampoline<B, F> {
TryTrampoline(self.0.map(|result| match result {
Ok(a) => Ok(f(a)),
Err(e) => Err(g(e)),
}))
}
/// Chains fallible computations.
#[document_signature]
///
#[document_type_parameters("The type of the new success value.")]
///
#[document_parameters("The function to apply to the success value.")]
///
#[document_returns("A new `TryTrampoline` that chains `f` after this task.")]
///
#[document_examples]
///
/// ```
/// use fp_library::types::*;
///
/// let task: TryTrampoline<i32, String> = TryTrampoline::ok(10).bind(|x| TryTrampoline::ok(x * 2));
/// assert_eq!(task.evaluate(), Ok(20));
/// ```
#[inline]
pub fn bind<B: 'static>(
self,
f: impl FnOnce(A) -> TryTrampoline<B, E> + 'static,
) -> TryTrampoline<B, E> {
TryTrampoline(self.0.bind(|result| match result {
Ok(a) => f(a).0,
Err(e) => Trampoline::pure(Err(e)),
}))
}
/// Recovers from an error.
#[document_signature]
///
#[document_parameters("The function to apply to the error value.")]
///
#[document_returns("A new `TryTrampoline` that attempts to recover from failure.")]
///
#[document_examples]
///
/// ```
/// use fp_library::types::*;
///
/// let task: TryTrampoline<i32, String> =
/// TryTrampoline::err("error".to_string()).catch(|_| TryTrampoline::ok(42));
/// assert_eq!(task.evaluate(), Ok(42));
/// ```
#[inline]
pub fn catch(
self,
f: impl FnOnce(E) -> TryTrampoline<A, E> + 'static,
) -> Self {
TryTrampoline(self.0.bind(|result| match result {
Ok(a) => Trampoline::pure(Ok(a)),
Err(e) => f(e).0,
}))
}
/// Recovers from an error using a fallible recovery function that may produce a different error type.
///
/// Unlike [`catch`](TryTrampoline::catch), `catch_with` allows the recovery function to return a
/// `TryTrampoline` with a different error type `E2`. On success, the value is passed through
/// unchanged. On failure, the recovery function is applied to the error value and its
/// resulting `TryTrampoline` is composed via `bind`, preserving stack safety through deeply chained recovery operations.
#[document_signature]
///
#[document_type_parameters("The error type produced by the recovery computation.")]
///
#[document_parameters("The monadic recovery function applied to the error value.")]
///
#[document_returns(
"A new `TryTrampoline` that either passes through the success value or uses the result of the recovery computation."
)]
///
#[document_examples]
///
/// ```
/// use fp_library::types::*;
///
/// let recovered: TryTrampoline<i32, i32> =
/// TryTrampoline::<i32, &str>::err("error").catch_with(|_| TryTrampoline::err(42));
/// assert_eq!(recovered.evaluate(), Err(42));
///
/// let ok: TryTrampoline<i32, i32> =
/// TryTrampoline::<i32, &str>::ok(1).catch_with(|_| TryTrampoline::err(42));
/// assert_eq!(ok.evaluate(), Ok(1));
/// ```
#[inline]
pub fn catch_with<E2: 'static>(
self,
f: impl FnOnce(E) -> TryTrampoline<A, E2> + 'static,
) -> TryTrampoline<A, E2> {
TryTrampoline(self.0.bind(move |result| match result {
Ok(a) => Trampoline::pure(Ok(a)),
Err(e) => f(e).0,
}))
}
/// Combines two `TryTrampoline`s, running both and combining results.
///
/// Short-circuits on error: if `self` fails, `other` is never evaluated.
#[document_signature]
///
#[document_type_parameters(
"The type of the second computation's success value.",
"The type of the combined result."
)]
///
#[document_parameters("The second computation.", "The function to combine the results.")]
///
#[document_returns("A new `TryTrampoline` producing the combined result.")]
///
#[document_examples]
///
/// ```
/// use fp_library::types::*;
///
/// let t1: TryTrampoline<i32, String> = TryTrampoline::ok(10);
/// let t2: TryTrampoline<i32, String> = TryTrampoline::ok(20);
/// let t3 = t1.lift2(t2, |a, b| a + b);
/// assert_eq!(t3.evaluate(), Ok(30));
/// ```
#[inline]
pub fn lift2<B: 'static, C: 'static>(
self,
other: TryTrampoline<B, E>,
f: impl FnOnce(A, B) -> C + 'static,
) -> TryTrampoline<C, E> {
self.bind(move |a| other.map(move |b| f(a, b)))
}
/// Sequences two `TryTrampoline`s, discarding the first result.
///
/// Short-circuits on error: if `self` fails, `other` is never evaluated.
#[document_signature]
///
#[document_type_parameters("The type of the second computation's success value.")]
///
#[document_parameters("The second computation.")]
///
#[document_returns(
"A new `TryTrampoline` that runs both computations and returns the result of the second."
)]
///
#[document_examples]
///
/// ```
/// use fp_library::types::*;
///
/// let t1: TryTrampoline<i32, String> = TryTrampoline::ok(10);
/// let t2: TryTrampoline<i32, String> = TryTrampoline::ok(20);
/// let t3 = t1.then(t2);
/// assert_eq!(t3.evaluate(), Ok(20));
/// ```
#[inline]
pub fn then<B: 'static>(
self,
other: TryTrampoline<B, E>,
) -> TryTrampoline<B, E> {
self.bind(move |_| other)
}
/// Stack-safe tail recursion for fallible computations.
///
/// The step function returns `TryTrampoline<ControlFlow<A, S>, E>`, and the
/// loop short-circuits on error.
///
/// # Clone Bound
///
/// The function `f` must implement `Clone` because each iteration
/// of the recursion may need its own copy. Most closures naturally
/// implement `Clone` when all their captures implement `Clone`.
///
/// For closures that don't implement `Clone`, use `arc_tail_rec_m`
/// which wraps the closure in `Arc` internally.
#[document_signature]
///
#[document_type_parameters("The type of the state.")]
///
#[document_parameters(
"The function that performs one step of the recursion.",
"The initial state."
)]
///
#[document_returns("A `TryTrampoline` that performs the recursion.")]
#[document_examples]
///
/// ```
/// use {
/// core::ops::ControlFlow,
/// fp_library::types::TryTrampoline,
/// };
///
/// // Fallible factorial using tail recursion
/// fn factorial(n: i32) -> TryTrampoline<i32, String> {
/// TryTrampoline::tail_rec_m(
/// |(n, acc)| {
/// if n < 0 {
/// TryTrampoline::err("Negative input".to_string())
/// } else if n <= 1 {
/// TryTrampoline::ok(ControlFlow::Break(acc))
/// } else {
/// TryTrampoline::ok(ControlFlow::Continue((n - 1, n * acc)))
/// }
/// },
/// (n, 1),
/// )
/// }
///
/// assert_eq!(factorial(5).evaluate(), Ok(120));
/// assert_eq!(factorial(-1).evaluate(), Err("Negative input".to_string()));
/// ```
pub fn tail_rec_m<S: 'static>(
f: impl Fn(S) -> TryTrampoline<ControlFlow<A, S>, E> + Clone + 'static,
initial: S,
) -> Self {
fn go<S: 'static, A: 'static, E: 'static>(
f: impl Fn(S) -> TryTrampoline<ControlFlow<A, S>, E> + Clone + 'static,
s: S,
) -> Trampoline<Result<A, E>> {
Trampoline::defer(move || {
let result = f(s);
result.0.bind(move |r| match r {
Ok(ControlFlow::Continue(next)) => go(f, next),
Ok(ControlFlow::Break(a)) => Trampoline::pure(Ok(a)),
Err(e) => Trampoline::pure(Err(e)),
})
})
}
TryTrampoline(go(f, initial))
}
/// Arc-wrapped version of `tail_rec_m` for non-Clone closures.
///
/// Use this when your closure captures non-Clone state.
#[document_signature]
///
#[document_type_parameters("The type of the state.")]
///
#[document_parameters(
"The function that performs one step of the recursion.",
"The initial state."
)]
///
#[document_returns("A `TryTrampoline` that performs the recursion.")]
#[document_examples]
///
/// ```
/// use {
/// core::ops::ControlFlow,
/// fp_library::types::TryTrampoline,
/// std::sync::{
/// Arc,
/// atomic::{
/// AtomicUsize,
/// Ordering,
/// },
/// },
/// };
///
/// // Closure captures non-Clone state
/// let counter = Arc::new(AtomicUsize::new(0));
/// let counter_clone = Arc::clone(&counter);
/// let task: TryTrampoline<i32, String> = TryTrampoline::arc_tail_rec_m(
/// move |n| {
/// counter_clone.fetch_add(1, Ordering::SeqCst);
/// if n == 0 {
/// TryTrampoline::ok(ControlFlow::Break(0))
/// } else {
/// TryTrampoline::ok(ControlFlow::Continue(n - 1))
/// }
/// },
/// 100,
/// );
/// assert_eq!(task.evaluate(), Ok(0));
/// assert_eq!(counter.load(Ordering::SeqCst), 101);
/// ```
pub fn arc_tail_rec_m<S: 'static>(
f: impl Fn(S) -> TryTrampoline<ControlFlow<A, S>, E> + 'static,
initial: S,
) -> Self {
use std::sync::Arc;
let f = Arc::new(f);
let wrapper = move |s: S| {
let f = Arc::clone(&f);
f(s)
};
Self::tail_rec_m(wrapper, initial)
}
/// Runs the computation, returning the result.
#[document_signature]
///
#[document_returns("The result of the computation.")]
///
#[document_examples]
///
/// ```
/// use fp_library::types::*;
///
/// let task: TryTrampoline<i32, String> = TryTrampoline::ok(42);
/// assert_eq!(task.evaluate(), Ok(42));
/// ```
#[inline]
pub fn evaluate(self) -> Result<A, E> {
self.0.evaluate()
}
/// Combines two `TryTrampoline` values using the inner type's [`Semigroup`].
///
/// Both computations are evaluated. If both succeed, their results are
/// combined via [`Semigroup::append`]. If either fails, the first error
/// is propagated (short-circuiting on the left).
#[document_signature]
///
#[document_parameters(
"The second `TryTrampoline` whose result will be combined with this one."
)]
///
#[document_returns("A new `TryTrampoline` producing the combined result.")]
///
#[document_examples]
///
/// ```
/// use fp_library::types::*;
///
/// let t1: TryTrampoline<Vec<i32>, String> = TryTrampoline::ok(vec![1, 2]);
/// let t2: TryTrampoline<Vec<i32>, String> = TryTrampoline::ok(vec![3, 4]);
/// assert_eq!(t1.append(t2).evaluate(), Ok(vec![1, 2, 3, 4]));
/// ```
#[inline]
pub fn append(
self,
other: TryTrampoline<A, E>,
) -> TryTrampoline<A, E>
where
A: Semigroup + 'static, {
self.lift2(other, Semigroup::append)
}
/// Creates a `TryTrampoline` that produces the identity element for the given [`Monoid`].
#[document_signature]
///
#[document_returns(
"A `TryTrampoline` producing the monoid identity element wrapped in `Ok`."
)]
///
#[document_examples]
///
/// ```
/// use fp_library::types::*;
///
/// let t: TryTrampoline<Vec<i32>, String> = TryTrampoline::empty();
/// assert_eq!(t.evaluate(), Ok(Vec::<i32>::new()));
/// ```
#[inline]
pub fn empty() -> TryTrampoline<A, E>
where
A: Monoid + 'static, {
TryTrampoline::ok(Monoid::empty())
}
/// Converts this `TryTrampoline` into a memoized [`RcTryLazy`](crate::types::RcTryLazy) value.
///
/// The computation will be evaluated at most once; subsequent accesses
/// return the cached result.
#[document_signature]
///
#[document_returns(
"A memoized `RcTryLazy` value that evaluates this trampoline on first access."
)]
///
#[document_examples]
///
/// ```
/// use fp_library::types::*;
///
/// let task: TryTrampoline<i32, String> = TryTrampoline::ok(42);
/// let lazy = task.into_rc_try_lazy();
/// assert_eq!(lazy.evaluate(), Ok(&42));
/// ```
#[inline]
pub fn into_rc_try_lazy(self) -> crate::types::RcTryLazy<'static, A, E> {
crate::types::RcTryLazy::from(self)
}
/// Evaluates this `TryTrampoline` and wraps the result in a thread-safe [`ArcTryLazy`](crate::types::ArcTryLazy).
///
/// The trampoline is evaluated eagerly because its inner closures are
/// not `Send`. The result is stored in an `ArcTryLazy` for thread-safe sharing.
#[document_signature]
///
#[document_returns("A thread-safe `ArcTryLazy` containing the eagerly evaluated result.")]
///
#[document_examples]
///
/// ```
/// use fp_library::types::*;
///
/// let task: TryTrampoline<i32, String> = TryTrampoline::ok(42);
/// let lazy = task.into_arc_try_lazy();
/// assert_eq!(lazy.evaluate(), Ok(&42));
/// ```
#[inline]
pub fn into_arc_try_lazy(self) -> crate::types::ArcTryLazy<'static, A, E>
where
A: Send + Sync,
E: Send + Sync, {
crate::types::ArcTryLazy::from(self)
}
/// Peels off one layer of the trampoline.
///
/// Returns `Ok(result)` if the computation has completed (where `result` is
/// itself a `Result<A, E>` indicating success or failure), or
/// `Err(thunk)` if the computation is suspended. Evaluating the returned
/// [`Thunk`] yields the next `TryTrampoline` step.
///
/// This is useful for implementing custom interpreters or drivers that need
/// to interleave trampoline steps with other logic (e.g., logging, resource
/// cleanup, cooperative scheduling).
#[document_signature]
///
#[document_returns(
"`Ok(result)` if the computation is finished, `Err(thunk)` if it is suspended."
)]
///
#[document_examples]
///
/// ```
/// use fp_library::types::*;
///
/// // A completed TryTrampoline resumes immediately.
/// let t: TryTrampoline<i32, String> = TryTrampoline::ok(42);
/// assert_eq!(t.resume().unwrap(), Ok(42));
///
/// // A deferred TryTrampoline is suspended.
/// let t: TryTrampoline<i32, String> = TryTrampoline::defer(|| TryTrampoline::ok(99));
/// match t.resume() {
/// Ok(_) => panic!("expected suspension"),
/// Err(thunk) => {
/// let next = thunk.evaluate();
/// assert_eq!(next.resume().unwrap(), Ok(99));
/// }
/// }
/// ```
pub fn resume(self) -> Result<Result<A, E>, Thunk<'static, TryTrampoline<A, E>>> {
match self.0.resume() {
Ok(result) => Ok(result),
Err(thunk) => Err(thunk.map(TryTrampoline)),
}
}
}
#[document_type_parameters("The type of the computed value.", "The type of the error value.")]
impl<A: 'static, E: 'static> TryTrampoline<A, E> {
/// Creates a `TryTrampoline` that catches unwinds (panics), converting the
/// panic payload using a custom conversion function.
///
/// The closure `f` is executed when the trampoline is evaluated. If `f`
/// panics, the panic payload is passed to `handler` to produce the
/// error value. If `f` returns normally, the value is wrapped in `Ok`.
#[document_signature]
///
#[document_parameters(
"The closure that might panic.",
"The function that converts a panic payload into the error type."
)]
///
#[document_returns(
"A new `TryTrampoline` instance where panics are converted to `Err(E)` via the handler."
)]
///
#[document_examples]
///
/// ```
/// use fp_library::types::*;
///
/// let task = TryTrampoline::<i32, i32>::catch_unwind_with(
/// || {
/// if true {
/// panic!("oops")
/// }
/// 42
/// },
/// |_payload| -1,
/// );
/// assert_eq!(task.evaluate(), Err(-1));
/// ```
pub fn catch_unwind_with(
f: impl FnOnce() -> A + std::panic::UnwindSafe + 'static,
handler: impl FnOnce(Box<dyn std::any::Any + Send>) -> E + 'static,
) -> Self {
Self::new(move || std::panic::catch_unwind(f).map_err(handler))
}
}
#[document_type_parameters("The type of the computed value.")]
impl<A: 'static> TryTrampoline<A, String> {
/// Creates a `TryTrampoline` that catches unwinds (panics).
///
/// The closure is executed when the trampoline is evaluated. If the closure
/// panics, the panic payload is converted to a `String` error. If the
/// closure returns normally, the value is wrapped in `Ok`.
///
/// This is a convenience wrapper around [`catch_unwind_with`](TryTrampoline::catch_unwind_with)
/// that uses the default panic payload to string conversion.
#[document_signature]
///
#[document_parameters("The closure that might panic.")]
///
#[document_returns(
"A new `TryTrampoline` instance where panics are converted to `Err(String)`."
)]
///
#[document_examples]
///
/// ```
/// use fp_library::types::*;
///
/// let task = TryTrampoline::<i32, String>::catch_unwind(|| {
/// if true {
/// panic!("oops")
/// }
/// 42
/// });
/// assert_eq!(task.evaluate(), Err("oops".to_string()));
/// ```
pub fn catch_unwind(f: impl FnOnce() -> A + std::panic::UnwindSafe + 'static) -> Self {
Self::catch_unwind_with(f, crate::utils::panic_payload_to_string)
}
}
#[document_type_parameters("The type of the success value.", "The type of the error value.")]
impl<A, E> From<Trampoline<A>> for TryTrampoline<A, E>
where
A: 'static,
E: 'static,
{
#[document_signature]
#[document_parameters("The trampoline computation to convert.")]
#[document_returns("A new `TryTrampoline` instance that wraps the trampoline.")]
#[document_examples]
///
/// ```
/// use fp_library::types::*;
/// let task = Trampoline::pure(42);
/// let try_task: TryTrampoline<i32, ()> = TryTrampoline::from(task);
/// assert_eq!(try_task.evaluate(), Ok(42));
/// ```
fn from(task: Trampoline<A>) -> Self {
TryTrampoline(task.map(Ok))
}
}
#[document_type_parameters(
"The type of the success value.",
"The type of the error value.",
"The memoization configuration."
)]
impl<A, E, Config> From<Lazy<'static, A, Config>> for TryTrampoline<A, E>
where
A: Clone + 'static,
E: 'static,
Config: LazyConfig,
{
/// Converts a [`Lazy`] value into a [`TryTrampoline`] that defers evaluation.
///
/// The `Lazy` is not forced at conversion time; instead, the `TryTrampoline`
/// defers evaluation until it is run. This is the same deferred semantics as
/// [`From<TryLazy>`](#impl-From<TryLazy<'static,+A,+E,+Config>>-for-TryTrampoline<A,+E>).
#[document_signature]
#[document_parameters("The lazy value to convert.")]
#[document_returns("A new `TryTrampoline` instance that wraps the lazy value.")]
#[document_examples]
///
/// ```
/// use fp_library::types::*;
/// let lazy = Lazy::<_, RcLazyConfig>::pure(42);
/// let try_task: TryTrampoline<i32, ()> = TryTrampoline::from(lazy);
/// assert_eq!(try_task.evaluate(), Ok(42));
/// ```
fn from(memo: Lazy<'static, A, Config>) -> Self {
TryTrampoline(Trampoline::new(move || Ok(memo.evaluate().clone())))
}
}
#[document_type_parameters(
"The type of the success value.",
"The type of the error value.",
"The memoization configuration."
)]
impl<A, E, Config> From<TryLazy<'static, A, E, Config>> for TryTrampoline<A, E>
where
A: Clone + 'static,
E: Clone + 'static,
Config: LazyConfig,
{
/// Converts a [`TryLazy`] value into a [`TryTrampoline`] that defers evaluation.
///
/// This conversion defers forcing the `TryLazy` until the `TryTrampoline` is run.
/// The cost depends on the [`Clone`] implementations of `A` and `E`.
#[document_signature]
#[document_parameters("The fallible lazy value to convert.")]
#[document_returns("A new `TryTrampoline` instance that wraps the fallible lazy value.")]
#[document_examples]
///
/// ```
/// use fp_library::types::*;
/// let lazy = TryLazy::<_, _, RcLazyConfig>::new(|| Ok::<i32, ()>(42));
/// let try_task = TryTrampoline::from(lazy);
/// assert_eq!(try_task.evaluate(), Ok(42));
/// ```
fn from(memo: TryLazy<'static, A, E, Config>) -> Self {
TryTrampoline(Trampoline::new(move || {
let result = memo.evaluate();
match result {
Ok(a) => Ok(a.clone()),
Err(e) => Err(e.clone()),
}
}))
}
}
#[document_type_parameters("The type of the success value.", "The type of the error value.")]
impl<A, E> From<crate::types::TryThunk<'static, A, E>> for TryTrampoline<A, E>
where
A: 'static,
E: 'static,
{
/// Converts a `'static` [`TryThunk`](crate::types::TryThunk) into a `TryTrampoline`.
///
/// This lifts a non-stack-safe `TryThunk` into the stack-safe `TryTrampoline`
/// execution model. The resulting `TryTrampoline` evaluates the thunk when run.
#[document_signature]
#[document_parameters("The fallible thunk to convert.")]
#[document_returns("A new `TryTrampoline` instance that evaluates the thunk.")]
#[document_examples]
///
/// ```
/// use fp_library::types::*;
/// let thunk = TryThunk::new(|| Ok::<i32, String>(42));
/// let task = TryTrampoline::from(thunk);
/// assert_eq!(task.evaluate(), Ok(42));
/// ```
fn from(thunk: crate::types::TryThunk<'static, A, E>) -> Self {
TryTrampoline::new(move || thunk.evaluate())
}
}
#[document_type_parameters("The type of the success value.", "The type of the error value.")]
impl<A, E> From<Result<A, E>> for TryTrampoline<A, E>
where
A: 'static,
E: 'static,
{
#[document_signature]
#[document_parameters("The result to convert.")]
#[document_returns("A new `TryTrampoline` instance that produces the result.")]
#[document_examples]
///
/// ```
/// use fp_library::types::*;
/// let ok_task: TryTrampoline<i32, String> = TryTrampoline::from(Ok(42));
/// assert_eq!(ok_task.evaluate(), Ok(42));
///
/// let err_task: TryTrampoline<i32, String> = TryTrampoline::from(Err("error".to_string()));
/// assert_eq!(err_task.evaluate(), Err("error".to_string()));
/// ```
fn from(result: Result<A, E>) -> Self {
TryTrampoline(Trampoline::pure(result))
}
}
#[document_type_parameters("The type of the success value.", "The type of the error value.")]
impl<A, E> Deferrable<'static> for TryTrampoline<A, E>
where
A: 'static,
E: 'static,
{
/// Creates a value from a computation that produces the value.
#[document_signature]
///
#[document_parameters("A thunk that produces the value.")]
///
#[document_returns("The deferred value.")]
///
#[document_examples]
///
/// ```
/// use fp_library::{
/// brands::*,
/// classes::Deferrable,
/// functions::*,
/// types::*,
/// };
///
/// let task: TryTrampoline<i32, String> = Deferrable::defer(|| TryTrampoline::ok(42));
/// assert_eq!(task.evaluate(), Ok(42));
/// ```
fn defer(f: impl FnOnce() -> Self + 'static) -> Self
where
Self: Sized, {
TryTrampoline(Trampoline::defer(move || f().0))
}
}
#[document_type_parameters("The type of the success value.", "The type of the error value.")]
impl<A, E> Semigroup for TryTrampoline<A, E>
where
A: Semigroup + 'static,
E: 'static,
{
/// Combines two `TryTrampoline` computations.
///
/// Both computations are evaluated; if both succeed, their results are combined
/// using the inner `Semigroup`. If either fails, the first error is propagated.
#[document_signature]
///
#[document_parameters(
"The first `TryTrampoline` computation.",
"The second `TryTrampoline` computation."
)]
///
#[document_returns(
"A `TryTrampoline` that evaluates both and combines the results, or propagates the first error."
)]
///
#[document_examples]
///
/// ```
/// use fp_library::{
/// classes::Semigroup,
/// types::*,
/// };
///
/// let a: TryTrampoline<String, ()> = TryTrampoline::ok("hello".to_string());
/// let b: TryTrampoline<String, ()> = TryTrampoline::ok(" world".to_string());
/// let combined = Semigroup::append(a, b);
/// assert_eq!(combined.evaluate(), Ok("hello world".to_string()));
/// ```
fn append(
a: Self,
b: Self,
) -> Self {
a.lift2(b, Semigroup::append)
}
}
#[document_type_parameters("The type of the success value.", "The type of the error value.")]
impl<A, E> Monoid for TryTrampoline<A, E>
where
A: Monoid + 'static,
E: 'static,
{
/// Returns a `TryTrampoline` containing the monoidal identity.
#[document_signature]
///
#[document_returns("A `TryTrampoline` that succeeds with the monoidal identity element.")]
///
#[document_examples]
///
/// ```
/// use fp_library::{
/// classes::Monoid,
/// types::*,
/// };
///
/// let e: TryTrampoline<String, ()> = Monoid::empty();
/// assert_eq!(e.evaluate(), Ok(String::new()));
/// ```
fn empty() -> Self {
TryTrampoline::ok(A::empty())
}
}
#[document_type_parameters("The type of the success value.", "The type of the error value.")]
#[document_parameters("The try-trampoline to format.")]
impl<A: 'static, E: 'static> fmt::Debug for TryTrampoline<A, E> {
/// Formats the try-trampoline without evaluating it.
#[document_signature]
#[document_parameters("The formatter.")]
#[document_returns("The formatting result.")]
#[document_examples]
///
/// ```
/// use fp_library::types::*;
/// let task = TryTrampoline::<i32, ()>::ok(42);
/// assert_eq!(format!("{:?}", task), "TryTrampoline(<unevaluated>)");
/// ```
fn fmt(
&self,
f: &mut fmt::Formatter<'_>,
) -> fmt::Result {
f.write_str("TryTrampoline(<unevaluated>)")
}
}
}
pub use inner::*;
#[cfg(test)]
#[expect(
clippy::unwrap_used,
clippy::panic,
reason = "Tests use panicking operations for brevity and clarity"
)]
mod tests {
use {
super::*,
crate::types::Trampoline,
core::ops::ControlFlow,
quickcheck_macros::quickcheck,
};
/// Tests `TryTrampoline::ok`.
///
/// Verifies that `ok` creates a successful task.
#[test]
fn test_try_task_ok() {
let task: TryTrampoline<i32, String> = TryTrampoline::ok(42);
assert_eq!(task.evaluate(), Ok(42));
}
/// Tests `TryTrampoline::err`.
///
/// Verifies that `err` creates a failed task.
#[test]
fn test_try_task_err() {
let task: TryTrampoline<i32, String> = TryTrampoline::err("error".to_string());
assert_eq!(task.evaluate(), Err("error".to_string()));
}
/// Tests `TryTrampoline::map`.
///
/// Verifies that `map` transforms the success value.
#[test]
fn test_try_task_map() {
let task: TryTrampoline<i32, String> = TryTrampoline::ok(10).map(|x| x * 2);
assert_eq!(task.evaluate(), Ok(20));
}
/// Tests `TryTrampoline::map_err`.
///
/// Verifies that `map_err` transforms the error value.
#[test]
fn test_try_task_map_err() {
let task: TryTrampoline<i32, String> =
TryTrampoline::err("error".to_string()).map_err(|e| e.to_uppercase());
assert_eq!(task.evaluate(), Err("ERROR".to_string()));
}
/// Tests `TryTrampoline::bind`.
///
/// Verifies that `bind` chains computations.
#[test]
fn test_try_task_bind() {
let task: TryTrampoline<i32, String> =
TryTrampoline::ok(10).bind(|x| TryTrampoline::ok(x * 2));
assert_eq!(task.evaluate(), Ok(20));
}
/// Tests `TryTrampoline::or_else`.
///
/// Verifies that `or_else` recovers from failure.
#[test]
fn test_try_task_or_else() {
let task: TryTrampoline<i32, String> =
TryTrampoline::err("error".to_string()).catch(|_| TryTrampoline::ok(42));
assert_eq!(task.evaluate(), Ok(42));
}
/// Tests `TryTrampoline::catch_with`.
///
/// Verifies that `catch_with` recovers from failure using a different error type.
#[test]
fn test_catch_with_recovers() {
let task: TryTrampoline<i32, i32> = TryTrampoline::<i32, String>::err("error".to_string())
.catch_with(|_| TryTrampoline::err(42));
assert_eq!(task.evaluate(), Err(42));
}
/// Tests `TryTrampoline::catch_with` when the computation succeeds.
///
/// Verifies that success values pass through unchanged.
#[test]
fn test_catch_with_success_passes_through() {
let task: TryTrampoline<i32, i32> =
TryTrampoline::<i32, String>::ok(1).catch_with(|_| TryTrampoline::err(42));
assert_eq!(task.evaluate(), Ok(1));
}
/// Tests `TryTrampoline::new`.
///
/// Verifies that `new` creates a lazy task.
#[test]
fn test_try_task_new() {
let task: TryTrampoline<i32, String> = TryTrampoline::new(|| Ok(42));
assert_eq!(task.evaluate(), Ok(42));
}
/// Tests `TryTrampoline::pure`.
///
/// Verifies that `pure` creates a successful task.
#[test]
fn test_try_trampoline_pure() {
let task: TryTrampoline<i32, String> = TryTrampoline::pure(42);
assert_eq!(task.evaluate(), Ok(42));
}
/// Tests `TryTrampoline::into_inner`.
///
/// Verifies that `into_inner` unwraps the newtype.
#[test]
fn test_try_trampoline_into_inner() {
let task: TryTrampoline<i32, String> = TryTrampoline::ok(42);
let inner: Trampoline<Result<i32, String>> = task.into_inner();
assert_eq!(inner.evaluate(), Ok(42));
}
/// Tests `From<Trampoline>`.
#[test]
fn test_try_task_from_task() {
let task = Trampoline::pure(42);
let try_task: TryTrampoline<i32, String> = TryTrampoline::from(task);
assert_eq!(try_task.evaluate(), Ok(42));
}
/// Tests `From<Lazy>`.
#[test]
fn test_try_task_from_memo() {
use crate::types::ArcLazy;
let memo = ArcLazy::new(|| 42);
let try_task: TryTrampoline<i32, String> = TryTrampoline::from(memo);
assert_eq!(try_task.evaluate(), Ok(42));
}
/// Tests `From<TryLazy>`.
#[test]
fn test_try_task_from_try_memo() {
use crate::types::ArcTryLazy;
let memo = ArcTryLazy::new(|| Ok(42));
let try_task: TryTrampoline<i32, String> = TryTrampoline::from(memo);
assert_eq!(try_task.evaluate(), Ok(42));
}
/// Tests `TryTrampoline::lift2` with two successful values.
///
/// Verifies that `lift2` combines results from both computations.
#[test]
fn test_try_task_lift2_success() {
let t1: TryTrampoline<i32, String> = TryTrampoline::ok(10);
let t2: TryTrampoline<i32, String> = TryTrampoline::ok(20);
let t3 = t1.lift2(t2, |a, b| a + b);
assert_eq!(t3.evaluate(), Ok(30));
}
/// Tests `TryTrampoline::lift2` short-circuits on first error.
///
/// Verifies that if the first computation fails, the second is not evaluated.
#[test]
fn test_try_task_lift2_first_error() {
let t1: TryTrampoline<i32, String> = TryTrampoline::err("first".to_string());
let t2: TryTrampoline<i32, String> = TryTrampoline::ok(20);
let t3 = t1.lift2(t2, |a, b| a + b);
assert_eq!(t3.evaluate(), Err("first".to_string()));
}
/// Tests `TryTrampoline::lift2` propagates second error.
///
/// Verifies that if the second computation fails, the error is propagated.
#[test]
fn test_try_task_lift2_second_error() {
let t1: TryTrampoline<i32, String> = TryTrampoline::ok(10);
let t2: TryTrampoline<i32, String> = TryTrampoline::err("second".to_string());
let t3 = t1.lift2(t2, |a, b| a + b);
assert_eq!(t3.evaluate(), Err("second".to_string()));
}
/// Tests `TryTrampoline::then` with two successful values.
///
/// Verifies that `then` discards the first result and returns the second.
#[test]
fn test_try_task_then_success() {
let t1: TryTrampoline<i32, String> = TryTrampoline::ok(10);
let t2: TryTrampoline<i32, String> = TryTrampoline::ok(20);
let t3 = t1.then(t2);
assert_eq!(t3.evaluate(), Ok(20));
}
/// Tests `TryTrampoline::then` short-circuits on first error.
///
/// Verifies that if the first computation fails, the second is not evaluated.
#[test]
fn test_try_task_then_first_error() {
let t1: TryTrampoline<i32, String> = TryTrampoline::err("first".to_string());
let t2: TryTrampoline<i32, String> = TryTrampoline::ok(20);
let t3 = t1.then(t2);
assert_eq!(t3.evaluate(), Err("first".to_string()));
}
/// Tests `TryTrampoline::then` propagates second error.
///
/// Verifies that if the second computation fails, the error is propagated.
#[test]
fn test_try_task_then_second_error() {
let t1: TryTrampoline<i32, String> = TryTrampoline::ok(10);
let t2: TryTrampoline<i32, String> = TryTrampoline::err("second".to_string());
let t3 = t1.then(t2);
assert_eq!(t3.evaluate(), Err("second".to_string()));
}
/// Tests `TryTrampoline::tail_rec_m` with a factorial computation.
///
/// Verifies both the success and error paths.
#[test]
fn test_try_task_tail_rec_m() {
fn factorial(n: i32) -> TryTrampoline<i32, String> {
TryTrampoline::tail_rec_m(
|(n, acc)| {
if n < 0 {
TryTrampoline::err("Negative input".to_string())
} else if n <= 1 {
TryTrampoline::ok(ControlFlow::Break(acc))
} else {
TryTrampoline::ok(ControlFlow::Continue((n - 1, n * acc)))
}
},
(n, 1),
)
}
assert_eq!(factorial(5).evaluate(), Ok(120));
assert_eq!(factorial(0).evaluate(), Ok(1));
assert_eq!(factorial(1).evaluate(), Ok(1));
}
/// Tests `TryTrampoline::tail_rec_m` error short-circuit.
///
/// Verifies that an error terminates the recursion immediately.
#[test]
fn test_try_task_tail_rec_m_error() {
let task: TryTrampoline<i32, String> = TryTrampoline::tail_rec_m(
|n: i32| {
if n >= 5 {
TryTrampoline::err(format!("too large: {}", n))
} else {
TryTrampoline::ok(ControlFlow::Continue(n + 1))
}
},
0,
);
assert_eq!(task.evaluate(), Err("too large: 5".to_string()));
}
/// Tests `TryTrampoline::tail_rec_m` stack safety.
///
/// Verifies that `tail_rec_m` does not overflow the stack with 100,000+ iterations.
#[test]
fn test_try_task_tail_rec_m_stack_safety() {
let n = 100_000u64;
let task: TryTrampoline<u64, String> = TryTrampoline::tail_rec_m(
|(remaining, acc)| {
if remaining == 0 {
TryTrampoline::ok(ControlFlow::Break(acc))
} else {
TryTrampoline::ok(ControlFlow::Continue((remaining - 1, acc + remaining)))
}
},
(n, 0u64),
);
assert_eq!(task.evaluate(), Ok(n * (n + 1) / 2));
}
/// Tests `TryTrampoline::tail_rec_m` stack safety with error at the end.
///
/// Verifies that error short-circuit works after many successful iterations.
#[test]
fn test_try_task_tail_rec_m_stack_safety_error() {
let n = 100_000u64;
let task: TryTrampoline<u64, String> = TryTrampoline::tail_rec_m(
|remaining| {
if remaining == 0 {
TryTrampoline::err("done iterating".to_string())
} else {
TryTrampoline::ok(ControlFlow::Continue(remaining - 1))
}
},
n,
);
assert_eq!(task.evaluate(), Err("done iterating".to_string()));
}
/// Tests `TryTrampoline::arc_tail_rec_m` with non-Clone closures.
///
/// Verifies that `arc_tail_rec_m` works with closures capturing `Arc<AtomicUsize>`.
#[test]
fn test_try_task_arc_tail_rec_m() {
use std::sync::{
Arc,
atomic::{
AtomicUsize,
Ordering,
},
};
let counter = Arc::new(AtomicUsize::new(0));
let counter_clone = Arc::clone(&counter);
let task: TryTrampoline<i32, String> = TryTrampoline::arc_tail_rec_m(
move |n| {
counter_clone.fetch_add(1, Ordering::SeqCst);
if n == 0 {
TryTrampoline::ok(ControlFlow::Break(0))
} else {
TryTrampoline::ok(ControlFlow::Continue(n - 1))
}
},
10,
);
assert_eq!(task.evaluate(), Ok(0));
assert_eq!(counter.load(Ordering::SeqCst), 11);
}
/// Tests `TryTrampoline::arc_tail_rec_m` error short-circuit.
///
/// Verifies that `arc_tail_rec_m` correctly propagates errors.
#[test]
fn test_try_task_arc_tail_rec_m_error() {
use std::sync::{
Arc,
atomic::{
AtomicUsize,
Ordering,
},
};
let counter = Arc::new(AtomicUsize::new(0));
let counter_clone = Arc::clone(&counter);
let task: TryTrampoline<i32, String> = TryTrampoline::arc_tail_rec_m(
move |n| {
counter_clone.fetch_add(1, Ordering::SeqCst);
if n >= 5 {
TryTrampoline::err(format!("too large: {}", n))
} else {
TryTrampoline::ok(ControlFlow::Continue(n + 1))
}
},
0,
);
assert_eq!(task.evaluate(), Err("too large: 5".to_string()));
// Should have been called 6 times (0, 1, 2, 3, 4, 5)
assert_eq!(counter.load(Ordering::SeqCst), 6);
}
/// Tests `From<TryThunk>` with a successful thunk.
#[test]
fn test_try_task_from_try_thunk_ok() {
use crate::types::TryThunk;
let thunk = TryThunk::new(|| Ok::<i32, String>(42));
let task = TryTrampoline::from(thunk);
assert_eq!(task.evaluate(), Ok(42));
}
/// Tests `From<TryThunk>` with a failed thunk.
#[test]
fn test_try_task_from_try_thunk_err() {
use crate::types::TryThunk;
let thunk = TryThunk::new(|| Err::<i32, String>("error".to_string()));
let task = TryTrampoline::from(thunk);
assert_eq!(task.evaluate(), Err("error".to_string()));
}
/// Tests bidirectional conversion between `TryThunk` and `TryTrampoline`.
///
/// Verifies that a value survives a round-trip through both conversions.
#[test]
fn test_try_thunk_try_trampoline_round_trip() {
use crate::types::TryThunk;
// TryThunk -> TryTrampoline -> TryThunk (Ok case)
let thunk = TryThunk::new(|| Ok::<i32, String>(42));
let tramp = TryTrampoline::from(thunk);
let thunk_back: TryThunk<i32, String> = TryThunk::from(tramp);
assert_eq!(thunk_back.evaluate(), Ok(42));
// TryTrampoline -> TryThunk -> TryTrampoline (Err case)
let tramp = TryTrampoline::err("fail".to_string());
let thunk: TryThunk<i32, String> = TryThunk::from(tramp);
let tramp_back = TryTrampoline::from(thunk);
assert_eq!(tramp_back.evaluate(), Err("fail".to_string()));
}
/// Tests `From<Result>` with `Ok`.
#[test]
fn test_try_task_from_result_ok() {
let task: TryTrampoline<i32, String> = TryTrampoline::from(Ok(42));
assert_eq!(task.evaluate(), Ok(42));
}
/// Tests `From<Result>` with `Err`.
#[test]
fn test_try_task_from_result_err() {
let task: TryTrampoline<i32, String> = TryTrampoline::from(Err("error".to_string()));
assert_eq!(task.evaluate(), Err("error".to_string()));
}
// Tests for !Send types (Rc)
/// Tests that `TryTrampoline` works with `Rc<T>`, a `!Send` type.
///
/// This verifies that the `Send` bound relaxation allows single-threaded
/// stack-safe fallible recursion with reference-counted types.
#[test]
fn test_try_trampoline_with_rc() {
use std::rc::Rc;
let task: TryTrampoline<Rc<i32>, Rc<String>> = TryTrampoline::ok(Rc::new(42));
assert_eq!(*task.evaluate().unwrap(), 42);
}
/// Tests `TryTrampoline::bind` with `Rc<T>`.
///
/// Verifies that `bind` works correctly when value and error types are `!Send`.
#[test]
fn test_try_trampoline_bind_with_rc() {
use std::rc::Rc;
let task: TryTrampoline<Rc<i32>, Rc<String>> =
TryTrampoline::ok(Rc::new(10)).bind(|rc| TryTrampoline::ok(Rc::new(*rc * 2)));
assert_eq!(*task.evaluate().unwrap(), 20);
}
/// Tests `TryTrampoline::tail_rec_m` with `Rc<T>`.
///
/// Verifies that stack-safe fallible recursion works with `!Send` types.
#[test]
fn test_try_trampoline_tail_rec_m_with_rc() {
use std::rc::Rc;
let task: TryTrampoline<Rc<u64>, Rc<String>> = TryTrampoline::tail_rec_m(
|(n, acc): (u64, Rc<u64>)| {
if n == 0 {
TryTrampoline::ok(ControlFlow::Break(acc))
} else {
TryTrampoline::ok(ControlFlow::Continue((n - 1, Rc::new(*acc + n))))
}
},
(100u64, Rc::new(0u64)),
);
assert_eq!(*task.evaluate().unwrap(), 5050);
}
/// Tests `catch_unwind` on `TryTrampoline`.
///
/// Verifies that panics are caught and converted to `Err(String)`.
#[test]
fn test_catch_unwind() {
let task = TryTrampoline::<i32, String>::catch_unwind(|| {
if true {
panic!("oops")
}
42
});
assert_eq!(task.evaluate(), Err("oops".to_string()));
}
/// Tests `catch_unwind` on `TryTrampoline` with a non-panicking closure.
///
/// Verifies that a successful closure wraps the value in `Ok`.
#[test]
fn test_catch_unwind_success() {
let task = TryTrampoline::<i32, String>::catch_unwind(|| 42);
assert_eq!(task.evaluate(), Ok(42));
}
/// Tests `TryTrampoline::catch_unwind_with` with a panicking closure.
///
/// Verifies that the custom handler converts the panic payload.
#[test]
fn test_catch_unwind_with_panic() {
let task = TryTrampoline::<i32, i32>::catch_unwind_with(
|| {
if true {
panic!("oops")
}
42
},
|_payload| -1,
);
assert_eq!(task.evaluate(), Err(-1));
}
/// Tests `TryTrampoline::catch_unwind_with` with a non-panicking closure.
///
/// Verifies that a successful closure wraps the value in `Ok`.
#[test]
fn test_catch_unwind_with_success() {
let task = TryTrampoline::<i32, i32>::catch_unwind_with(|| 42, |_payload| -1);
assert_eq!(task.evaluate(), Ok(42));
}
// QuickCheck Law Tests (via inherent methods)
// Functor Laws
/// Functor identity: `ok(a).map(identity) == Ok(a)`.
#[quickcheck]
fn functor_identity(x: i32) -> bool {
TryTrampoline::<i32, i32>::ok(x).map(|a| a).evaluate() == Ok(x)
}
/// Functor composition: `t.map(f . g) == t.map(g).map(f)`.
#[quickcheck]
fn functor_composition(x: i32) -> bool {
let f = |a: i32| a.wrapping_add(1);
let g = |a: i32| a.wrapping_mul(2);
let lhs = TryTrampoline::<i32, i32>::ok(x).map(move |a| f(g(a))).evaluate();
let rhs = TryTrampoline::<i32, i32>::ok(x).map(g).map(f).evaluate();
lhs == rhs
}
// Monad Laws
/// Monad left identity: `ok(a).bind(f) == f(a)`.
#[quickcheck]
fn monad_left_identity(a: i32) -> bool {
let f = |x: i32| TryTrampoline::<i32, i32>::ok(x.wrapping_mul(2));
TryTrampoline::ok(a).bind(f).evaluate() == f(a).evaluate()
}
/// Monad right identity: `m.bind(ok) == m`.
#[quickcheck]
fn monad_right_identity(x: i32) -> bool {
TryTrampoline::<i32, i32>::ok(x).bind(TryTrampoline::ok).evaluate() == Ok(x)
}
/// Monad associativity: `m.bind(f).bind(g) == m.bind(|a| f(a).bind(g))`.
#[quickcheck]
fn monad_associativity(x: i32) -> bool {
let f = |a: i32| TryTrampoline::<i32, i32>::ok(a.wrapping_add(1));
let g = |a: i32| TryTrampoline::<i32, i32>::ok(a.wrapping_mul(3));
let lhs = TryTrampoline::<i32, i32>::ok(x).bind(f).bind(g).evaluate();
let rhs = TryTrampoline::<i32, i32>::ok(x).bind(move |a| f(a).bind(g)).evaluate();
lhs == rhs
}
/// Error short-circuit: `err(e).bind(f).evaluate() == Err(e)`.
#[quickcheck]
fn error_short_circuit(e: i32) -> bool {
TryTrampoline::<i32, i32>::err(e).bind(|x| TryTrampoline::ok(x.wrapping_add(1))).evaluate()
== Err(e)
}
// Semigroup / Monoid tests
/// Tests Semigroup::append with two successful computations.
#[test]
fn test_semigroup_append_both_ok() {
use crate::classes::Semigroup;
let a: TryTrampoline<String, ()> = TryTrampoline::ok("hello".to_string());
let b: TryTrampoline<String, ()> = TryTrampoline::ok(" world".to_string());
let result = Semigroup::append(a, b);
assert_eq!(result.evaluate(), Ok("hello world".to_string()));
}
/// Tests Semigroup::append propagates the first error.
#[test]
fn test_semigroup_append_first_err() {
use crate::classes::Semigroup;
let a: TryTrampoline<String, String> = TryTrampoline::err("fail".to_string());
let b: TryTrampoline<String, String> = TryTrampoline::ok(" world".to_string());
let result = Semigroup::append(a, b);
assert_eq!(result.evaluate(), Err("fail".to_string()));
}
/// Tests Semigroup::append propagates the second error.
#[test]
fn test_semigroup_append_second_err() {
use crate::classes::Semigroup;
let a: TryTrampoline<String, String> = TryTrampoline::ok("hello".to_string());
let b: TryTrampoline<String, String> = TryTrampoline::err("fail".to_string());
let result = Semigroup::append(a, b);
assert_eq!(result.evaluate(), Err("fail".to_string()));
}
/// Tests Semigroup associativity law for TryTrampoline.
#[quickcheck]
fn semigroup_associativity(
a: String,
b: String,
c: String,
) -> bool {
use crate::classes::Semigroup;
let lhs = Semigroup::append(
Semigroup::append(
TryTrampoline::<String, ()>::ok(a.clone()),
TryTrampoline::ok(b.clone()),
),
TryTrampoline::ok(c.clone()),
)
.evaluate();
let rhs = Semigroup::append(
TryTrampoline::<String, ()>::ok(a),
Semigroup::append(TryTrampoline::ok(b), TryTrampoline::ok(c)),
)
.evaluate();
lhs == rhs
}
/// Tests Monoid::empty returns Ok with the monoidal identity.
#[test]
fn test_monoid_empty() {
use crate::classes::Monoid;
let e: TryTrampoline<String, ()> = Monoid::empty();
assert_eq!(e.evaluate(), Ok(String::new()));
}
/// Tests Monoid left identity law.
#[quickcheck]
fn monoid_left_identity(a: String) -> bool {
use crate::classes::{
Monoid,
Semigroup,
};
let lhs = Semigroup::append(Monoid::empty(), TryTrampoline::<String, ()>::ok(a.clone()))
.evaluate();
lhs == Ok(a)
}
/// Tests Monoid right identity law.
#[quickcheck]
fn monoid_right_identity(a: String) -> bool {
use crate::classes::{
Monoid,
Semigroup,
};
let lhs = Semigroup::append(TryTrampoline::<String, ()>::ok(a.clone()), Monoid::empty())
.evaluate();
lhs == Ok(a)
}
// bimap tests
/// Tests bimap on a successful computation.
#[test]
fn test_bimap_ok() {
let task: TryTrampoline<i32, String> = TryTrampoline::ok(10);
let result = task.bimap(|x| x * 2, |e| e.len());
assert_eq!(result.evaluate(), Ok(20));
}
/// Tests bimap on a failed computation.
#[test]
fn test_bimap_err() {
let task: TryTrampoline<i32, String> = TryTrampoline::err("hello".to_string());
let result = task.bimap(|x| x * 2, |e| e.len());
assert_eq!(result.evaluate(), Err(5));
}
/// Tests bimap composes with map and map_err.
#[quickcheck]
fn bimap_consistent_with_map_and_map_err(x: i32) -> bool {
let f = |a: i32| a.wrapping_add(1);
let g = |e: i32| e.wrapping_mul(2);
let via_bimap = TryTrampoline::<i32, i32>::ok(x).bimap(f, g).evaluate();
let via_map = TryTrampoline::<i32, i32>::ok(x).map(f).evaluate();
via_bimap == via_map
}
/// Tests bimap on error is consistent with map_err.
#[quickcheck]
fn bimap_err_consistent_with_map_err(e: i32) -> bool {
let f = |a: i32| a.wrapping_add(1);
let g = |e: i32| e.wrapping_mul(2);
let via_bimap = TryTrampoline::<i32, i32>::err(e).bimap(f, g).evaluate();
let via_map_err = TryTrampoline::<i32, i32>::err(e).map_err(g).evaluate();
via_bimap == via_map_err
}
// into_rc_try_lazy / into_arc_try_lazy tests
/// Tests `TryTrampoline::into_rc_try_lazy` with a successful computation.
///
/// Verifies that the returned `RcTryLazy` evaluates to the same result and
/// memoizes it (the computation runs at most once).
#[test]
fn test_into_rc_try_lazy_ok() {
let task: TryTrampoline<i32, String> = TryTrampoline::ok(42);
let lazy = task.into_rc_try_lazy();
assert_eq!(lazy.evaluate(), Ok(&42));
// Second access returns the cached value.
assert_eq!(lazy.evaluate(), Ok(&42));
}
/// Tests `TryTrampoline::into_rc_try_lazy` with a failed computation.
///
/// Verifies that the returned `RcTryLazy` memoizes the error result.
#[test]
fn test_into_rc_try_lazy_err() {
let task: TryTrampoline<i32, String> = TryTrampoline::err("oops".to_string());
let lazy = task.into_rc_try_lazy();
assert_eq!(lazy.evaluate(), Err(&"oops".to_string()));
}
/// Tests `TryTrampoline::into_arc_try_lazy` with a successful computation.
///
/// Verifies that the returned `ArcTryLazy` evaluates to the same result.
/// `into_arc_try_lazy` evaluates eagerly because the inner closures are not
/// `Send`, so the result is stored immediately.
#[test]
fn test_into_arc_try_lazy_ok() {
let task: TryTrampoline<i32, String> = TryTrampoline::ok(42);
let lazy = task.into_arc_try_lazy();
assert_eq!(lazy.evaluate(), Ok(&42));
// Second access returns the cached value.
assert_eq!(lazy.evaluate(), Ok(&42));
}
/// Tests `TryTrampoline::into_arc_try_lazy` with a failed computation.
///
/// Verifies that the returned `ArcTryLazy` memoizes the error result.
#[test]
fn test_into_arc_try_lazy_err() {
let task: TryTrampoline<i32, String> = TryTrampoline::err("oops".to_string());
let lazy = task.into_arc_try_lazy();
assert_eq!(lazy.evaluate(), Err(&"oops".to_string()));
}
/// Tests `TryTrampoline::catch_with` stack safety.
///
/// Verifies that deeply chained `catch_with` calls do not overflow the stack.
#[test]
fn test_catch_with_stack_safety() {
let n = 100_000u64;
let mut task: TryTrampoline<u64, u64> = TryTrampoline::err(0);
for i in 1 ..= n {
task = task.catch_with(move |_| TryTrampoline::err(i));
}
assert_eq!(task.evaluate(), Err(n));
}
/// Tests `TryTrampoline::catch_with` stack safety on the success path.
///
/// Verifies that a deeply chained `catch_with` that eventually succeeds
/// does not overflow the stack.
#[test]
fn test_catch_with_stack_safety_ok() {
let n = 100_000u64;
let mut task: TryTrampoline<u64, u64> = TryTrampoline::err(0);
for i in 1 .. n {
task = task.catch_with(move |_| TryTrampoline::err(i));
}
task = task.catch_with(TryTrampoline::ok);
assert_eq!(task.evaluate(), Ok(n - 1));
}
/// Tests `TryTrampoline::resume` on a successful pure value.
///
/// Verifies that resuming a completed `TryTrampoline::ok` returns `Ok(Ok(value))`.
#[test]
fn test_resume_ok() {
let t: TryTrampoline<i32, String> = TryTrampoline::ok(42);
assert_eq!(t.resume().unwrap(), Ok(42));
}
/// Tests `TryTrampoline::resume` on a failed pure value.
///
/// Verifies that resuming a completed `TryTrampoline::err` returns `Ok(Err(error))`.
#[test]
fn test_resume_err() {
let t: TryTrampoline<i32, String> = TryTrampoline::err("oops".to_string());
assert_eq!(t.resume().unwrap(), Err("oops".to_string()));
}
/// Tests `TryTrampoline::resume` on a deferred computation.
///
/// Verifies that resuming a deferred `TryTrampoline` returns `Err(thunk)`,
/// and evaluating the thunk yields another `TryTrampoline` that can be resumed.
#[test]
fn test_resume_deferred() {
let t: TryTrampoline<i32, String> = TryTrampoline::defer(|| TryTrampoline::ok(99));
match t.resume() {
Ok(_) => panic!("expected suspension"),
Err(thunk) => {
let next = thunk.evaluate();
assert_eq!(next.resume().unwrap(), Ok(99));
}
}
}
/// Tests that resuming through a chain of deferred steps eventually reaches `Ok`.
///
/// Builds a chain of three deferred steps and manually drives it to completion.
#[test]
fn test_resume_chain_reaches_ok() {
let t: TryTrampoline<i32, String> = TryTrampoline::defer(|| {
TryTrampoline::defer(|| TryTrampoline::defer(|| TryTrampoline::ok(7)))
});
let mut current = t;
let mut steps = 0;
loop {
match current.resume() {
Ok(result) => {
assert_eq!(result, Ok(7));
break;
}
Err(thunk) => {
current = thunk.evaluate();
steps += 1;
}
}
}
assert!(steps > 0, "expected at least one suspension step");
}
}