lambdust 0.1.1

A Scheme dialect with gradual typing and effect systems
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
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
//! List processing functions for the Lambdust standard library.
//!
//! This module implements R7RS-compliant list operations including
//! list construction, manipulation, higher-order functions, and
//! list predicates.

#![allow(dead_code)]

use crate::diagnostics::{Error as DiagnosticError, Result};
use crate::eval::value::{Value, PrimitiveProcedure, PrimitiveImpl, ThreadSafeEnvironment};
use crate::effects::Effect;
use std::sync::Arc;

/// Creates list operation bindings for the standard library.
pub fn create_list_bindings(env: &Arc<ThreadSafeEnvironment>) {
    // Basic list operations
    bind_basic_list_operations(env);
    
    // List predicates
    bind_list_predicates(env);
    
    // List accessors
    bind_list_accessors(env);
    
    // List manipulation
    bind_list_manipulation(env);
    
    // Higher-order functions
    bind_higher_order_functions(env);
    
    // List utilities
    bind_list_utilities(env);
    
    // SRFI-1 extensions
    // TODO: Implement SRFI-1 extensions
    // bind_srfi1_extensions(env);
}

/// Binds basic list construction and deconstruction operations.
fn bind_basic_list_operations(env: &Arc<ThreadSafeEnvironment>) {
    // cons - only define if not already present (preserves bootstrap primitives)
    if env.lookup("cons").is_none() {
        env.define("cons".to_string(), Value::Primitive(Arc::new(PrimitiveProcedure {
            name: "cons".to_string(),
            arity_min: 2,
            arity_max: Some(2),
            implementation: PrimitiveImpl::RustFn(primitive_cons),
            effects: vec![Effect::Pure],
        })));
    }
    
    // car - only define if not already present (preserves bootstrap primitives)
    if env.lookup("car").is_none() {
        env.define("car".to_string(), Value::Primitive(Arc::new(PrimitiveProcedure {
            name: "car".to_string(),
            arity_min: 1,
            arity_max: Some(1),
            implementation: PrimitiveImpl::RustFn(primitive_car),
            effects: vec![Effect::Pure],
        })));
    }
    
    // cdr - only define if not already present (preserves bootstrap primitives)
    if env.lookup("cdr").is_none() {
        env.define("cdr".to_string(), Value::Primitive(Arc::new(PrimitiveProcedure {
            name: "cdr".to_string(),
            arity_min: 1,
            arity_max: Some(1),
            implementation: PrimitiveImpl::RustFn(primitive_cdr),
            effects: vec![Effect::Pure],
        })));
    }
    
    // list
    env.define("list".to_string(), Value::Primitive(Arc::new(PrimitiveProcedure {
        name: "list".to_string(),
        arity_min: 0,
        arity_max: None,
        implementation: PrimitiveImpl::RustFn(primitive_list),
        effects: vec![Effect::Pure],
    })));
    
    // list*
    env.define("list*".to_string(), Value::Primitive(Arc::new(PrimitiveProcedure {
        name: "list*".to_string(),
        arity_min: 1,
        arity_max: None,
        implementation: PrimitiveImpl::RustFn(primitive_list_star),
        effects: vec![Effect::Pure],
    })));
    
    // make-list
    env.define("make-list".to_string(), Value::Primitive(Arc::new(PrimitiveProcedure {
        name: "make-list".to_string(),
        arity_min: 1,
        arity_max: Some(2),
        implementation: PrimitiveImpl::RustFn(primitive_make_list),
        effects: vec![Effect::Pure],
    })));
}

/// Binds list predicates.
fn bind_list_predicates(env: &Arc<ThreadSafeEnvironment>) {
    // pair?
    env.define("pair?".to_string(), Value::Primitive(Arc::new(PrimitiveProcedure {
        name: "pair?".to_string(),
        arity_min: 1,
        arity_max: Some(1),
        implementation: PrimitiveImpl::RustFn(primitive_pair_p),
        effects: vec![Effect::Pure],
    })));
    
    // null?
    env.define("null?".to_string(), Value::Primitive(Arc::new(PrimitiveProcedure {
        name: "null?".to_string(),
        arity_min: 1,
        arity_max: Some(1),
        implementation: PrimitiveImpl::RustFn(primitive_null_p),
        effects: vec![Effect::Pure],
    })));
    
    // list?
    env.define("list?".to_string(), Value::Primitive(Arc::new(PrimitiveProcedure {
        name: "list?".to_string(),
        arity_min: 1,
        arity_max: Some(1),
        implementation: PrimitiveImpl::RustFn(primitive_list_p),
        effects: vec![Effect::Pure],
    })));
}

/// Binds list accessor functions.
fn bind_list_accessors(env: &Arc<ThreadSafeEnvironment>) {
    // Combinations of car/cdr
    let combinations = [
        ("caar", "car", "car"),
        ("cadr", "cdr", "car"),
        ("cdar", "car", "cdr"),
        ("cddr", "cdr", "cdr"),
        ("caaar", "caar", "car"),
        ("caadr", "cadr", "car"),
        ("cadar", "cdar", "car"),
        ("caddr", "cddr", "car"),
        ("cdaar", "caar", "cdr"),
        ("cdadr", "cadr", "cdr"),
        ("cddar", "cdar", "cdr"),
        ("cdddr", "cddr", "cdr"),
        ("caaaar", "caaar", "car"),
        ("caaadr", "caadr", "car"),
        ("caadar", "cadar", "car"),
        ("caaddr", "caddr", "car"),
        ("cadaar", "cdaar", "car"),
        ("cadadr", "cdadr", "car"),
        ("caddar", "cddar", "car"),
        ("cadddr", "cdddr", "car"),
        ("cdaaar", "caaar", "cdr"),
        ("cdaadr", "caadr", "cdr"),
        ("cdadar", "cadar", "cdr"),
        ("cdaddr", "caddr", "cdr"),
        ("cddaar", "cdaar", "cdr"),
        ("cddadr", "cdadr", "cdr"),
        ("cdddar", "cddar", "cdr"),
        ("cddddr", "cdddr", "cdr"),
    ];
    
    for (name, _, _) in &combinations {
        env.define(name.to_string(), Value::Primitive(Arc::new(PrimitiveProcedure {
            name: name.to_string(),
            arity_min: 1,
            arity_max: Some(1),
            implementation: PrimitiveImpl::RustFn(make_car_cdr_combination(name)),
            effects: vec![Effect::Pure],
        })));
    }
    
    // list-ref
    env.define("list-ref".to_string(), Value::Primitive(Arc::new(PrimitiveProcedure {
        name: "list-ref".to_string(),
        arity_min: 2,
        arity_max: Some(2),
        implementation: PrimitiveImpl::RustFn(primitive_list_ref),
        effects: vec![Effect::Pure],
    })));
    
    // list-tail
    env.define("list-tail".to_string(), Value::Primitive(Arc::new(PrimitiveProcedure {
        name: "list-tail".to_string(),
        arity_min: 2,
        arity_max: Some(2),
        implementation: PrimitiveImpl::RustFn(primitive_list_tail),
        effects: vec![Effect::Pure],
    })));
}

/// Binds list manipulation functions.
fn bind_list_manipulation(env: &Arc<ThreadSafeEnvironment>) {
    // length
    env.define("length".to_string(), Value::Primitive(Arc::new(PrimitiveProcedure {
        name: "length".to_string(),
        arity_min: 1,
        arity_max: Some(1),
        implementation: PrimitiveImpl::RustFn(primitive_length),
        effects: vec![Effect::Pure],
    })));
    
    // append
    env.define("append".to_string(), Value::Primitive(Arc::new(PrimitiveProcedure {
        name: "append".to_string(),
        arity_min: 0,
        arity_max: None,
        implementation: PrimitiveImpl::RustFn(primitive_append),
        effects: vec![Effect::Pure],
    })));
    
    // reverse
    env.define("reverse".to_string(), Value::Primitive(Arc::new(PrimitiveProcedure {
        name: "reverse".to_string(),
        arity_min: 1,
        arity_max: Some(1),
        implementation: PrimitiveImpl::RustFn(primitive_reverse),
        effects: vec![Effect::Pure],
    })));
    
    // set-car! (mutation)
    env.define("set-car!".to_string(), Value::Primitive(Arc::new(PrimitiveProcedure {
        name: "set-car!".to_string(),
        arity_min: 2,
        arity_max: Some(2),
        implementation: PrimitiveImpl::RustFn(primitive_set_car),
        effects: vec![Effect::State], // Mutation effect
    })));
    
    // set-cdr! (mutation)
    env.define("set-cdr!".to_string(), Value::Primitive(Arc::new(PrimitiveProcedure {
        name: "set-cdr!".to_string(),
        arity_min: 2,
        arity_max: Some(2),
        implementation: PrimitiveImpl::RustFn(primitive_set_cdr),
        effects: vec![Effect::State], // Mutation effect
    })));
    
    // list-set! (mutation)
    env.define("list-set!".to_string(), Value::Primitive(Arc::new(PrimitiveProcedure {
        name: "list-set!".to_string(),
        arity_min: 3,
        arity_max: Some(3),
        implementation: PrimitiveImpl::RustFn(primitive_list_set),
        effects: vec![Effect::State], // Mutation effect
    })));
    
    // list-copy
    env.define("list-copy".to_string(), Value::Primitive(Arc::new(PrimitiveProcedure {
        name: "list-copy".to_string(),
        arity_min: 1,
        arity_max: Some(1),
        implementation: PrimitiveImpl::RustFn(primitive_list_copy),
        effects: vec![Effect::Pure],
    })));
}

/// Binds higher-order list functions.
fn bind_higher_order_functions(env: &Arc<ThreadSafeEnvironment>) {
    // map
    env.define("map".to_string(), Value::Primitive(Arc::new(PrimitiveProcedure {
        name: "map".to_string(),
        arity_min: 2,
        arity_max: None,
        implementation: PrimitiveImpl::EvaluatorIntegrated(evaluator_map),
        effects: vec![Effect::Pure], // May call user functions with effects
    })));
    
    // for-each
    env.define("for-each".to_string(), Value::Primitive(Arc::new(PrimitiveProcedure {
        name: "for-each".to_string(),
        arity_min: 2,
        arity_max: None,
        implementation: PrimitiveImpl::EvaluatorIntegrated(evaluator_for_each),
        effects: vec![Effect::State], // For side effects
    })));
    
    // filter
    env.define("filter".to_string(), Value::Primitive(Arc::new(PrimitiveProcedure {
        name: "filter".to_string(),
        arity_min: 2,
        arity_max: Some(2),
        implementation: PrimitiveImpl::EvaluatorIntegrated(evaluator_filter),
        effects: vec![Effect::Pure],
    })));
    
    // fold-left (reduce)
    env.define("fold-left".to_string(), Value::Primitive(Arc::new(PrimitiveProcedure {
        name: "fold-left".to_string(),
        arity_min: 3,
        arity_max: None,
        implementation: PrimitiveImpl::EvaluatorIntegrated(evaluator_fold_left),
        effects: vec![Effect::Pure],
    })));
    
    // fold-right
    env.define("fold-right".to_string(), Value::Primitive(Arc::new(PrimitiveProcedure {
        name: "fold-right".to_string(),
        arity_min: 3,
        arity_max: None,
        implementation: PrimitiveImpl::EvaluatorIntegrated(evaluator_fold_right),
        effects: vec![Effect::Pure],
    })));
    
    // any (exists)
    env.define("any".to_string(), Value::Primitive(Arc::new(PrimitiveProcedure {
        name: "any".to_string(),
        arity_min: 2,
        arity_max: None,
        implementation: PrimitiveImpl::RustFn(primitive_any),
        effects: vec![Effect::Pure],
    })));
    
    // every (for-all)
    env.define("every".to_string(), Value::Primitive(Arc::new(PrimitiveProcedure {
        name: "every".to_string(),
        arity_min: 2,
        arity_max: None,
        implementation: PrimitiveImpl::RustFn(primitive_every),
        effects: vec![Effect::Pure],
    })));
}

/// Binds list utility functions.
fn bind_list_utilities(env: &Arc<ThreadSafeEnvironment>) {
    // member
    env.define("member".to_string(), Value::Primitive(Arc::new(PrimitiveProcedure {
        name: "member".to_string(),
        arity_min: 2,
        arity_max: Some(3),
        implementation: PrimitiveImpl::RustFn(primitive_member),
        effects: vec![Effect::Pure],
    })));
    
    // memq
    env.define("memq".to_string(), Value::Primitive(Arc::new(PrimitiveProcedure {
        name: "memq".to_string(),
        arity_min: 2,
        arity_max: Some(2),
        implementation: PrimitiveImpl::RustFn(primitive_memq),
        effects: vec![Effect::Pure],
    })));
    
    // memv
    env.define("memv".to_string(), Value::Primitive(Arc::new(PrimitiveProcedure {
        name: "memv".to_string(),
        arity_min: 2,
        arity_max: Some(2),
        implementation: PrimitiveImpl::RustFn(primitive_memv),
        effects: vec![Effect::Pure],
    })));
    
    // assoc
    env.define("assoc".to_string(), Value::Primitive(Arc::new(PrimitiveProcedure {
        name: "assoc".to_string(),
        arity_min: 2,
        arity_max: Some(3),
        implementation: PrimitiveImpl::RustFn(primitive_assoc),
        effects: vec![Effect::Pure],
    })));
    
    // assq
    env.define("assq".to_string(), Value::Primitive(Arc::new(PrimitiveProcedure {
        name: "assq".to_string(),
        arity_min: 2,
        arity_max: Some(2),
        implementation: PrimitiveImpl::RustFn(primitive_assq),
        effects: vec![Effect::Pure],
    })));
    
    // assv
    env.define("assv".to_string(), Value::Primitive(Arc::new(PrimitiveProcedure {
        name: "assv".to_string(),
        arity_min: 2,
        arity_max: Some(2),
        implementation: PrimitiveImpl::RustFn(primitive_assv),
        effects: vec![Effect::Pure],
    })));
    
    // sort
    env.define("sort".to_string(), Value::Primitive(Arc::new(PrimitiveProcedure {
        name: "sort".to_string(),
        arity_min: 2,
        arity_max: Some(2),
        implementation: PrimitiveImpl::RustFn(primitive_sort),
        effects: vec![Effect::Pure],
    })));
}

// ============= BASIC LIST OPERATION IMPLEMENTATIONS =============

/// cons procedure
fn primitive_cons(args: &[Value]) -> Result<Value> {
    if args.len() != 2 {
        return Err(Box::new(DiagnosticError::runtime_error(
            format!("cons expects 2 arguments, got {}", args.len()),
            None,
        )));
    }
    
    Ok(Value::pair(args[0].clone(), args[1].clone()))
}

/// car procedure
fn primitive_car(args: &[Value]) -> Result<Value> {
    if args.len() != 1 {
        return Err(Box::new(DiagnosticError::runtime_error(
            format!("car expects 1 argument, got {}", args.len()),
            None,
        )));
    }
    
    match &args[0] {
        Value::Pair(car, _) => Ok((**car).clone()),
        Value::MutablePair(car_ref, _) => {
            if let Ok(car) = car_ref.read() {
                Ok(car.clone())
            } else {
                Err(Box::new(DiagnosticError::runtime_error(
                    "car failed to acquire read lock".to_string(),
                    None,
                )))
            }
        }
        _ => Err(Box::new(DiagnosticError::runtime_error(
            "car requires a pair".to_string(),
            None,
        ))),
    }
}

/// cdr procedure
fn primitive_cdr(args: &[Value]) -> Result<Value> {
    if args.len() != 1 {
        return Err(Box::new(DiagnosticError::runtime_error(
            format!("cdr expects 1 argument, got {}", args.len()),
            None,
        )));
    }
    
    match &args[0] {
        Value::Pair(_, cdr) => Ok((**cdr).clone()),
        Value::MutablePair(_, cdr_ref) => {
            if let Ok(cdr) = cdr_ref.read() {
                Ok(cdr.clone())
            } else {
                Err(Box::new(DiagnosticError::runtime_error(
                    "cdr failed to acquire read lock".to_string(),
                    None,
                )))
            }
        }
        _ => Err(Box::new(DiagnosticError::runtime_error(
            "cdr requires a pair".to_string(),
            None,
        ))),
    }
}

/// list constructor
fn primitive_list(args: &[Value]) -> Result<Value> {
    Ok(Value::list(args.to_vec()))
}

/// list* procedure (improper list constructor)
fn primitive_list_star(args: &[Value]) -> Result<Value> {
    if args.is_empty() {
        return Err(Box::new(DiagnosticError::runtime_error(
            "list* requires at least 1 argument".to_string(),
            None,
        )));
    }
    
    if args.len() == 1 {
        return Ok(args[0].clone());
    }
    
    let mut result = args[args.len() - 1].clone();
    
    for arg in args[..args.len() - 1].iter().rev() {
        result = Value::pair(arg.clone(), result);
    }
    
    Ok(result)
}

/// make-list procedure
fn primitive_make_list(args: &[Value]) -> Result<Value> {
    if args.is_empty() || args.len() > 2 {
        return Err(Box::new(DiagnosticError::runtime_error(
            format!("make-list expects 1 or 2 arguments, got {}", args.len()),
            None,
        )));
    }
    
    let length = args[0].as_integer().ok_or_else(|| {
        DiagnosticError::runtime_error(
            "make-list first argument must be a non-negative integer".to_string(),
            None,
        )
    })?;
    
    if length < 0 {
        return Err(Box::new(DiagnosticError::runtime_error(
            "make-list length must be non-negative".to_string(),
            None,
        )));
    }
    
    let fill = if args.len() == 2 {
        args[1].clone()
    } else {
        Value::Unspecified
    };
    
    let elements = vec![fill; length as usize];
    Ok(Value::list(elements))
}

// ============= LIST PREDICATE IMPLEMENTATIONS =============

/// pair? predicate
fn primitive_pair_p(args: &[Value]) -> Result<Value> {
    if args.len() != 1 {
        return Err(Box::new(DiagnosticError::runtime_error(
            format!("pair? expects 1 argument, got {}", args.len()),
            None,
        )));
    }
    
    Ok(Value::boolean(args[0].is_pair()))
}

/// null? predicate
fn primitive_null_p(args: &[Value]) -> Result<Value> {
    if args.len() != 1 {
        return Err(Box::new(DiagnosticError::runtime_error(
            format!("null? expects 1 argument, got {}", args.len()),
            None,
        )));
    }
    
    Ok(Value::boolean(args[0].is_nil()))
}

/// list? predicate
fn primitive_list_p(args: &[Value]) -> Result<Value> {
    if args.len() != 1 {
        return Err(Box::new(DiagnosticError::runtime_error(
            format!("list? expects 1 argument, got {}", args.len()),
            None,
        )));
    }
    
    Ok(Value::boolean(is_proper_list(&args[0])))
}

// ============= LIST ACCESSOR IMPLEMENTATIONS =============

/// Creates a car/cdr combination function
fn make_car_cdr_combination(name: &str) -> fn(&[Value]) -> Result<Value> {
    // This is a simplified implementation
    // In practice, you'd generate these dynamically
    match name {
        "caar" => |args| {
            let result = primitive_car(args)?;
            primitive_car(&[result])
        },
        "cadr" => |args| {
            let result = primitive_cdr(args)?;
            primitive_car(&[result])
        },
        "cdar" => |args| {
            let result = primitive_car(args)?;
            primitive_cdr(&[result])
        },
        "cddr" => |args| {
            let result = primitive_cdr(args)?;
            primitive_cdr(&[result])
        },
        // Add more combinations as needed
        _ => {
            fn unknown_combination(_args: &[Value]) -> Result<Value> {
                Err(Box::new(DiagnosticError::runtime_error(
                    "Unknown car/cdr combination".to_string(),
                    None,
                )))
            }
            unknown_combination
        },
    }
}

/// list-ref procedure
fn primitive_list_ref(args: &[Value]) -> Result<Value> {
    if args.len() != 2 {
        return Err(Box::new(DiagnosticError::runtime_error(
            format!("list-ref expects 2 arguments, got {}", args.len()),
            None,
        )));
    }
    
    let index = args[1].as_integer().ok_or_else(|| {
        DiagnosticError::runtime_error(
            "list-ref index must be a non-negative integer".to_string(),
            None,
        )
    })?;
    
    if index < 0 {
        return Err(Box::new(DiagnosticError::runtime_error(
            "list-ref index must be non-negative".to_string(),
            None,
        )));
    }
    
    let mut current = &args[0];
    let mut i = 0;
    
    while i < index {
        match current {
            Value::Pair(_, cdr) => {
                current = cdr;
                i += 1;
            }
            Value::MutablePair(_, cdr_ref) => {
                // For mutable pairs, we need to use a different approach
                // since we can't hold references. Use as_list for simplicity.
                if let Some(list_values) = args[0].as_list() {
                    if index as usize >= list_values.len() {
                        return Err(Box::new(DiagnosticError::runtime_error(
                            "list-ref index out of bounds".to_string(),
                            None,
                        )));
                    }
                    return Ok(list_values[index as usize].clone());
                } else {
                    return Err(Box::new(DiagnosticError::runtime_error(
                        "list-ref requires a proper list".to_string(),
                        None,
                    )));
                }
            }
            _ => {
                return Err(Box::new(DiagnosticError::runtime_error(
                    "list-ref index out of bounds".to_string(),
                    None,
                )));
            }
        }
    }
    
    match current {
        Value::Pair(car, _) => Ok((**car).clone()),
        Value::MutablePair(car_ref, _) => {
            if let Ok(car) = car_ref.read() {
                Ok(car.clone())
            } else {
                Err(Box::new(DiagnosticError::runtime_error(
                    "list-ref failed to acquire read lock".to_string(),
                    None,
                )))
            }
        }
        _ => Err(Box::new(DiagnosticError::runtime_error(
            "list-ref index out of bounds".to_string(),
            None,
        ))),
    }
}

/// list-tail procedure
fn primitive_list_tail(args: &[Value]) -> Result<Value> {
    if args.len() != 2 {
        return Err(Box::new(DiagnosticError::runtime_error(
            format!("list-tail expects 2 arguments, got {}", args.len()),
            None,
        )));
    }
    
    let k = args[1].as_integer().ok_or_else(|| {
        DiagnosticError::runtime_error(
            "list-tail k must be a non-negative integer".to_string(),
            None,
        )
    })?;
    
    if k < 0 {
        return Err(Box::new(DiagnosticError::runtime_error(
            "list-tail k must be non-negative".to_string(),
            None,
        )));
    }
    
    let mut current = args[0].clone();
    let mut i = 0;
    
    while i < k {
        match current {
            Value::Pair(_, cdr) => {
                current = cdr.as_ref().clone();
                i += 1;
            }
            _ => {
                return Err(Box::new(DiagnosticError::runtime_error(
                    "list-tail k out of bounds".to_string(),
                    None,
                )));
            }
        }
    }
    
    Ok(current)
}

// ============= LIST MANIPULATION IMPLEMENTATIONS =============

/// length procedure
fn primitive_length(args: &[Value]) -> Result<Value> {
    if args.len() != 1 {
        return Err(Box::new(DiagnosticError::runtime_error(
            format!("length expects 1 argument, got {}", args.len()),
            None,
        )));
    }
    
    let mut current = &args[0];
    let mut length = 0;
    
    loop {
        match current {
            Value::Nil => break,
            Value::Pair(_, cdr) => {
                current = cdr;
                length += 1;
            }
            Value::MutablePair(_, cdr_ref) => {
                if let Ok(cdr) = cdr_ref.read() {
                    // For mutable pairs, we need to use as_list for simplicity
                    // since we can't hold references across iterations
                    if let Some(list) = args[0].as_list() {
                        return Ok(Value::integer(list.len() as i64));
                    } else {
                        return Err(Box::new(DiagnosticError::runtime_error(
                            "length requires a proper list".to_string(),
                            None,
                        )));
                    }
                } else {
                    return Err(Box::new(DiagnosticError::runtime_error(
                        "length failed to acquire read lock".to_string(),
                        None,
                    )));
                }
            }
            _ => {
                return Err(Box::new(DiagnosticError::runtime_error(
                    "length requires a proper list".to_string(),
                    None,
                )));
            }
        }
    }
    
    Ok(Value::integer(length))
}

/// append procedure
fn primitive_append(args: &[Value]) -> Result<Value> {
    if args.is_empty() {
        return Ok(Value::Nil);
    }
    
    if args.len() == 1 {
        return Ok(args[0].clone());
    }
    
    // All but the last argument must be proper lists
    for arg in &args[..args.len() - 1] {
        if !is_proper_list(arg) {
            return Err(Box::new(DiagnosticError::runtime_error(
                "append arguments (except the last) must be proper lists".to_string(),
                None,
            )));
        }
    }
    
    let mut result = args[args.len() - 1].clone();
    
    for arg in args[..args.len() - 1].iter().rev() {
        if let Some(list) = arg.as_list() {
            for item in list.into_iter().rev() {
                result = Value::pair(item, result);
            }
        }
    }
    
    Ok(result)
}

/// reverse procedure
fn primitive_reverse(args: &[Value]) -> Result<Value> {
    if args.len() != 1 {
        return Err(Box::new(DiagnosticError::runtime_error(
            format!("reverse expects 1 argument, got {}", args.len()),
            None,
        )));
    }
    
    if let Some(list) = args[0].as_list() {
        let mut reversed = list;
        reversed.reverse();
        Ok(Value::list(reversed))
    } else {
        Err(Box::new(DiagnosticError::runtime_error(
            "reverse requires a proper list".to_string(),
            None,
        )))
    }
}

/// set-car! procedure (mutation)
fn primitive_set_car(args: &[Value]) -> Result<Value> {
    if args.len() != 2 {
        return Err(Box::new(DiagnosticError::runtime_error(
            format!("set-car! expects 2 arguments, got {}", args.len()),
            None,
        )));
    }
    
    match &args[0] {
        Value::MutablePair(car_ref, _) => {
            if let Ok(mut car) = car_ref.write() {
                *car = args[1].clone();
                Ok(Value::Unspecified)
            } else {
                Err(Box::new(DiagnosticError::runtime_error(
                    "set-car! failed to acquire write lock".to_string(),
                    None,
                )))
            }
        }
        Value::Pair(_, _) => {
            Err(Box::new(DiagnosticError::runtime_error(
                "set-car! requires a mutable pair (immutable pair given)".to_string(),
                None,
            )))
        }
        _ => {
            Err(Box::new(DiagnosticError::runtime_error(
                "set-car! requires a pair".to_string(),
                None,
            )))
        }
    }
}

/// set-cdr! procedure (mutation)
fn primitive_set_cdr(args: &[Value]) -> Result<Value> {
    if args.len() != 2 {
        return Err(Box::new(DiagnosticError::runtime_error(
            format!("set-cdr! expects 2 arguments, got {}", args.len()),
            None,
        )));
    }
    
    match &args[0] {
        Value::MutablePair(_, cdr_ref) => {
            if let Ok(mut cdr) = cdr_ref.write() {
                *cdr = args[1].clone();
                Ok(Value::Unspecified)
            } else {
                Err(Box::new(DiagnosticError::runtime_error(
                    "set-cdr! failed to acquire write lock".to_string(),
                    None,
                )))
            }
        }
        Value::Pair(_, _) => {
            Err(Box::new(DiagnosticError::runtime_error(
                "set-cdr! requires a mutable pair (immutable pair given)".to_string(),
                None,
            )))
        }
        _ => {
            Err(Box::new(DiagnosticError::runtime_error(
                "set-cdr! requires a pair".to_string(),
                None,
            )))
        }
    }
}

/// list-set! procedure (mutation)
fn primitive_list_set(args: &[Value]) -> Result<Value> {
    if args.len() != 3 {
        return Err(Box::new(DiagnosticError::runtime_error(
            format!("list-set! expects 3 arguments, got {}", args.len()),
            None,
        )));
    }
    
    let index = args[1].as_integer().ok_or_else(|| {
        DiagnosticError::runtime_error(
            "list-set! index must be a non-negative integer".to_string(),
            None,
        )
    })?;
    
    if index < 0 {
        return Err(Box::new(DiagnosticError::runtime_error(
            "list-set! index must be non-negative".to_string(),
            None,
        )));
    }
    
    let mut current = &args[0];
    let mut steps_remaining = index;
    
    // Navigate to the target pair
    while steps_remaining > 0 {
        match current {
            Value::MutablePair(_, cdr_ref) => {
                if let Ok(cdr) = cdr_ref.read() {
                    let cdr_clone = cdr.clone();
                    drop(cdr); // Release the lock
                    match cdr_clone {
                        Value::MutablePair(_, _) | Value::Pair(_, _) => {
                            // We need to continue with a reference, but we can't store it
                            // This is a limitation of our approach - we'll need to navigate again
                            return set_list_element(&args[0], index, args[2].clone());
                        }
                        _ => {
                            return Err(Box::new(DiagnosticError::runtime_error(
                                "list-set! index out of bounds".to_string(),
                                None,
                            )));
                        }
                    }
                } else {
                    return Err(Box::new(DiagnosticError::runtime_error(
                        "list-set! failed to acquire read lock".to_string(),
                        None,
                    )));
                }
            }
            Value::Pair(_, cdr) => {
                current = cdr;
                steps_remaining -= 1;
            }
            _ => {
                return Err(Box::new(DiagnosticError::runtime_error(
                    "list-set! index out of bounds".to_string(),
                    None,
                )));
            }
        }
    }
    
    // Set the car of the current pair
    match current {
        Value::MutablePair(car_ref, _) => {
            if let Ok(mut car) = car_ref.write() {
                *car = args[2].clone();
                Ok(Value::Unspecified)
            } else {
                Err(Box::new(DiagnosticError::runtime_error(
                    "list-set! failed to acquire write lock".to_string(),
                    None,
                )))
            }
        }
        _ => {
            Err(Box::new(DiagnosticError::runtime_error(
                "list-set! requires a mutable list".to_string(),
                None,
            )))
        }
    }
}

/// list-copy procedure
fn primitive_list_copy(args: &[Value]) -> Result<Value> {
    if args.len() != 1 {
        return Err(Box::new(DiagnosticError::runtime_error(
            format!("list-copy expects 1 argument, got {}", args.len()),
            None,
        )));
    }
    
    // For now, we'll do a shallow copy by reconstructing the list
    copy_list(&args[0])
}

/// Helper function to set an element in a list by index
fn set_list_element(list: &Value, index: i64, value: Value) -> Result<Value> {
    if index == 0 {
        match list {
            Value::MutablePair(car_ref, _) => {
                if let Ok(mut car) = car_ref.write() {
                    *car = value;
                    Ok(Value::Unspecified)
                } else {
                    Err(Box::new(DiagnosticError::runtime_error(
                        "set-list-element failed to acquire write lock".to_string(),
                        None,
                    )))
                }
            }
            _ => Err(Box::new(DiagnosticError::runtime_error(
                "set-list-element requires a mutable list".to_string(),
                None,
            )))
        }
    } else {
        match list {
            Value::MutablePair(_, cdr_ref) => {
                if let Ok(cdr) = cdr_ref.read() {
                    let cdr_clone = cdr.clone();
                    drop(cdr); // Release the lock
                    set_list_element(&cdr_clone, index - 1, value)
                } else {
                    Err(Box::new(DiagnosticError::runtime_error(
                        "set-list-element failed to acquire read lock".to_string(),
                        None,
                    )))
                }
            }
            Value::Pair(_, cdr) => {
                set_list_element(cdr, index - 1, value)
            }
            _ => Err(Box::new(DiagnosticError::runtime_error(
                "set-list-element index out of bounds".to_string(),
                None,
            )))
        }
    }
}

// ============= HIGHER-ORDER FUNCTION IMPLEMENTATIONS =============

/// map procedure - Enhanced R7RS implementation supporting multiple lists
fn primitive_map(args: &[Value]) -> Result<Value> {
    if args.len() < 2 {
        return Err(Box::new(DiagnosticError::runtime_error(
            "map requires at least 2 arguments".to_string(),
            None,
        )));
    }
    
    let procedure = &args[0];
    let lists = &args[1..];
    
    // Verify procedure is callable
    if !procedure.is_procedure() {
        return Err(Box::new(DiagnosticError::runtime_error(
            "map first argument must be a procedure".to_string(),
            None,
        )));
    }
    
    // Convert all arguments to proper lists and find minimum length
    let mut list_vectors = Vec::new();
    let mut min_length = usize::MAX;
    
    for (i, list_arg) in lists.iter().enumerate() {
        if let Some(list_values) = list_arg.as_list() {
            min_length = min_length.min(list_values.len());
            list_vectors.push(list_values);
        } else {
            return Err(Box::new(DiagnosticError::runtime_error(
                format!("map argument {} must be a list", i + 2),
                None,
            )));
        }
    }
    
    // If any list is empty, return empty list
    if min_length == 0 || min_length == usize::MAX {
        return Ok(Value::Nil);
    }
    
    // Apply procedure to each position across all lists
    let mut results = Vec::new();
    
    for i in 0..min_length {
        let mut proc_args = Vec::new();
        for list in &list_vectors {
            proc_args.push(list[i].clone());
        }
        
        // Apply the procedure - for now we can only handle primitive procedures
        match procedure {
            Value::Primitive(prim) => {
                let result = match &prim.implementation {
                    PrimitiveImpl::RustFn(func) => func(&proc_args)?,
                    PrimitiveImpl::Native(func) => func(&proc_args)?,
                    PrimitiveImpl::EvaluatorIntegrated(_) => {
                        return Err(Box::new(DiagnosticError::runtime_error(
                            "map with EvaluatorIntegrated functions requires evaluator access (not yet implemented)".to_string(),
                            None,
                        )));
                    }
                    PrimitiveImpl::ForeignFn { .. } => {
                        return Err(Box::new(DiagnosticError::runtime_error(
                            "map with foreign functions not yet implemented".to_string(),
                            None,
                        )));
                    }
                };
                results.push(result);
            },
            _ => {
                return Err(Box::new(DiagnosticError::runtime_error(
                    "map with user-defined procedures requires evaluator integration (not yet implemented)".to_string(),
                    None,
                )));
            }
        }
    }
    
    Ok(Value::list(results))
}

/// for-each procedure - Enhanced R7RS implementation supporting multiple lists
fn primitive_for_each(args: &[Value]) -> Result<Value> {
    if args.len() < 2 {
        return Err(Box::new(DiagnosticError::runtime_error(
            "for-each requires at least 2 arguments".to_string(),
            None,
        )));
    }
    
    let procedure = &args[0];
    let lists = &args[1..];
    
    // Verify procedure is callable
    if !procedure.is_procedure() {
        return Err(Box::new(DiagnosticError::runtime_error(
            "for-each first argument must be a procedure".to_string(),
            None,
        )));
    }
    
    // Convert all arguments to proper lists and find minimum length
    let mut list_vectors = Vec::new();
    let mut min_length = usize::MAX;
    
    for (i, list_arg) in lists.iter().enumerate() {
        if let Some(list_values) = list_arg.as_list() {
            min_length = min_length.min(list_values.len());
            list_vectors.push(list_values);
        } else {
            return Err(Box::new(DiagnosticError::runtime_error(
                format!("for-each argument {} must be a list", i + 2),
                None,
            )));
        }
    }
    
    // If any list is empty, return unspecified immediately
    if min_length == 0 || min_length == usize::MAX {
        return Ok(Value::Unspecified);
    }
    
    // Apply procedure to each position across all lists for side effects
    for i in 0..min_length {
        let mut proc_args = Vec::new();
        for list in &list_vectors {
            proc_args.push(list[i].clone());
        }
        
        // Apply the procedure - for now we can only handle primitive procedures
        match procedure {
            Value::Primitive(prim) => {
                match &prim.implementation {
                    PrimitiveImpl::RustFn(func) => {
                        // Call the function but ignore the result (for-each is for side effects)
                        func(&proc_args)?;
                    },
                    PrimitiveImpl::Native(func) => {
                        // Call the function but ignore the result (for-each is for side effects)
                        func(&proc_args)?;
                    },
                    PrimitiveImpl::EvaluatorIntegrated(_) => {
                        return Err(Box::new(DiagnosticError::runtime_error(
                            "for-each with EvaluatorIntegrated functions requires evaluator access (not yet implemented)".to_string(),
                            None,
                        )));
                    }
                    PrimitiveImpl::ForeignFn { .. } => {
                        return Err(Box::new(DiagnosticError::runtime_error(
                            "for-each with foreign functions not yet implemented".to_string(),
                            None,
                        )));
                    }
                }
            },
            _ => {
                return Err(Box::new(DiagnosticError::runtime_error(
                    "for-each with user-defined procedures requires evaluator integration (not yet implemented)".to_string(),
                    None,
                )));
            }
        }
    }
    
    // for-each returns unspecified
    Ok(Value::Unspecified)
}

/// filter procedure
fn primitive_filter(args: &[Value]) -> Result<Value> {
    if args.len() != 2 {
        return Err(Box::new(DiagnosticError::runtime_error(
            format!("filter expects 2 arguments, got {}", args.len()),
            None,
        )));
    }
    
    let predicate = &args[0];
    let list_arg = &args[1];
    
    // Verify predicate is callable
    if !predicate.is_procedure() {
        return Err(Box::new(DiagnosticError::runtime_error(
            "filter first argument must be a procedure".to_string(),
            None,
        )));
    }
    
    // Convert to proper list
    let list = list_arg.as_list().ok_or_else(|| {
        DiagnosticError::runtime_error(
            "filter requires a proper list".to_string(),
            None,
        )
    })?;
    
    let mut results = Vec::new();
    
    // Apply predicate to each element
    for element in list {
        let proc_args = vec![element.clone()];
        
        // Apply the predicate - for now we can only handle primitive procedures
        let keep = match predicate {
            Value::Primitive(prim) => {
                let result = match &prim.implementation {
                    PrimitiveImpl::RustFn(func) => func(&proc_args)?,
                    PrimitiveImpl::Native(func) => func(&proc_args)?,
                    PrimitiveImpl::EvaluatorIntegrated(_) => {
                        return Err(Box::new(DiagnosticError::runtime_error(
                            "filter with EvaluatorIntegrated functions requires evaluator access (not yet implemented)".to_string(),
                            None,
                        )));
                    }
                    PrimitiveImpl::ForeignFn { .. } => {
                        return Err(Box::new(DiagnosticError::runtime_error(
                            "filter with foreign functions not yet implemented".to_string(),
                            None,
                        )));
                    }
                };
                
                // Check if result is truthy
                result.is_truthy()
            },
            _ => {
                return Err(Box::new(DiagnosticError::runtime_error(
                    "filter with user-defined procedures requires evaluator integration (not yet implemented)".to_string(),
                    None,
                )));
            }
        };
        
        if keep {
            results.push(element);
        }
    }
    
    Ok(Value::list(results))
}

/// fold-left procedure
fn primitive_fold_left(args: &[Value]) -> Result<Value> {
    if args.len() < 3 {
        return Err(Box::new(DiagnosticError::runtime_error(
            "fold-left requires at least 3 arguments".to_string(),
            None,
        )));
    }
    
    let procedure = &args[0];
    let mut accumulator = args[1].clone();
    let lists = &args[2..];
    
    // Verify procedure is callable
    if !procedure.is_procedure() {
        return Err(Box::new(DiagnosticError::runtime_error(
            "fold-left first argument must be a procedure".to_string(),
            None,
        )));
    }
    
    // Convert all list arguments to proper lists and find minimum length
    let mut list_data = Vec::new();
    let mut min_length = usize::MAX;
    
    for (i, list_arg) in lists.iter().enumerate() {
        let list = list_arg.as_list().ok_or_else(|| {
            DiagnosticError::runtime_error(
                format!("fold-left argument {} must be a proper list", i + 3),
                None,
            )
        })?;
        min_length = min_length.min(list.len());
        list_data.push(list);
    }
    
    // If any list is empty, return accumulator immediately
    if min_length == 0 || min_length == usize::MAX {
        return Ok(accumulator);
    }
    
    // Apply procedure to accumulator and each position across all lists
    for i in 0..min_length {
        let mut proc_args = vec![accumulator];
        for list in &list_data {
            proc_args.push(list[i].clone());
        }
        
        // Apply the procedure - for now we can only handle primitive procedures
        match procedure {
            Value::Primitive(prim) => {
                accumulator = match &prim.implementation {
                    PrimitiveImpl::RustFn(func) => func(&proc_args)?,
                    PrimitiveImpl::Native(func) => func(&proc_args)?,
                    PrimitiveImpl::EvaluatorIntegrated(_) => {
                        return Err(Box::new(DiagnosticError::runtime_error(
                            "fold-left with EvaluatorIntegrated functions requires evaluator access (not yet implemented)".to_string(),
                            None,
                        )));
                    }
                    PrimitiveImpl::ForeignFn { .. } => {
                        return Err(Box::new(DiagnosticError::runtime_error(
                            "fold-left with foreign functions not yet implemented".to_string(),
                            None,
                        )));
                    }
                };
            },
            _ => {
                return Err(Box::new(DiagnosticError::runtime_error(
                    "fold-left with user-defined procedures requires evaluator integration (not yet implemented)".to_string(),
                    None,
                )));
            }
        }
    }
    
    Ok(accumulator)
}

/// fold-right procedure
fn primitive_fold_right(args: &[Value]) -> Result<Value> {
    if args.len() < 3 {
        return Err(Box::new(DiagnosticError::runtime_error(
            "fold-right requires at least 3 arguments".to_string(),
            None,
        )));
    }
    
    let procedure = &args[0];
    let mut accumulator = args[1].clone();
    let lists = &args[2..];
    
    // Verify procedure is callable
    if !procedure.is_procedure() {
        return Err(Box::new(DiagnosticError::runtime_error(
            "fold-right first argument must be a procedure".to_string(),
            None,
        )));
    }
    
    // Convert all list arguments to proper lists and find minimum length
    let mut list_data = Vec::new();
    let mut min_length = usize::MAX;
    
    for (i, list_arg) in lists.iter().enumerate() {
        let list = list_arg.as_list().ok_or_else(|| {
            DiagnosticError::runtime_error(
                format!("fold-right argument {} must be a proper list", i + 3),
                None,
            )
        })?;
        min_length = min_length.min(list.len());
        list_data.push(list);
    }
    
    // If any list is empty, return accumulator immediately
    if min_length == 0 || min_length == usize::MAX {
        return Ok(accumulator);
    }
    
    // Apply procedure from right to left (reverse order)
    for i in (0..min_length).rev() {
        let mut proc_args = Vec::new();
        for list in &list_data {
            proc_args.push(list[i].clone());
        }
        proc_args.push(accumulator);
        
        // Apply the procedure - for now we can only handle primitive procedures
        match procedure {
            Value::Primitive(prim) => {
                accumulator = match &prim.implementation {
                    PrimitiveImpl::RustFn(func) => func(&proc_args)?,
                    PrimitiveImpl::Native(func) => func(&proc_args)?,
                    PrimitiveImpl::EvaluatorIntegrated(_) => {
                        return Err(Box::new(DiagnosticError::runtime_error(
                            "fold-right with EvaluatorIntegrated functions requires evaluator access (not yet implemented)".to_string(),
                            None,
                        )));
                    }
                    PrimitiveImpl::ForeignFn { .. } => {
                        return Err(Box::new(DiagnosticError::runtime_error(
                            "fold-right with foreign functions not yet implemented".to_string(),
                            None,
                        )));
                    }
                };
            },
            _ => {
                return Err(Box::new(DiagnosticError::runtime_error(
                    "fold-right with user-defined procedures requires evaluator integration (not yet implemented)".to_string(),
                    None,
                )));
            }
        }
    }
    
    Ok(accumulator)
}

/// any procedure
fn primitive_any(args: &[Value]) -> Result<Value> {
    if args.len() < 2 {
        return Err(Box::new(DiagnosticError::runtime_error(
            "any requires at least 2 arguments".to_string(),
            None,
        )));
    }
    
    // Note: This is a simplified implementation
    // A full implementation would need to handle procedure calls with the evaluator
    Err(Box::new(DiagnosticError::runtime_error(
        "any requires evaluator integration (not yet implemented)".to_string(),
        None,
    )))
}

/// every procedure
fn primitive_every(args: &[Value]) -> Result<Value> {
    if args.len() < 2 {
        return Err(Box::new(DiagnosticError::runtime_error(
            "every requires at least 2 arguments".to_string(),
            None,
        )));
    }
    
    // Note: This is a simplified implementation
    // A full implementation would need to handle procedure calls with the evaluator
    Err(Box::new(DiagnosticError::runtime_error(
        "every requires evaluator integration (not yet implemented)".to_string(),
        None,
    )))
}

// ============= LIST UTILITY IMPLEMENTATIONS =============

/// member procedure
fn primitive_member(args: &[Value]) -> Result<Value> {
    if args.len() < 2 || args.len() > 3 {
        return Err(Box::new(DiagnosticError::runtime_error(
            format!("member expects 2 or 3 arguments, got {}", args.len()),
            None,
        )));
    }
    
    let obj = &args[0];
    let mut current = &args[1];
    
    // For now, we'll use default equality (equal?)
    // TODO: Handle custom comparison function when provided
    
    loop {
        match current {
            Value::Nil => return Ok(Value::boolean(false)),
            Value::Pair(car, cdr) => {
                if values_equal(obj, car) {
                    return Ok(current.clone());
                }
                current = cdr;
            }
            _ => {
                return Err(Box::new(DiagnosticError::runtime_error(
                    "member requires a proper list".to_string(),
                    None,
                )));
            }
        }
    }
}

/// memq procedure (eq? comparison)
fn primitive_memq(args: &[Value]) -> Result<Value> {
    if args.len() != 2 {
        return Err(Box::new(DiagnosticError::runtime_error(
            format!("memq expects 2 arguments, got {}", args.len()),
            None,
        )));
    }
    
    let obj = &args[0];
    let mut current = &args[1];
    
    loop {
        match current {
            Value::Nil => return Ok(Value::boolean(false)),
            Value::Pair(car, cdr) => {
                if values_eq(obj, car) {
                    return Ok(current.clone());
                }
                current = cdr;
            }
            _ => {
                return Err(Box::new(DiagnosticError::runtime_error(
                    "memq requires a proper list".to_string(),
                    None,
                )));
            }
        }
    }
}

/// memv procedure (eqv? comparison)
fn primitive_memv(args: &[Value]) -> Result<Value> {
    if args.len() != 2 {
        return Err(Box::new(DiagnosticError::runtime_error(
            format!("memv expects 2 arguments, got {}", args.len()),
            None,
        )));
    }
    
    let obj = &args[0];
    let mut current = &args[1];
    
    loop {
        match current {
            Value::Nil => return Ok(Value::boolean(false)),
            Value::Pair(car, cdr) => {
                if values_eqv(obj, car) {
                    return Ok(current.clone());
                }
                current = cdr;
            }
            _ => {
                return Err(Box::new(DiagnosticError::runtime_error(
                    "memv requires a proper list".to_string(),
                    None,
                )));
            }
        }
    }
}

/// assoc procedure
fn primitive_assoc(args: &[Value]) -> Result<Value> {
    if args.len() < 2 || args.len() > 3 {
        return Err(Box::new(DiagnosticError::runtime_error(
            format!("assoc expects 2 or 3 arguments, got {}", args.len()),
            None,
        )));
    }
    
    let obj = &args[0];
    let mut current = &args[1];
    
    loop {
        match current {
            Value::Nil => return Ok(Value::boolean(false)),
            Value::Pair(car, cdr) => {
                match car.as_ref() {
                    Value::Pair(key, _) => {
                        if values_equal(obj, key) {
                            return Ok((**car).clone());
                        }
                    }
                    _ => {
                        return Err(Box::new(DiagnosticError::runtime_error(
                            "assoc requires a list of pairs".to_string(),
                            None,
                        )));
                    }
                }
                current = cdr;
            }
            _ => {
                return Err(Box::new(DiagnosticError::runtime_error(
                    "assoc requires a proper list".to_string(),
                    None,
                )));
            }
        }
    }
}

/// assq procedure (eq? comparison)
fn primitive_assq(args: &[Value]) -> Result<Value> {
    if args.len() != 2 {
        return Err(Box::new(DiagnosticError::runtime_error(
            format!("assq expects 2 arguments, got {}", args.len()),
            None,
        )));
    }
    
    let obj = &args[0];
    let mut current = &args[1];
    
    loop {
        match current {
            Value::Nil => return Ok(Value::boolean(false)),
            Value::Pair(car, cdr) => {
                match car.as_ref() {
                    Value::Pair(key, _) => {
                        if values_eq(obj, key) {
                            return Ok((**car).clone());
                        }
                    }
                    _ => {
                        return Err(Box::new(DiagnosticError::runtime_error(
                            "assq requires a list of pairs".to_string(),
                            None,
                        )));
                    }
                }
                current = cdr;
            }
            _ => {
                return Err(Box::new(DiagnosticError::runtime_error(
                    "assq requires a proper list".to_string(),
                    None,
                )));
            }
        }
    }
}

/// assv procedure (eqv? comparison)
fn primitive_assv(args: &[Value]) -> Result<Value> {
    if args.len() != 2 {
        return Err(Box::new(DiagnosticError::runtime_error(
            format!("assv expects 2 arguments, got {}", args.len()),
            None,
        )));
    }
    
    let obj = &args[0];
    let mut current = &args[1];
    
    loop {
        match current {
            Value::Nil => return Ok(Value::boolean(false)),
            Value::Pair(car, cdr) => {
                match car.as_ref() {
                    Value::Pair(key, _) => {
                        if values_eqv(obj, key) {
                            return Ok((**car).clone());
                        }
                    }
                    _ => {
                        return Err(Box::new(DiagnosticError::runtime_error(
                            "assv requires a list of pairs".to_string(),
                            None,
                        )));
                    }
                }
                current = cdr;
            }
            _ => {
                return Err(Box::new(DiagnosticError::runtime_error(
                    "assv requires a proper list".to_string(),
                    None,
                )));
            }
        }
    }
}

/// sort procedure
fn primitive_sort(args: &[Value]) -> Result<Value> {
    if args.len() != 2 {
        return Err(Box::new(DiagnosticError::runtime_error(
            format!("sort expects 2 arguments, got {}", args.len()),
            None,
        )));
    }
    
    // Note: This is a simplified implementation
    // A full implementation would need to handle procedure calls with the evaluator
    Err(Box::new(DiagnosticError::runtime_error(
        "sort requires evaluator integration (not yet implemented)".to_string(),
        None,
    )))
}

// ============= HELPER FUNCTIONS =============

/// Checks if a value is a proper list.
fn is_proper_list(value: &Value) -> bool {
    let mut current = value;
    
    loop {
        match current {
            Value::Nil => return true,
            Value::Pair(_, cdr) => {
                current = cdr;
            }
            _ => return false,
        }
    }
}

/// Copies a list (shallow copy).
fn copy_list(value: &Value) -> Result<Value> {
    match value {
        Value::Nil => Ok(Value::Nil),
        Value::Pair(car, cdr) => {
            let copied_cdr = copy_list(cdr)?;
            Ok(Value::pair((**car).clone(), copied_cdr))
        }
        _ => Err(Box::new(DiagnosticError::runtime_error(
            "copy-list requires a list".to_string(),
            None,
        ))),
    }
}

/// Equality comparison functions (placeholders)
fn values_equal(a: &Value, b: &Value) -> bool {
    a == b // Using derived PartialEq for now
}

fn values_eq(a: &Value, b: &Value) -> bool {
    // eq? is stricter than equal? - reference equality for mutable objects
    a == b // Simplified for now
}

fn values_eqv(a: &Value, b: &Value) -> bool {
    // eqv? is between eq? and equal?
    a == b // Simplified for now
}

// ============= SRFI-1 MANIPULATION IMPLEMENTATION =============

/// take - Take the first n elements of a list
fn srfi1_take(args: &[Value]) -> Result<Value> {
    if args.len() != 2 {
        return Err(Box::new(DiagnosticError::runtime_error(
            format!("take expects 2 arguments, got {}", args.len()),
            None,
        )));
    }
    
    let list_arg = &args[0];
    let n = args[1].as_integer().ok_or_else(|| {
        DiagnosticError::runtime_error(
            "take n must be a non-negative integer".to_string(),
            None,
        )
    })?;
    
    if n < 0 {
        return Err(Box::new(DiagnosticError::runtime_error(
            "take n must be non-negative".to_string(),
            None,
        )));
    }
    
    let mut current = list_arg;
    let mut result = Vec::new();
    let mut count = 0;
    
    while count < n {
        match current {
            Value::Nil => break,
            Value::Pair(car, cdr) => {
                result.push((**car).clone());
                current = cdr;
                count += 1;
            }
            _ => {
                return Err(Box::new(DiagnosticError::runtime_error(
                    "take requires a proper list".to_string(),
                    None,
                )));
            }
        }
    }
    
    if count < n {
        return Err(Box::new(DiagnosticError::runtime_error(
            "take: list too short".to_string(),
            None,
        )));
    }
    
    Ok(Value::list(result))
}

/// drop - Drop the first n elements of a list
fn srfi1_drop(args: &[Value]) -> Result<Value> {
    if args.len() != 2 {
        return Err(Box::new(DiagnosticError::runtime_error(
            format!("drop expects 2 arguments, got {}", args.len()),
            None,
        )));
    }
    
    let mut list_arg = args[0].clone();
    let n = args[1].as_integer().ok_or_else(|| {
        DiagnosticError::runtime_error(
            "drop n must be a non-negative integer".to_string(),
            None,
        )
    })?;
    
    if n < 0 {
        return Err(Box::new(DiagnosticError::runtime_error(
            "drop n must be non-negative".to_string(),
            None,
        )));
    }
    
    let mut count = 0;
    while count < n {
        match list_arg {
            Value::Nil => {
                return Err(Box::new(DiagnosticError::runtime_error(
                    "drop: list too short".to_string(),
                    None,
                )));
            }
            Value::Pair(_, cdr) => {
                list_arg = cdr.as_ref().clone();
                count += 1;
            }
            _ => {
                return Err(Box::new(DiagnosticError::runtime_error(
                    "drop requires a proper list".to_string(),
                    None,
                )));
            }
        }
    }
    
    Ok(list_arg)
}

/// take-right - Take the last n elements of a list
fn srfi1_take_right(args: &[Value]) -> Result<Value> {
    if args.len() != 2 {
        return Err(Box::new(DiagnosticError::runtime_error(
            format!("take-right expects 2 arguments, got {}", args.len()),
            None,
        )));
    }
    
    let list_arg = &args[0];
    let n = args[1].as_integer().ok_or_else(|| {
        DiagnosticError::runtime_error(
            "take-right n must be a non-negative integer".to_string(),
            None,
        )
    })?;
    
    if n < 0 {
        return Err(Box::new(DiagnosticError::runtime_error(
            "take-right n must be non-negative".to_string(),
            None,
        )));
    }
    
    let list = list_arg.as_list().ok_or_else(|| {
        DiagnosticError::runtime_error(
            "take-right requires a proper list".to_string(),
            None,
        )
    })?;
    
    let list_len = list.len();
    if (n as usize) > list_len {
        return Err(Box::new(DiagnosticError::runtime_error(
            "take-right: n larger than list length".to_string(),
            None,
        )));
    }
    
    let start_idx = list_len - (n as usize);
    let result = list[start_idx..].to_vec();
    Ok(Value::list(result))
}

/// drop-right - Drop the last n elements of a list
fn srfi1_drop_right(args: &[Value]) -> Result<Value> {
    if args.len() != 2 {
        return Err(Box::new(DiagnosticError::runtime_error(
            format!("drop-right expects 2 arguments, got {}", args.len()),
            None,
        )));
    }
    
    let list_arg = &args[0];
    let n = args[1].as_integer().ok_or_else(|| {
        DiagnosticError::runtime_error(
            "drop-right n must be a non-negative integer".to_string(),
            None,
        )
    })?;
    
    if n < 0 {
        return Err(Box::new(DiagnosticError::runtime_error(
            "drop-right n must be non-negative".to_string(),
            None,
        )));
    }
    
    let list = list_arg.as_list().ok_or_else(|| {
        DiagnosticError::runtime_error(
            "drop-right requires a proper list".to_string(),
            None,
        )
    })?;
    
    let list_len = list.len();
    if (n as usize) > list_len {
        return Ok(Value::Nil);
    }
    
    let end_idx = list_len - (n as usize);
    let result = list[..end_idx].to_vec();
    Ok(Value::list(result))
}

/// take-while - Take elements while predicate is true
fn srfi1_take_while(args: &[Value]) -> Result<Value> {
    if args.len() != 2 {
        return Err(Box::new(DiagnosticError::runtime_error(
            format!("take-while expects 2 arguments, got {}", args.len()),
            None,
        )));
    }
    
    let predicate = &args[0];
    let list_arg = &args[1];
    
    if !predicate.is_procedure() {
        return Err(Box::new(DiagnosticError::runtime_error(
            "take-while first argument must be a procedure".to_string(),
            None,
        )));
    }
    
    let list = list_arg.as_list().ok_or_else(|| {
        DiagnosticError::runtime_error(
            "take-while requires a proper list".to_string(),
            None,
        )
    })?;
    
    let mut result = Vec::new();
    
    for element in list {
        let proc_args = vec![element.clone()];
        
        let should_take = match predicate {
            Value::Primitive(prim) => {
                let pred_result = match &prim.implementation {
                    PrimitiveImpl::RustFn(func) => func(&proc_args)?,
                    PrimitiveImpl::Native(func) => func(&proc_args)?,
                    PrimitiveImpl::EvaluatorIntegrated(_) => {
                        return Err(Box::new(DiagnosticError::runtime_error(
                            "take-while with evaluator-integrated functions requires evaluator access".to_string(),
                            None,
                        )));
                    }
                    PrimitiveImpl::ForeignFn { .. } => {
                        return Err(Box::new(DiagnosticError::runtime_error(
                            "take-while with foreign functions not yet implemented".to_string(),
                            None,
                        )));
                    }
                };
                pred_result.is_truthy()
            },
            _ => {
                return Err(Box::new(DiagnosticError::runtime_error(
                    "take-while with user-defined procedures requires evaluator integration".to_string(),
                    None,
                )));
            }
        };
        
        if should_take {
            result.push(element);
        } else {
            break;
        }
    }
    
    Ok(Value::list(result))
}

/// drop-while - Drop elements while predicate is true
fn srfi1_drop_while(args: &[Value]) -> Result<Value> {
    if args.len() != 2 {
        return Err(Box::new(DiagnosticError::runtime_error(
            format!("drop-while expects 2 arguments, got {}", args.len()),
            None,
        )));
    }
    
    let predicate = &args[0];
    let mut current = &args[1];
    
    if !predicate.is_procedure() {
        return Err(Box::new(DiagnosticError::runtime_error(
            "drop-while first argument must be a procedure".to_string(),
            None,
        )));
    }
    
    loop {
        match current {
            Value::Nil => return Ok(Value::Nil),
            Value::Pair(car, cdr) => {
                let proc_args = vec![(**car).clone()];
                
                let should_drop = match predicate {
                    Value::Primitive(prim) => {
                        let pred_result = match &prim.implementation {
                            PrimitiveImpl::RustFn(func) => func(&proc_args)?,
                            PrimitiveImpl::Native(func) => func(&proc_args)?,
                            PrimitiveImpl::EvaluatorIntegrated(_) => {
                                return Err(Box::new(DiagnosticError::runtime_error(
                                    "drop-while with evaluator-integrated functions requires evaluator access".to_string(),
                                    None,
                                )));
                            }
                            PrimitiveImpl::ForeignFn { .. } => {
                                return Err(Box::new(DiagnosticError::runtime_error(
                                    "drop-while with foreign functions not yet implemented".to_string(),
                                    None,
                                )));
                            }
                        };
                        pred_result.is_truthy()
                    },
                    _ => {
                        return Err(Box::new(DiagnosticError::runtime_error(
                            "drop-while with user-defined procedures requires evaluator integration".to_string(),
                            None,
                        )));
                    }
                };
                
                if should_drop {
                    current = cdr;
                } else {
                    return Ok(current.clone());
                }
            }
            _ => {
                return Err(Box::new(DiagnosticError::runtime_error(
                    "drop-while requires a proper list".to_string(),
                    None,
                )));
            }
        }
    }
}

/// split-at - Split a list at position n
fn srfi1_split_at(args: &[Value]) -> Result<Value> {
    if args.len() != 2 {
        return Err(Box::new(DiagnosticError::runtime_error(
            format!("split-at expects 2 arguments, got {}", args.len()),
            None,
        )));
    }
    
    let list_arg = &args[0];
    let n = args[1].as_integer().ok_or_else(|| {
        DiagnosticError::runtime_error(
            "split-at n must be a non-negative integer".to_string(),
            None,
        )
    })?;
    
    if n < 0 {
        return Err(Box::new(DiagnosticError::runtime_error(
            "split-at n must be non-negative".to_string(),
            None,
        )));
    }
    
    let list = list_arg.as_list().ok_or_else(|| {
        DiagnosticError::runtime_error(
            "split-at requires a proper list".to_string(),
            None,
        )
    })?;
    
    let n_usize = n as usize;
    if n_usize > list.len() {
        return Err(Box::new(DiagnosticError::runtime_error(
            "split-at: index out of bounds".to_string(),
            None,
        )));
    }
    
    let (prefix, suffix) = list.split_at(n_usize);
    Ok(Value::pair(
        Value::list(prefix.to_vec()),
        Value::list(suffix.to_vec()),
    ))
}

/// last - Get the last element of a list
fn srfi1_last(args: &[Value]) -> Result<Value> {
    if args.len() != 1 {
        return Err(Box::new(DiagnosticError::runtime_error(
            format!("last expects 1 argument, got {}", args.len()),
            None,
        )));
    }
    
    let list = args[0].as_list().ok_or_else(|| {
        DiagnosticError::runtime_error(
            "last requires a proper list".to_string(),
            None,
        )
    })?;
    
    if list.is_empty() {
        return Err(Box::new(DiagnosticError::runtime_error(
            "last: empty list".to_string(),
            None,
        )));
    }
    
    Ok(list[list.len() - 1].clone())
}

/// last-pair - Get the last pair of a list
fn srfi1_last_pair(args: &[Value]) -> Result<Value> {
    if args.len() != 1 {
        return Err(Box::new(DiagnosticError::runtime_error(
            format!("last-pair expects 1 argument, got {}", args.len()),
            None,
        )));
    }
    
    let mut current = &args[0];
    
    loop {
        match current {
            Value::Nil => {
                return Err(Box::new(DiagnosticError::runtime_error(
                    "last-pair: empty list".to_string(),
                    None,
                )));
            }
            Value::Pair(_, cdr) => {
                let last_pair = current.clone();
                if cdr.is_nil() {
                    return Ok(last_pair);
                }
                current = cdr;
            }
            _ => {
                return Err(Box::new(DiagnosticError::runtime_error(
                    "last-pair requires a list".to_string(),
                    None,
                )));
            }
        }
    }
}

// ============= SRFI-1 FOLDING IMPLEMENTATION =============

/// fold - SRFI-1 version of fold (different argument order)
/// (fold kons knil clist1 clist2 ...)
fn srfi1_fold(args: &[Value]) -> Result<Value> {
    if args.len() < 3 {
        return Err(Box::new(DiagnosticError::runtime_error(
            "fold requires at least 3 arguments".to_string(),
            None,
        )));
    }
    
    let procedure = &args[0];
    let mut accumulator = args[1].clone();
    let lists = &args[2..];
    
    if !procedure.is_procedure() {
        return Err(Box::new(DiagnosticError::runtime_error(
            "fold first argument must be a procedure".to_string(),
            None,
        )));
    }
    
    // Convert all list arguments to proper lists and find minimum length
    let mut list_data = Vec::new();
    let mut min_length = usize::MAX;
    
    for (i, list_arg) in lists.iter().enumerate() {
        let list = list_arg.as_list().ok_or_else(|| {
            DiagnosticError::runtime_error(
                format!("fold argument {} must be a proper list", i + 3),
                None,
            )
        })?;
        min_length = min_length.min(list.len());
        list_data.push(list);
    }
    
    if min_length == 0 || min_length == usize::MAX {
        return Ok(accumulator);
    }
    
    // Apply procedure to accumulator and each position across all lists
    for i in 0..min_length {
        let mut proc_args = vec![accumulator];
        for list in &list_data {
            proc_args.push(list[i].clone());
        }
        
        match procedure {
            Value::Primitive(prim) => {
                accumulator = match &prim.implementation {
                    PrimitiveImpl::RustFn(func) => func(&proc_args)?,
                    PrimitiveImpl::Native(func) => func(&proc_args)?,
                    PrimitiveImpl::EvaluatorIntegrated(_) => {
                        return Err(Box::new(DiagnosticError::runtime_error(
                            "fold with evaluator-integrated functions requires evaluator access".to_string(),
                            None,
                        )));
                    }
                    PrimitiveImpl::ForeignFn { .. } => {
                        return Err(Box::new(DiagnosticError::runtime_error(
                            "fold with foreign functions not yet implemented".to_string(),
                            None,
                        )));
                    }
                };
            },
            _ => {
                return Err(Box::new(DiagnosticError::runtime_error(
                    "fold with user-defined procedures requires evaluator integration".to_string(),
                    None,
                )));
            }
        }
    }
    
    Ok(accumulator)
}

/// fold-right - SRFI-1 version of fold-right
fn srfi1_fold_right(args: &[Value]) -> Result<Value> {
    if args.len() < 3 {
        return Err(Box::new(DiagnosticError::runtime_error(
            "fold-right requires at least 3 arguments".to_string(),
            None,
        )));
    }
    
    let procedure = &args[0];
    let mut accumulator = args[1].clone();
    let lists = &args[2..];
    
    if !procedure.is_procedure() {
        return Err(Box::new(DiagnosticError::runtime_error(
            "fold-right first argument must be a procedure".to_string(),
            None,
        )));
    }
    
    // Convert all list arguments to proper lists and find minimum length
    let mut list_data = Vec::new();
    let mut min_length = usize::MAX;
    
    for (i, list_arg) in lists.iter().enumerate() {
        let list = list_arg.as_list().ok_or_else(|| {
            DiagnosticError::runtime_error(
                format!("fold-right argument {} must be a proper list", i + 3),
                None,
            )
        })?;
        min_length = min_length.min(list.len());
        list_data.push(list);
    }
    
    if min_length == 0 || min_length == usize::MAX {
        return Ok(accumulator);
    }
    
    // Apply procedure from right to left (reverse order)
    for i in (0..min_length).rev() {
        let mut proc_args = Vec::new();
        for list in &list_data {
            proc_args.push(list[i].clone());
        }
        proc_args.push(accumulator);
        
        match procedure {
            Value::Primitive(prim) => {
                accumulator = match &prim.implementation {
                    PrimitiveImpl::RustFn(func) => func(&proc_args)?,
                    PrimitiveImpl::Native(func) => func(&proc_args)?,
                    PrimitiveImpl::EvaluatorIntegrated(_) => {
                        return Err(Box::new(DiagnosticError::runtime_error(
                            "fold-right with evaluator-integrated functions requires evaluator access".to_string(),
                            None,
                        )));
                    }
                    PrimitiveImpl::ForeignFn { .. } => {
                        return Err(Box::new(DiagnosticError::runtime_error(
                            "fold-right with foreign functions not yet implemented".to_string(),
                            None,
                        )));
                    }
                };
            },
            _ => {
                return Err(Box::new(DiagnosticError::runtime_error(
                    "fold-right with user-defined procedures requires evaluator integration".to_string(),
                    None,
                )));
            }
        }
    }
    
    Ok(accumulator)
}

/// reduce - Reduce a list using a binary operation
fn srfi1_reduce(args: &[Value]) -> Result<Value> {
    if args.len() != 3 {
        return Err(Box::new(DiagnosticError::runtime_error(
            format!("reduce expects 3 arguments, got {}", args.len()),
            None,
        )));
    }
    
    let procedure = &args[0];
    let ridentity = &args[1];
    let list_arg = &args[2];
    
    if !procedure.is_procedure() {
        return Err(Box::new(DiagnosticError::runtime_error(
            "reduce first argument must be a procedure".to_string(),
            None,
        )));
    }
    
    let list = list_arg.as_list().ok_or_else(|| {
        DiagnosticError::runtime_error(
            "reduce requires a proper list".to_string(),
            None,
        )
    })?;
    
    if list.is_empty() {
        return Ok(ridentity.clone());
    }
    
    if list.len() == 1 {
        return Ok(list[0].clone());
    }
    
    let mut accumulator = list[0].clone();
    
    for element in &list[1..] {
        let proc_args = vec![accumulator, element.clone()];
        
        match procedure {
            Value::Primitive(prim) => {
                accumulator = match &prim.implementation {
                    PrimitiveImpl::RustFn(func) => func(&proc_args)?,
                    PrimitiveImpl::Native(func) => func(&proc_args)?,
                    PrimitiveImpl::EvaluatorIntegrated(_) => {
                        return Err(Box::new(DiagnosticError::runtime_error(
                            "reduce with evaluator-integrated functions requires evaluator access".to_string(),
                            None,
                        )));
                    }
                    PrimitiveImpl::ForeignFn { .. } => {
                        return Err(Box::new(DiagnosticError::runtime_error(
                            "reduce with foreign functions not yet implemented".to_string(),
                            None,
                        )));
                    }
                };
            },
            _ => {
                return Err(Box::new(DiagnosticError::runtime_error(
                    "reduce with user-defined procedures requires evaluator integration".to_string(),
                    None,
                )));
            }
        }
    }
    
    Ok(accumulator)
}

/// reduce-right - Reduce a list from right to left
fn srfi1_reduce_right(args: &[Value]) -> Result<Value> {
    if args.len() != 3 {
        return Err(Box::new(DiagnosticError::runtime_error(
            format!("reduce-right expects 3 arguments, got {}", args.len()),
            None,
        )));
    }
    
    let procedure = &args[0];
    let ridentity = &args[1];
    let list_arg = &args[2];
    
    if !procedure.is_procedure() {
        return Err(Box::new(DiagnosticError::runtime_error(
            "reduce-right first argument must be a procedure".to_string(),
            None,
        )));
    }
    
    let list = list_arg.as_list().ok_or_else(|| {
        DiagnosticError::runtime_error(
            "reduce-right requires a proper list".to_string(),
            None,
        )
    })?;
    
    if list.is_empty() {
        return Ok(ridentity.clone());
    }
    
    if list.len() == 1 {
        return Ok(list[0].clone());
    }
    
    let mut accumulator = list[list.len() - 1].clone();
    
    for element in list[..list.len() - 1].iter().rev() {
        let proc_args = vec![element.clone(), accumulator];
        
        match procedure {
            Value::Primitive(prim) => {
                accumulator = match &prim.implementation {
                    PrimitiveImpl::RustFn(func) => func(&proc_args)?,
                    PrimitiveImpl::Native(func) => func(&proc_args)?,
                    PrimitiveImpl::EvaluatorIntegrated(_) => {
                        return Err(Box::new(DiagnosticError::runtime_error(
                            "reduce-right with evaluator-integrated functions requires evaluator access".to_string(),
                            None,
                        )));
                    }
                    PrimitiveImpl::ForeignFn { .. } => {
                        return Err(Box::new(DiagnosticError::runtime_error(
                            "reduce-right with foreign functions not yet implemented".to_string(),
                            None,
                        )));
                    }
                };
            },
            _ => {
                return Err(Box::new(DiagnosticError::runtime_error(
                    "reduce-right with user-defined procedures requires evaluator integration".to_string(),
                    None,
                )));
            }
        }
    }
    
    Ok(accumulator)
}

/// unfold - Generate a list by repeatedly applying functions
fn srfi1_unfold(args: &[Value]) -> Result<Value> {
    if args.len() < 4 || args.len() > 5 {
        return Err(Box::new(DiagnosticError::runtime_error(
            format!("unfold expects 4 or 5 arguments, got {}", args.len()),
            None,
        )));
    }
    
    // For now, return not implemented
    Err(Box::new(DiagnosticError::runtime_error(
        "unfold requires evaluator integration (not yet implemented)".to_string(),
        None,
    )))
}

/// unfold-right - Generate a list in reverse by repeatedly applying functions
fn srfi1_unfold_right(args: &[Value]) -> Result<Value> {
    if args.len() < 4 || args.len() > 5 {
        return Err(Box::new(DiagnosticError::runtime_error(
            format!("unfold-right expects 4 or 5 arguments, got {}", args.len()),
            None,
        )));
    }
    
    // For now, return not implemented
    Err(Box::new(DiagnosticError::runtime_error(
        "unfold-right requires evaluator integration (not yet implemented)".to_string(),
        None,
    )))
}

// ============= SRFI-1 ASSOCIATION IMPLEMENTATION =============

/// alist-cons - Add a key-value pair to an association list
fn srfi1_alist_cons(args: &[Value]) -> Result<Value> {
    if args.len() != 3 {
        return Err(Box::new(DiagnosticError::runtime_error(
            format!("alist-cons expects 3 arguments, got {}", args.len()),
            None,
        )));
    }
    
    let key = &args[0];
    let datum = &args[1];
    let alist = &args[2];
    
    let pair = Value::pair(key.clone(), datum.clone());
    Ok(Value::pair(pair, alist.clone()))
}

/// alist-copy - Copy an association list
fn srfi1_alist_copy(args: &[Value]) -> Result<Value> {
    if args.len() != 1 {
        return Err(Box::new(DiagnosticError::runtime_error(
            format!("alist-copy expects 1 argument, got {}", args.len()),
            None,
        )));
    }
    
    copy_alist(&args[0])
}

/// alist-delete - Delete entries with a given key from an association list
fn srfi1_alist_delete(args: &[Value]) -> Result<Value> {
    if args.len() < 2 || args.len() > 3 {
        return Err(Box::new(DiagnosticError::runtime_error(
            format!("alist-delete expects 2 or 3 arguments, got {}", args.len()),
            None,
        )));
    }
    
    let key = &args[0];
    let alist = &args[1];
    // TODO: Handle custom equality predicate when provided
    
    let mut result = Vec::new();
    let mut current = alist;
    
    loop {
        match current {
            Value::Nil => break,
            Value::Pair(car, cdr) => {
                match car.as_ref() {
                    Value::Pair(entry_key, entry_value) => {
                        if !values_equal(key, entry_key) {
                            let entry = Value::pair((**entry_key).clone(), (**entry_value).clone());
                            result.push(entry);
                        }
                    }
                    _ => {
                        return Err(Box::new(DiagnosticError::runtime_error(
                            "alist-delete requires a list of pairs".to_string(),
                            None,
                        )));
                    }
                }
                current = cdr;
            }
            _ => {
                return Err(Box::new(DiagnosticError::runtime_error(
                    "alist-delete requires a proper list".to_string(),
                    None,
                )));
            }
        }
    }
    
    Ok(Value::list(result))
}

// ============= SRFI-1 COMPARISON IMPLEMENTATION =============

/// list= - Test if lists are equal element-wise
fn srfi1_list_equal(args: &[Value]) -> Result<Value> {
    if args.is_empty() {
        return Err(Box::new(DiagnosticError::runtime_error(
            "list= requires at least 1 argument".to_string(),
            None,
        )));
    }
    
    if args.len() == 1 {
        return Ok(Value::boolean(true));
    }
    
    // For now, use the first argument as the equality predicate if it's a procedure
    // Otherwise, use default equality
    let (eq_pred, lists) = if args[0].is_procedure() {
        (&args[0], &args[1..])
    } else {
        // No custom equality predicate, use default
        return Ok(Value::boolean(lists_equal_default(&args[0], &args[1..])));
    };
    
    if lists.len() < 2 {
        return Ok(Value::boolean(true));
    }
    
    // Convert all to proper lists
    let mut list_data = Vec::new();
    for (i, list_arg) in lists.iter().enumerate() {
        let list = list_arg.as_list().ok_or_else(|| {
            DiagnosticError::runtime_error(
                format!("list= argument {} must be a proper list", i + 2),
                None,
            )
        })?;
        list_data.push(list);
    }
    
    // Check that all lists have the same length
    let first_len = list_data[0].len();
    for list in &list_data[1..] {
        if list.len() != first_len {
            return Ok(Value::boolean(false));
        }
    }
    
    // Compare elements pairwise using the equality predicate
    for i in 0..first_len {
        for j in 1..list_data.len() {
            let proc_args = vec![list_data[0][i].clone(), list_data[j][i].clone()];
            
            let are_equal = match eq_pred {
                Value::Primitive(prim) => {
                    let result = match &prim.implementation {
                        PrimitiveImpl::RustFn(func) => func(&proc_args)?,
                        PrimitiveImpl::Native(func) => func(&proc_args)?,
                        PrimitiveImpl::EvaluatorIntegrated(_) => {
                            return Err(Box::new(DiagnosticError::runtime_error(
                                "list= with evaluator-integrated functions requires evaluator access".to_string(),
                                None,
                            )));
                        }
                        PrimitiveImpl::ForeignFn { .. } => {
                            return Err(Box::new(DiagnosticError::runtime_error(
                                "list= with foreign functions not yet implemented".to_string(),
                                None,
                            )));
                        }
                    };
                    result.is_truthy()
                },
                _ => {
                    return Err(Box::new(DiagnosticError::runtime_error(
                        "list= with user-defined procedures requires evaluator integration".to_string(),
                        None,
                    )));
                }
            };
            
            if !are_equal {
                return Ok(Value::boolean(false));
            }
        }
    }
    
    Ok(Value::boolean(true))
}

// ============= SRFI-1 HELPER FUNCTIONS =============

/// Check if a value is a circular list (using Floyd's cycle detection)
fn is_circular_list(value: &Value) -> bool {
    let mut slow = value;
    let mut fast = value;
    
    loop {
        // Move fast pointer two steps
        match fast {
            Value::Pair(_, cdr1) => {
                match cdr1.as_ref() {
                    Value::Pair(_, cdr2) => {
                        fast = cdr2;
                    }
                    Value::Nil => return false,
                    _ => return false, // Not a proper list structure
                }
            }
            Value::Nil => return false,
            _ => return false,
        }
        
        // Move slow pointer one step
        match slow {
            Value::Pair(_, cdr) => {
                slow = cdr;
            }
            Value::Nil => return false,
            _ => return false,
        }
        
        // Check if they meet (cycle detected)
        if std::ptr::eq(slow, fast) {
            return true;
        }
    }
}

/// Check if a value is a dotted (improper) list
fn is_dotted_list(value: &Value) -> bool {
    let mut current = value;
    
    loop {
        match current {
            Value::Nil => return false, // Proper list
            Value::Pair(_, cdr) => {
                current = cdr;
            }
            _ => return true, // Improper list (dotted)
        }
    }
}

/// Copy an association list (deep copy of pairs)
fn copy_alist(alist: &Value) -> Result<Value> {
    let mut result = Vec::new();
    let mut current = alist;
    
    loop {
        match current {
            Value::Nil => break,
            Value::Pair(car, cdr) => {
                match car.as_ref() {
                    Value::Pair(key, value) => {
                        let copied_pair = Value::pair((**key).clone(), (**value).clone());
                        result.push(copied_pair);
                    }
                    _ => {
                        return Err(Box::new(DiagnosticError::runtime_error(
                            "alist-copy requires a list of pairs".to_string(),
                            None,
                        )));
                    }
                }
                current = cdr;
            }
            _ => {
                return Err(Box::new(DiagnosticError::runtime_error(
                    "alist-copy requires a proper list".to_string(),
                    None,
                )));
            }
        }
    }
    
    Ok(Value::list(result))
}

/// Check if multiple lists are equal using default equality
fn lists_equal_default(first: &Value, rest: &[Value]) -> bool {
    let first_list = match first.as_list() {
        Some(list) => list,
        None => return false,
    };
    
    for other in rest {
        let other_list = match other.as_list() {
            Some(list) => list,
            None => return false,
        };
        
        if first_list.len() != other_list.len() {
            return false;
        }
        
        for (a, b) in first_list.iter().zip(other_list.iter()) {
            if !values_equal(a, b) {
                return false;
            }
        }
    }
    
    true
}

#[cfg(test)]
mod tests {
    use super::*;
    
    

    #[test]
    fn test_cons_car_cdr() {
        let args = vec![Value::integer(1), Value::integer(2)];
        let pair = primitive_cons(&args).unwrap();
        
        let car_result = primitive_car(&[pair.clone()]).unwrap();
        assert_eq!(car_result, Value::integer(1));
        
        let cdr_result = primitive_cdr(&[pair]).unwrap();
        assert_eq!(cdr_result, Value::integer(2));
    }
    
    #[test]
    fn test_list_construction() {
        let args = vec![Value::integer(1), Value::integer(2), Value::integer(3)];
        let list = primitive_list(&args).unwrap();
        
        // Test that it's a proper list
        assert!(is_proper_list(&list));
        
        // Test list length
        let length = primitive_length(&[list]).unwrap();
        assert_eq!(length, Value::integer(3));
    }
    
    #[test]
    fn test_list_predicates() {
        let pair = Value::pair(Value::integer(1), Value::integer(2));
        assert_eq!(primitive_pair_p(&[pair]).unwrap(), Value::boolean(true));
        
        let nil = Value::Nil;
        assert_eq!(primitive_null_p(&[nil]).unwrap(), Value::boolean(true));
        
        let proper_list = Value::list(vec![Value::integer(1), Value::integer(2)]);
        assert_eq!(primitive_list_p(&[proper_list]).unwrap(), Value::boolean(true));
    }
    
    #[test]
    fn test_list_ref() {
        let list = Value::list(vec![
            Value::string("a"),
            Value::string("b"),
            Value::string("c"),
        ]);
        
        let args = vec![list, Value::integer(1)];
        let result = primitive_list_ref(&args).unwrap();
        assert_eq!(result, Value::string("b"));
    }
    
    #[test]
    fn test_append() {
        let list1 = Value::list(vec![Value::integer(1), Value::integer(2)]);
        let list2 = Value::list(vec![Value::integer(3), Value::integer(4)]);
        
        let args = vec![list1, list2];
        let result = primitive_append(&args).unwrap();
        
        // Result should be (1 2 3 4)
        let expected = Value::list(vec![
            Value::integer(1),
            Value::integer(2),
            Value::integer(3),
            Value::integer(4),
        ]);
        assert_eq!(result, expected);
    }
    
    #[test]
    fn test_reverse() {
        let list = Value::list(vec![
            Value::integer(1),
            Value::integer(2),
            Value::integer(3),
        ]);
        
        let result = primitive_reverse(&[list]).unwrap();
        let expected = Value::list(vec![
            Value::integer(3),
            Value::integer(2),
            Value::integer(1),
        ]);
        assert_eq!(result, expected);
    }
    
    #[test]
    fn test_member() {
        let list = Value::list(vec![
            Value::string("a"),
            Value::string("b"),
            Value::string("c"),
        ]);
        
        let args = vec![Value::string("b"), list];
        let result = primitive_member(&args).unwrap();
        
        // Should return the tail starting with "b"
        assert!(result.is_pair());
    }
    
    #[test]
    fn test_map_single_list() {
        // Test map with a simple procedure that doubles numbers
        let double_proc = Arc::new(PrimitiveProcedure {
            name: "double".to_string(),
            arity_min: 1,
            arity_max: Some(1),
            implementation: PrimitiveImpl::RustFn(|args| {
                if let Some(n) = args[0].as_number() {
                    Ok(Value::number(n * 2.0))
                } else {
                    Ok(Value::Unspecified)
                }
            }),
            effects: vec![Effect::Pure],
        });
        
        let list = Value::list(vec![Value::number(1.0), Value::number(2.0), Value::number(3.0)]);
        let args = vec![Value::Primitive(double_proc), list];
        let result = primitive_map(&args).unwrap();
        
        let expected = Value::list(vec![Value::number(2.0), Value::number(4.0), Value::number(6.0)]);
        assert_eq!(result, expected);
    }
    
    #[test]
    fn test_map_multiple_lists() {
        // Test map with multiple lists
        let add_proc = Arc::new(PrimitiveProcedure {
            name: "+".to_string(),
            arity_min: 0,
            arity_max: None,
            implementation: PrimitiveImpl::RustFn(|args| {
                let sum = args.iter()
                    .filter_map(|v| v.as_number())
                    .fold(0.0, |acc, n| acc + n);
                Ok(Value::number(sum))
            }),
            effects: vec![Effect::Pure],
        });
        
        let list1 = Value::list(vec![Value::number(1.0), Value::number(2.0), Value::number(3.0)]);
        let list2 = Value::list(vec![Value::number(4.0), Value::number(5.0), Value::number(6.0)]);
        let args = vec![Value::Primitive(add_proc), list1, list2];
        let result = primitive_map(&args).unwrap();
        
        let expected = Value::list(vec![Value::number(5.0), Value::number(7.0), Value::number(9.0)]);
        assert_eq!(result, expected);
    }
    
    #[test]
    fn test_map_different_lengths() {
        // Test map with lists of different lengths - should use shortest
        let add_proc = Arc::new(PrimitiveProcedure {
            name: "+".to_string(),
            arity_min: 0,
            arity_max: None,
            implementation: PrimitiveImpl::RustFn(|args| {
                let sum = args.iter()
                    .filter_map(|v| v.as_number())
                    .fold(0.0, |acc, n| acc + n);
                Ok(Value::number(sum))
            }),
            effects: vec![Effect::Pure],
        });
        
        let list1 = Value::list(vec![Value::number(1.0), Value::number(2.0)]);
        let list2 = Value::list(vec![Value::number(4.0), Value::number(5.0), Value::number(6.0)]);
        let args = vec![Value::Primitive(add_proc), list1, list2];
        let result = primitive_map(&args).unwrap();
        
        let expected = Value::list(vec![Value::number(5.0), Value::number(7.0)]);
        assert_eq!(result, expected);
    }
    
    #[test]
    fn test_map_empty_list() {
        let double_proc = Arc::new(PrimitiveProcedure {
            name: "double".to_string(),
            arity_min: 1,
            arity_max: Some(1),
            implementation: PrimitiveImpl::RustFn(|args| {
                if let Some(n) = args[0].as_number() {
                    Ok(Value::number(n * 2.0))
                } else {
                    Ok(Value::Unspecified)
                }
            }),
            effects: vec![Effect::Pure],
        });
        
        let empty_list = Value::Nil;
        let args = vec![Value::Primitive(double_proc), empty_list];
        let result = primitive_map(&args).unwrap();
        
        assert_eq!(result, Value::Nil);
    }
    
    #[test]
    fn test_for_each_basic() {
        // Test for-each with a simple side-effect procedure
        let identity_proc = Arc::new(PrimitiveProcedure {
            name: "identity".to_string(),
            arity_min: 1,
            arity_max: Some(1),
            implementation: PrimitiveImpl::RustFn(|args| Ok(args[0].clone())),
            effects: vec![Effect::Pure],
        });
        
        let list = Value::list(vec![Value::number(1.0), Value::number(2.0), Value::number(3.0)]);
        let args = vec![Value::Primitive(identity_proc), list];
        let result = primitive_for_each(&args).unwrap();
        
        // for-each should return unspecified
        assert_eq!(result, Value::Unspecified);
    }
    
    #[test]
    fn test_for_each_multiple_lists() {
        let add_proc = Arc::new(PrimitiveProcedure {
            name: "+".to_string(),
            arity_min: 0,
            arity_max: None,
            implementation: PrimitiveImpl::RustFn(|args| {
                let sum = args.iter()
                    .filter_map(|v| v.as_number())
                    .fold(0.0, |acc, n| acc + n);
                Ok(Value::number(sum))
            }),
            effects: vec![Effect::Pure],
        });
        
        let list1 = Value::list(vec![Value::number(1.0), Value::number(2.0)]);
        let list2 = Value::list(vec![Value::number(4.0), Value::number(5.0)]);
        let args = vec![Value::Primitive(add_proc), list1, list2];
        let result = primitive_for_each(&args).unwrap();
        
        assert_eq!(result, Value::Unspecified);
    }
    
    #[test]
    fn test_map_for_each_errors() {
        // Test errors for both map and for-each
        
        // Non-procedure first argument
        let args = vec![Value::integer(42), Value::list(vec![Value::integer(1)])];
        assert!(primitive_map(&args).is_err());
        assert!(primitive_for_each(&args).is_err());
        
        // Non-list argument
        let proc = Arc::new(PrimitiveProcedure {
            name: "test".to_string(),
            arity_min: 1,
            arity_max: Some(1),
            implementation: PrimitiveImpl::RustFn(|args| Ok(args[0].clone())),
            effects: vec![Effect::Pure],
        });
        let args = vec![Value::Primitive(proc.clone()), Value::integer(42)];
        assert!(primitive_map(&args).is_err());
        assert!(primitive_for_each(&args).is_err());
        
        // Too few arguments
        assert!(primitive_map(&[]).is_err());
        assert!(primitive_for_each(&[]).is_err());
        
        let args = vec![Value::Primitive(proc)];
        assert!(primitive_map(&args).is_err());
        assert!(primitive_for_each(&args).is_err());
    }
    
    #[test]
    fn test_filter_basic() {
        // Test filter with a predicate that keeps even numbers
        let even_pred = Arc::new(PrimitiveProcedure {
            name: "even?".to_string(),
            arity_min: 1,
            arity_max: Some(1),
            implementation: PrimitiveImpl::RustFn(|args| {
                if let Some(n) = args[0].as_integer() {
                    Ok(Value::boolean(n % 2 == 0))
                } else {
                    Ok(Value::boolean(false))
                }
            }),
            effects: vec![Effect::Pure],
        });
        
        let list = Value::list(vec![
            Value::integer(1), Value::integer(2), Value::integer(3), 
            Value::integer(4), Value::integer(5), Value::integer(6)
        ]);
        let args = vec![Value::Primitive(even_pred), list];
        let result = primitive_filter(&args).unwrap();
        
        let expected = Value::list(vec![Value::integer(2), Value::integer(4), Value::integer(6)]);
        assert_eq!(result, expected);
    }
    
    #[test]
    fn test_filter_empty_result() {
        // Test filter with a predicate that keeps nothing
        let false_pred = Arc::new(PrimitiveProcedure {
            name: "false".to_string(),
            arity_min: 1,
            arity_max: Some(1),
            implementation: PrimitiveImpl::RustFn(|_args| Ok(Value::boolean(false))),
            effects: vec![Effect::Pure],
        });
        
        let list = Value::list(vec![Value::integer(1), Value::integer(2), Value::integer(3)]);
        let args = vec![Value::Primitive(false_pred), list];
        let result = primitive_filter(&args).unwrap();
        
        assert_eq!(result, Value::Nil);
    }
    
    #[test]
    fn test_filter_all_kept() {
        // Test filter with a predicate that keeps everything
        let true_pred = Arc::new(PrimitiveProcedure {
            name: "true".to_string(),
            arity_min: 1,
            arity_max: Some(1),
            implementation: PrimitiveImpl::RustFn(|_args| Ok(Value::boolean(true))),
            effects: vec![Effect::Pure],
        });
        
        let list = Value::list(vec![Value::integer(1), Value::integer(2), Value::integer(3)]);
        let args = vec![Value::Primitive(true_pred), list.clone()];
        let result = primitive_filter(&args).unwrap();
        
        assert_eq!(result, list);
    }
    
    #[test]
    fn test_fold_left_basic() {
        // Test fold-left with addition
        let add_proc = Arc::new(PrimitiveProcedure {
            name: "+".to_string(),
            arity_min: 0,
            arity_max: None,
            implementation: PrimitiveImpl::RustFn(|args| {
                let sum = args.iter()
                    .filter_map(|v| v.as_number())
                    .fold(0.0, |acc, n| acc + n);
                Ok(Value::number(sum))
            }),
            effects: vec![Effect::Pure],
        });
        
        let list = Value::list(vec![Value::number(1.0), Value::number(2.0), Value::number(3.0)]);
        let args = vec![Value::Primitive(add_proc), Value::number(0.0), list];
        let result = primitive_fold_left(&args).unwrap();
        
        assert_eq!(result, Value::number(6.0));
    }
    
    #[test]
    fn test_fold_left_with_strings() {
        // Test fold-left with string concatenation
        let concat_proc = Arc::new(PrimitiveProcedure {
            name: "string-append".to_string(),
            arity_min: 0,
            arity_max: None,
            implementation: PrimitiveImpl::RustFn(|args| {
                let mut result = String::new();
                for arg in args {
                    if let Some(s) = arg.as_string() {
                        result.push_str(s);
                    }
                }
                Ok(Value::string(result))
            }),
            effects: vec![Effect::Pure],
        });
        
        let list = Value::list(vec![Value::string("a"), Value::string("b"), Value::string("c")]);
        let args = vec![Value::Primitive(concat_proc), Value::string(""), list];
        let result = primitive_fold_left(&args).unwrap();
        
        assert_eq!(result, Value::string("abc"));
    }
    
    #[test]
    fn test_fold_right_basic() {
        // Test fold-right with subtraction to show order difference
        let sub_proc = Arc::new(PrimitiveProcedure {
            name: "-".to_string(),
            arity_min: 1,
            arity_max: None,
            implementation: PrimitiveImpl::RustFn(|args| {
                if args.is_empty() {
                    return Ok(Value::number(0.0));
                }
                
                let first = args[0].as_number().unwrap_or(0.0);
                if args.len() == 1 {
                    return Ok(Value::number(-first));
                }
                
                let result = args[1..].iter()
                    .filter_map(|v| v.as_number())
                    .fold(first, |acc, n| acc - n);
                Ok(Value::number(result))
            }),
            effects: vec![Effect::Pure],
        });
        
        let list = Value::list(vec![Value::number(1.0), Value::number(2.0), Value::number(3.0)]);
        let args = vec![Value::Primitive(sub_proc), Value::number(0.0), list];
        let result = primitive_fold_right(&args).unwrap();
        
        // fold-right with - should compute (1 - (2 - (3 - 0))) = 1 - (2 - 3) = 1 - (-1) = 2
        assert_eq!(result, Value::number(2.0));
    }
    
    #[test]
    fn test_fold_empty_list() {
        let add_proc = Arc::new(PrimitiveProcedure {
            name: "+".to_string(),
            arity_min: 0,
            arity_max: None,
            implementation: PrimitiveImpl::RustFn(|args| {
                let sum = args.iter()
                    .filter_map(|v| v.as_number())
                    .fold(0.0, |acc, n| acc + n);
                Ok(Value::number(sum))
            }),
            effects: vec![Effect::Pure],
        });
        
        let empty_list = Value::Nil;
        let initial = Value::number(42.0);
        
        let args = vec![Value::Primitive(add_proc.clone()), initial.clone(), empty_list.clone()];
        let result_left = primitive_fold_left(&args).unwrap();
        assert_eq!(result_left, initial);
        
        let args = vec![Value::Primitive(add_proc), initial.clone(), empty_list];
        let result_right = primitive_fold_right(&args).unwrap();
        assert_eq!(result_right, initial);
    }
    
    #[test]
    fn test_higher_order_errors() {
        // Test errors for filter and folds
        
        // Non-procedure first argument
        let args = vec![Value::integer(42), Value::list(vec![Value::integer(1)])];
        assert!(primitive_filter(&args).is_err());
        
        let args = vec![Value::integer(42), Value::integer(0), Value::list(vec![Value::integer(1)])];
        assert!(primitive_fold_left(&args).is_err());
        assert!(primitive_fold_right(&args).is_err());
        
        // Non-list argument
        let proc = Arc::new(PrimitiveProcedure {
            name: "test".to_string(),
            arity_min: 1,
            arity_max: Some(1),
            implementation: PrimitiveImpl::RustFn(|args| Ok(args[0].clone())),
            effects: vec![Effect::Pure],
        });
        
        let args = vec![Value::Primitive(proc.clone()), Value::integer(42)];
        assert!(primitive_filter(&args).is_err());
        
        let args = vec![Value::Primitive(proc.clone()), Value::integer(0), Value::integer(42)];
        assert!(primitive_fold_left(&args).is_err());
        assert!(primitive_fold_right(&args).is_err());
        
        // Too few arguments
        assert!(primitive_filter(&[]).is_err());
        assert!(primitive_fold_left(&[]).is_err());
        assert!(primitive_fold_right(&[]).is_err());
        
        let args = vec![Value::Primitive(proc.clone())];
        assert!(primitive_filter(&args).is_err());
        
        let args = vec![Value::Primitive(proc.clone()), Value::integer(0)];
        assert!(primitive_fold_left(&args).is_err());
        assert!(primitive_fold_right(&args).is_err());
    }
    
    // ============= SRFI-1 SPECIFIC TESTS =============
    
    #[test]
    fn test_srfi1_take_drop() {
        let list = Value::list(vec![Value::integer(1), Value::integer(2), Value::integer(3), Value::integer(4), Value::integer(5)]);
        
        // Test take
        let args = vec![list.clone(), Value::integer(3)];
        let result = srfi1_take(&args).unwrap();
        let expected = Value::list(vec![Value::integer(1), Value::integer(2), Value::integer(3)]);
        assert_eq!(result, expected);
        
        // Test drop
        let args = vec![list.clone(), Value::integer(2)];
        let result = srfi1_drop(&args).unwrap();
        let expected = Value::list(vec![Value::integer(3), Value::integer(4), Value::integer(5)]);
        assert_eq!(result, expected);
        
        // Test take-right
        let args = vec![list.clone(), Value::integer(2)];
        let result = srfi1_take_right(&args).unwrap();
        let expected = Value::list(vec![Value::integer(4), Value::integer(5)]);
        assert_eq!(result, expected);
        
        // Test drop-right
        let args = vec![list, Value::integer(2)];
        let result = srfi1_drop_right(&args).unwrap();
        let expected = Value::list(vec![Value::integer(1), Value::integer(2), Value::integer(3)]);
        assert_eq!(result, expected);
    }
    
    #[test]
    fn test_srfi1_split_at() {
        let list = Value::list(vec![Value::integer(1), Value::integer(2), Value::integer(3), Value::integer(4)]);
        let args = vec![list, Value::integer(2)];
        let result = srfi1_split_at(&args).unwrap();
        
        match result {
            Value::Pair(prefix, suffix) => {
                let expected_prefix = Value::list(vec![Value::integer(1), Value::integer(2)]);
                let expected_suffix = Value::list(vec![Value::integer(3), Value::integer(4)]);
                assert_eq!(prefix.as_ref().clone(), expected_prefix);
                assert_eq!(suffix.as_ref().clone(), expected_suffix);
            },
            _ => panic!("split-at should return a pair"),
        }
    }
    
    #[test]
    fn test_srfi1_last_last_pair() {
        let list = Value::list(vec![Value::integer(1), Value::integer(2), Value::integer(3)]);
        
        // Test last
        let result = srfi1_last(&[list.clone()]).unwrap();
        assert_eq!(result, Value::integer(3));
        
        // Test last-pair
        let result = srfi1_last_pair(&[list]).unwrap();
        // Should return the pair (3 . ())
        match result {
            Value::Pair(car, cdr) => {
                assert_eq!(car.as_ref().clone(), Value::integer(3));
                assert_eq!(cdr.as_ref().clone(), Value::Nil);
            },
            _ => panic!("last-pair should return a pair"),
        }
    }
    
    #[test]
    fn test_srfi1_fold_reduce() {
        let add_proc = Arc::new(PrimitiveProcedure {
            name: "+".to_string(),
            arity_min: 0,
            arity_max: None,
            implementation: PrimitiveImpl::RustFn(|args| {
                let sum = args.iter()
                    .filter_map(|v| v.as_number())
                    .fold(0.0, |acc, n| acc + n);
                Ok(Value::number(sum))
            }),
            effects: vec![Effect::Pure],
        });
        
        let list = Value::list(vec![Value::number(1.0), Value::number(2.0), Value::number(3.0)]);
        
        // Test fold (SRFI-1 version: kons knil clist)
        let args = vec![Value::Primitive(add_proc.clone()), Value::number(0.0), list.clone()];
        let result = srfi1_fold(&args).unwrap();
        assert_eq!(result, Value::number(6.0));
        
        // Test reduce  
        let args = vec![Value::Primitive(add_proc), Value::number(0.0), list];
        let result = srfi1_reduce(&args).unwrap();
        assert_eq!(result, Value::number(6.0));
    }
    
    #[test]
    fn test_srfi1_alist_operations() {
        // Create an association list: ((a . 1) (b . 2) (c . 3))
        let alist = Value::list(vec![
            Value::pair(Value::string("a"), Value::integer(1)),
            Value::pair(Value::string("b"), Value::integer(2)),
            Value::pair(Value::string("c"), Value::integer(3)),
        ]);
        
        // Test alist-cons
        let args = vec![Value::string("d"), Value::integer(4), alist.clone()];
        let result = srfi1_alist_cons(&args).unwrap();
        
        // Should add (d . 4) to the front
        match result {
            Value::Pair(car, cdr) => {
                match car.as_ref() {
                    Value::Pair(key, value) => {
                        assert_eq!(key.as_ref().clone(), Value::string("d"));
                        assert_eq!(value.as_ref().clone(), Value::integer(4));
                    },
                    _ => panic!("Expected pair in alist-cons result"),
                }
                assert_eq!(cdr.as_ref().clone(), alist);
            },
            _ => panic!("alist-cons should return a pair"),
        }
        
        // Test alist-copy
        let result = srfi1_alist_copy(&[alist.clone()]).unwrap();
        // Should be structurally equal but not the same object
        if let (Some(orig_list), Some(copied_list)) = (alist.as_list(), result.as_list()) {
            assert_eq!(orig_list.len(), copied_list.len());
            for (orig, copied) in orig_list.iter().zip(copied_list.iter()) {
                assert_eq!(orig, copied);
            }
        } else {
            panic!("Both should be proper lists");
        }
        
        // Test alist-delete
        let args = vec![Value::string("b"), alist];
        let result = srfi1_alist_delete(&args).unwrap();
        let expected = Value::list(vec![
            Value::pair(Value::string("a"), Value::integer(1)),
            Value::pair(Value::string("c"), Value::integer(3)),
        ]);
        assert_eq!(result, expected);
    }
}

// ============= EVALUATOR-INTEGRATED HIGHER-ORDER FUNCTIONS =============

/// Apply any procedure (primitive or user-defined) with evaluator integration
fn apply_procedure_with_evaluator(
    evaluator: &mut crate::eval::evaluator::Evaluator,
    procedure: &Value,
    args: &[Value],
) -> crate::diagnostics::Result<Value> {
    use crate::eval::evaluator::EvalStep;
    use crate::diagnostics::Error;
    
    // Start with the initial procedure application
    let mut step = evaluator.apply_procedure(procedure.clone(), args.to_vec(), None);
    
    // Run the trampoline loop to handle all evaluation steps
    loop {
        step = match step {
            EvalStep::Return(value) => return Ok(value),
            EvalStep::Error(error) => return Err(Box::new(error)),
            EvalStep::Continue { expr, env } => {
                // Continue evaluation with the given expression and environment
                evaluator.eval_step(&expr, env)
            }
            EvalStep::TailCall { procedure: proc, args: tail_args, location } => {
                // Handle tail call by applying the procedure
                evaluator.apply_procedure(proc, tail_args, location)
            }
            EvalStep::CallContinuation { continuation, value } => {
                // Handle continuation call
                evaluator.call_continuation(continuation, value)
            }
            EvalStep::NonLocalJump { value, target_stack_depth: _ } => {
                // Non-local jump immediately returns the value
                return Ok(value);
            }
        };
    }
}

/// Evaluator-integrated map function
fn evaluator_map(evaluator: &mut crate::eval::evaluator::Evaluator, args: &[Value]) -> crate::diagnostics::Result<Value> {
    use crate::diagnostics::Error as DiagnosticError;
    
    if args.len() < 2 {
        return Err(Box::new(DiagnosticError::runtime_error(
            "map requires at least 2 arguments".to_string(),
            None,
        )));
    }
    
    let procedure = &args[0];
    
    // Verify the first argument is callable
    if !procedure.is_procedure() {
        return Err(Box::new(DiagnosticError::runtime_error(
            "map first argument must be a procedure".to_string(),
            None,
        )));
    }
    
    // Convert all list arguments to vectors for parallel iteration
    let mut list_data = Vec::new();
    let mut min_length = usize::MAX;
    
    for (i, arg) in args.iter().enumerate().skip(1) {
        if let Some(list_values) = arg.as_list() {
            let length = list_values.len();
            if length < min_length {
                min_length = length;
            }
            list_data.push(list_values);
        } else {
            return Err(Box::new(DiagnosticError::runtime_error(
                format!("map argument {} must be a list", i + 1),
                None,
            )));
        }
    }
    
    // If any list is empty, return empty list
    if min_length == 0 || min_length == usize::MAX {
        return Ok(Value::Nil);
    }
    
    // Apply procedure to each element across all lists
    let mut results = Vec::new();
    for i in 0..min_length {
        let mut proc_args = Vec::new();
        for list in &list_data {
            proc_args.push(list[i].clone());
        }
        
        // Apply the procedure using evaluator integration
        let result = apply_procedure_with_evaluator(evaluator, procedure, &proc_args)?;
        results.push(result);
    }
    
    Ok(Value::list(results))
}

/// Evaluator-integrated filter function
fn evaluator_filter(evaluator: &mut crate::eval::evaluator::Evaluator, args: &[Value]) -> crate::diagnostics::Result<Value> {
    use crate::diagnostics::Error as DiagnosticError;
    
    if args.len() != 2 {
        return Err(Box::new(DiagnosticError::runtime_error(
            format!("filter expects 2 arguments, got {}", args.len()),
            None,
        )));
    }
    
    let predicate = &args[0];
    let list_arg = &args[1];
    
    // Verify the first argument is callable
    if !predicate.is_procedure() {
        return Err(Box::new(DiagnosticError::runtime_error(
            "filter first argument must be a procedure".to_string(),
            None,
        )));
    }
    
    // Convert list argument to vector
    let list_values = list_arg.as_list().ok_or_else(|| {
        Box::new(DiagnosticError::runtime_error(
            "filter requires a proper list".to_string(),
            None,
        ))
    })?;
    
    // Apply predicate to each element
    let mut filtered = Vec::new();
    for element in list_values {
        let proc_args = vec![element.clone()];
        
        // Apply the predicate using evaluator integration
        let result = apply_procedure_with_evaluator(evaluator, predicate, &proc_args)?;
        
        // Check if result is truthy
        if result.is_truthy() {
            filtered.push(element);
        }
    }
    
    Ok(Value::list(filtered))
}

/// Evaluator-integrated fold-left function
fn evaluator_fold_left(evaluator: &mut crate::eval::evaluator::Evaluator, args: &[Value]) -> crate::diagnostics::Result<Value> {
    use crate::diagnostics::Error as DiagnosticError;
    
    if args.len() < 3 {
        return Err(Box::new(DiagnosticError::runtime_error(
            "fold-left requires at least 3 arguments".to_string(),
            None,
        )));
    }
    
    let procedure = &args[0];
    let mut accumulator = args[1].clone();
    
    // Verify the first argument is callable
    if !procedure.is_procedure() {
        return Err(Box::new(DiagnosticError::runtime_error(
            "fold-left first argument must be a procedure".to_string(),
            None,
        )));
    }
    
    // Convert all list arguments to vectors for parallel iteration
    let mut list_data = Vec::new();
    let mut min_length = usize::MAX;
    
    for (i, arg) in args.iter().enumerate().skip(2) {
        if let Some(list_values) = arg.as_list() {
            let length = list_values.len();
            if length < min_length {
                min_length = length;
            }
            list_data.push(list_values);
        } else {
            return Err(Box::new(DiagnosticError::runtime_error(
                format!("fold-left argument {} must be a proper list", i + 1),
                None,
            )));
        }
    }
    
    // If any list is empty, return accumulator immediately
    if min_length == 0 || min_length == usize::MAX {
        return Ok(accumulator);
    }
    
    // Apply procedure to accumulator and each position across all lists
    for i in 0..min_length {
        let mut proc_args = vec![accumulator];
        for list in &list_data {
            proc_args.push(list[i].clone());
        }
        
        // Apply the procedure using evaluator integration
        accumulator = apply_procedure_with_evaluator(evaluator, procedure, &proc_args)?;
    }
    
    Ok(accumulator)
}

/// Evaluator-integrated fold-right function
fn evaluator_fold_right(evaluator: &mut crate::eval::evaluator::Evaluator, args: &[Value]) -> crate::diagnostics::Result<Value> {
    use crate::diagnostics::Error as DiagnosticError;
    
    if args.len() < 3 {
        return Err(Box::new(DiagnosticError::runtime_error(
            "fold-right requires at least 3 arguments".to_string(),
            None,
        )));
    }
    
    let procedure = &args[0];
    let mut accumulator = args[1].clone();
    
    // Verify the first argument is callable
    if !procedure.is_procedure() {
        return Err(Box::new(DiagnosticError::runtime_error(
            "fold-right first argument must be a procedure".to_string(),
            None,
        )));
    }
    
    // Convert all list arguments to vectors for parallel iteration
    let mut list_data = Vec::new();
    let mut min_length = usize::MAX;
    
    for (i, arg) in args.iter().enumerate().skip(2) {
        if let Some(list_values) = arg.as_list() {
            let length = list_values.len();
            if length < min_length {
                min_length = length;
            }
            list_data.push(list_values);
        } else {
            return Err(Box::new(DiagnosticError::runtime_error(
                format!("fold-right argument {} must be a proper list", i + 1),
                None,
            )));
        }
    }
    
    // If any list is empty, return accumulator immediately
    if min_length == 0 || min_length == usize::MAX {
        return Ok(accumulator);
    }
    
    // Apply procedure from right to left (reverse order)
    for i in (0..min_length).rev() {
        let mut proc_args = Vec::new();
        for list in &list_data {
            proc_args.push(list[i].clone());
        }
        proc_args.push(accumulator);
        
        // Apply the procedure using evaluator integration
        accumulator = apply_procedure_with_evaluator(evaluator, procedure, &proc_args)?;
    }
    
    Ok(accumulator)
}

/// Evaluator-integrated for-each function
fn evaluator_for_each(evaluator: &mut crate::eval::evaluator::Evaluator, args: &[Value]) -> crate::diagnostics::Result<Value> {
    use crate::diagnostics::Error as DiagnosticError;
    
    if args.len() < 2 {
        return Err(Box::new(DiagnosticError::runtime_error(
            "for-each requires at least 2 arguments".to_string(),
            None,
        )));
    }
    
    let procedure = &args[0];
    
    // Verify the first argument is callable
    if !procedure.is_procedure() {
        return Err(Box::new(DiagnosticError::runtime_error(
            "for-each first argument must be a procedure".to_string(),
            None,
        )));
    }
    
    // Convert all list arguments to vectors for parallel iteration
    let mut list_data = Vec::new();
    let mut min_length = usize::MAX;
    
    for (i, arg) in args.iter().enumerate().skip(1) {
        if let Some(list_values) = arg.as_list() {
            let length = list_values.len();
            if length < min_length {
                min_length = length;
            }
            list_data.push(list_values);
        } else {
            return Err(Box::new(DiagnosticError::runtime_error(
                format!("for-each argument {} must be a list", i + 1),
                None,
            )));
        }
    }
    
    // If any list is empty, return unspecified immediately
    if min_length == 0 || min_length == usize::MAX {
        return Ok(Value::Unspecified);
    }
    
    // Apply procedure to each element across all lists (for side effects)
    for i in 0..min_length {
        let mut proc_args = Vec::new();
        for list in &list_data {
            proc_args.push(list[i].clone());
        }
        
        // Apply the procedure using evaluator integration (ignore result)
        let _result = apply_procedure_with_evaluator(evaluator, procedure, &proc_args)?;
    }
    
    // for-each returns unspecified
    Ok(Value::Unspecified)
}

#[cfg(test)]
mod mutable_pair_tests {
    use super::*;

    #[test]
    fn test_mutable_pair_creation() {
        let pair = Value::mutable_pair(Value::integer(1), Value::integer(2));
        
        // Test that mutable pairs are recognized as pairs
        assert!(pair.is_pair());
        assert_eq!(primitive_pair_p(&[pair]).unwrap(), Value::boolean(true));
    }

    #[test]
    fn test_mutable_pair_car_cdr() {
        let pair = Value::mutable_pair(Value::integer(42), Value::string("hello"));
        
        let car_result = primitive_car(&[pair.clone()]).unwrap();
        assert_eq!(car_result, Value::integer(42));
        
        let cdr_result = primitive_cdr(&[pair]).unwrap();
        assert_eq!(cdr_result, Value::string("hello"));
    }

    #[test]
    fn test_set_car() {
        let pair = Value::mutable_pair(Value::integer(1), Value::integer(2));
        
        // Set the car to a new value
        let result = primitive_set_car(&[pair.clone(), Value::string("new")]).unwrap();
        assert_eq!(result, Value::Unspecified);
        
        // Check that the car was changed
        let car_result = primitive_car(&[pair]).unwrap();
        assert_eq!(car_result, Value::string("new"));
    }

    #[test]
    fn test_set_cdr() {
        let pair = Value::mutable_pair(Value::integer(1), Value::integer(2));
        
        // Set the cdr to a new value
        let result = primitive_set_cdr(&[pair.clone(), Value::string("new")]).unwrap();
        assert_eq!(result, Value::Unspecified);
        
        // Check that the cdr was changed
        let cdr_result = primitive_cdr(&[pair]).unwrap();
        assert_eq!(cdr_result, Value::string("new"));
    }

    #[test]
    fn test_list_set() {
        // Create a mutable list: (a b c)
        let mut_list = Value::mutable_pair(
            Value::string("a"),
            Value::mutable_pair(
                Value::string("b"), 
                Value::mutable_pair(
                    Value::string("c"), 
                    Value::Nil
                )
            )
        );
        
        // Set element at index 1 to "modified"
        let result = primitive_list_set(&[mut_list.clone(), Value::integer(1), Value::string("modified")]).unwrap();
        assert_eq!(result, Value::Unspecified);
        
        // Check that the list was modified
        let elem1 = primitive_list_ref(&[mut_list, Value::integer(1)]).unwrap();
        assert_eq!(elem1, Value::string("modified"));
    }

    #[test]
    fn test_mutable_list_length() {
        // Create a mutable list
        let mut_list = Value::mutable_pair(
            Value::integer(1),
            Value::mutable_pair(
                Value::integer(2), 
                Value::mutable_pair(
                    Value::integer(3), 
                    Value::Nil
                )
            )
        );
        
        let length = primitive_length(&[mut_list]).unwrap();
        assert_eq!(length, Value::integer(3));
    }

    #[test]
    fn test_immutable_pair_mutation_errors() {
        let immutable_pair = Value::pair(Value::integer(1), Value::integer(2));
        
        // Try to mutate an immutable pair - should fail
        assert!(primitive_set_car(&[immutable_pair.clone(), Value::string("new")]).is_err());
        assert!(primitive_set_cdr(&[immutable_pair, Value::string("new")]).is_err());
    }

    #[test] 
    fn test_list_set_errors() {
        let mut_list = Value::mutable_pair(Value::integer(1), Value::Nil);
        
        // Test negative index
        assert!(primitive_list_set(&[mut_list.clone(), Value::integer(-1), Value::string("x")]).is_err());
        
        // Test out of bounds
        assert!(primitive_list_set(&[mut_list, Value::integer(5), Value::string("x")]).is_err());
        
        // Test non-integer index
        assert!(primitive_list_set(&[Value::Nil, Value::string("bad"), Value::string("x")]).is_err());
    }
}

#[cfg(test)]
mod evaluator_integration_tests {
    use super::*;
    use crate::eval::evaluator::Evaluator;
    use std::sync::Arc;

    #[test]
    fn test_evaluator_integration_compiles() {
        // Basic compilation test to verify our evaluator integration functions compile
        let _map_func = evaluator_map as fn(&mut Evaluator, &[Value]) -> crate::diagnostics::Result<Value>;
        let _filter_func = evaluator_filter as fn(&mut Evaluator, &[Value]) -> crate::diagnostics::Result<Value>;
        let _fold_left_func = evaluator_fold_left as fn(&mut Evaluator, &[Value]) -> crate::diagnostics::Result<Value>;
        let _fold_right_func = evaluator_fold_right as fn(&mut Evaluator, &[Value]) -> crate::diagnostics::Result<Value>;
        let _for_each_func = evaluator_for_each as fn(&mut Evaluator, &[Value]) -> crate::diagnostics::Result<Value>;
        
        // The test passes if compilation succeeds
        assert!(true);
    }
}