relateby-pattern 0.4.2

Core pattern data structures
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
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
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
//! Pattern type definition
//!
//! This module provides the core `Pattern<V>` type, a recursive, nested structure
//! (s-expression-like) that is generic over value type `V`.
//!
//! # Construction Functions
//!
//! - [`Pattern::point`] - Creates an atomic pattern from a value (special case, matches gram-hs API)
//! - [`Pattern::pattern`] - Creates a pattern with elements (primary constructor, matches gram-hs API)
//! - [`Pattern::from_list`] - Creates a pattern from a list of values
//!
//! # Accessor Methods
//!
//! - [`Pattern::value`] - Returns a reference to the pattern's value
//! - [`Pattern::elements`] - Returns a slice of the pattern's elements
//!
//! # Inspection Utilities
//!
//! - [`Pattern::length`] - Returns the number of direct elements
//! - [`Pattern::size`] - Returns the total number of nodes
//! - [`Pattern::depth`] - Returns the maximum nesting depth
//! - [`Pattern::is_atomic`] - Checks if a pattern is atomic
//! - [`Pattern::values`] - Extracts all values as a flat list (pre-order)
//!
//! # Query Functions
//!
//! - [`Pattern::any_value`] - Checks if at least one value satisfies a predicate (short-circuits)
//! - [`Pattern::all_values`] - Checks if all values satisfy a predicate (short-circuits)
//! - [`Pattern::filter`] - Extracts subpatterns that satisfy a pattern predicate
//! - [`Pattern::find_first`] - Finds the first subpattern that satisfies a pattern predicate (short-circuits)
//! - [`Pattern::matches`] - Checks if two patterns have identical structure
//! - [`Pattern::contains`] - Checks if a pattern contains another as a subpattern
//!
//! # Combination Operations
//!
//! - [`Pattern::combine`] - Combines two patterns associatively (value combination + element concatenation)

use std::cmp::Ordering;
use std::fmt;
use std::hash::{Hash, Hasher};

/// A recursive, nested structure (s-expression-like) that is generic over value type `V`.
///
/// The value provides "information about the elements" - they form an intimate pairing.
/// Elements are themselves patterns, creating the recursive structure.
///
/// Patterns are s-expression-like structures, not trees, though they may appear tree-like
/// and accept tree-like operations.
///
/// # Examples
///
/// ## Creating a simple pattern
///
/// ```rust
/// use pattern_core::Pattern;
///
/// let pattern = Pattern {
///     value: "hello".to_string(),
///     elements: vec![],
/// };
/// ```
///
/// ## Creating a nested pattern
///
/// ```rust
/// use pattern_core::Pattern;
///
/// let nested = Pattern {
///     value: "parent".to_string(),
///     elements: vec![
///         Pattern {
///             value: "child1".to_string(),
///             elements: vec![],
///         },
///         Pattern {
///             value: "child2".to_string(),
///             elements: vec![],
///         },
///     ],
/// };
/// ```
///
/// ## Using with Subject type
///
/// ```rust
/// use pattern_core::{Pattern, Subject, Symbol};
/// use std::collections::HashSet;
///
/// let subject = Subject {
///     identity: Symbol("n".to_string()),
///     labels: HashSet::new(),
///     properties: std::collections::HashMap::new(),
/// };
///
/// let pattern: Pattern<Subject> = Pattern {
///     value: subject,
///     elements: vec![],
/// };
/// ```
///
/// # Trait Implementations
///
/// - `Clone`: Patterns can be cloned when `V: Clone`
/// - `PartialEq`, `Eq`: Patterns can be compared for equality when `V: PartialEq` (or `Eq`)
/// - `PartialOrd`, `Ord`: Patterns can be ordered when `V: PartialOrd` (or `Ord`)
///   - Uses value-first lexicographic ordering: compares values, then elements
///   - Enables sorting, min/max operations, and use in ordered collections (BTreeSet, BTreeMap)
/// - `Hash`: Patterns can be hashed when `V: Hash` for use in HashMap/HashSet
///   - Enables pattern deduplication and caching
///   - Structure-preserving: different structures produce different hashes
///   - Note: `Pattern<Subject>` is NOT hashable (Subject contains f64)
/// - `Debug`: Structured representation for debugging (with truncation for deep nesting)
/// - `Display`: Human-readable representation
///
/// # Performance
///
/// Patterns support:
/// - At least 100 nesting levels without stack overflow
/// - At least 10,000 elements efficiently
/// - WASM compilation for web applications
#[derive(Clone, PartialEq, Eq)]
pub struct Pattern<V> {
    /// The value component, which provides information about the elements.
    ///
    /// The value and elements form an intimate pairing where the value provides
    /// "information about the elements".
    pub value: V,

    /// The nested collection of patterns that form the recursive structure.
    ///
    /// Elements are themselves `Pattern<V>`, creating the recursive nested structure.
    /// An empty vector represents an atomic pattern (a pattern with no nested elements).
    pub elements: Vec<Pattern<V>>,
}

/// Configurable validation rules for pattern structure.
///
/// Rules can specify limits on nesting depth, element counts, or other structural properties.
/// Rules are optional (None means no limit).
///
/// # Examples
///
/// ```
/// use pattern_core::ValidationRules;
///
/// // No constraints (all patterns valid)
/// let rules = ValidationRules::default();
///
/// // Maximum depth constraint
/// let rules = ValidationRules {
///     max_depth: Some(10),
///     ..Default::default()
/// };
/// ```
#[derive(Debug, Clone, Default)]
pub struct ValidationRules {
    /// Maximum nesting depth allowed (None = no limit)
    pub max_depth: Option<usize>,
    /// Maximum element count allowed (None = no limit)
    pub max_elements: Option<usize>,
    /// Required fields (reserved for future value-specific validation)
    pub required_fields: Vec<String>,
}

/// Error type for pattern validation failures.
///
/// Provides detailed information about what rule was violated and where
/// in the pattern structure the violation occurred.
///
/// # Examples
///
/// ```
/// use pattern_core::ValidationError;
///
/// let error = ValidationError {
///     message: "Pattern depth exceeds maximum".to_string(),
///     rule_violated: "max_depth".to_string(),
///     location: vec!["elements".to_string(), "0".to_string()],
/// };
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ValidationError {
    /// Human-readable error message
    pub message: String,
    /// Name of violated rule (e.g., "max_depth", "max_elements")
    pub rule_violated: String,
    /// Path to violating node in pattern structure
    pub location: Vec<String>,
}

/// Results from structure analysis utilities.
///
/// Provides detailed information about pattern structural characteristics
/// including depth distribution, element counts, nesting patterns, and summaries.
///
/// # Examples
///
/// ```
/// use pattern_core::{Pattern, StructureAnalysis};
///
/// let pattern = Pattern::pattern("root".to_string(), vec![/* ... */]);
/// let analysis = pattern.analyze_structure();
///
/// println!("Depth distribution: {:?}", analysis.depth_distribution);
/// println!("Summary: {}", analysis.summary);
/// ```
#[derive(Debug, Clone)]
pub struct StructureAnalysis {
    /// Count of nodes at each depth level (index = depth, value = count)
    pub depth_distribution: Vec<usize>,
    /// Element counts at each level (index = level, value = count)
    pub element_counts: Vec<usize>,
    /// Identified structural patterns (e.g., "linear", "tree", "balanced")
    pub nesting_patterns: Vec<String>,
    /// Human-readable summary of structure
    pub summary: String,
}

impl<V: fmt::Debug> Pattern<V> {
    fn fmt_debug_with_depth(
        &self,
        f: &mut fmt::Formatter<'_>,
        depth: usize,
        max_depth: usize,
    ) -> fmt::Result {
        if depth > max_depth {
            return write!(f, "...");
        }

        f.debug_struct("Pattern")
            .field("value", &self.value)
            .field(
                "elements",
                &DebugElements {
                    elements: &self.elements,
                    depth,
                    max_depth,
                },
            )
            .finish()
    }
}

impl<V: fmt::Debug> fmt::Debug for Pattern<V> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.fmt_debug_with_depth(f, 0, 10) // Max depth of 10 for truncation
    }
}

struct DebugElements<'a, V> {
    elements: &'a Vec<Pattern<V>>,
    depth: usize,
    max_depth: usize,
}

impl<'a, V: fmt::Debug> fmt::Debug for DebugElements<'a, V> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.depth > self.max_depth {
            return write!(f, "[...]");
        }

        let mut list = f.debug_list();
        for (i, elem) in self.elements.iter().enumerate() {
            if i >= 5 && self.elements.len() > 10 {
                // Truncate if more than 10 elements
                list.entry(&format_args!("... ({} more)", self.elements.len() - 5));
                break;
            }
            list.entry(&DebugPattern {
                pattern: elem,
                depth: self.depth + 1,
                max_depth: self.max_depth,
            });
        }
        list.finish()
    }
}

struct DebugPattern<'a, V> {
    pattern: &'a Pattern<V>,
    depth: usize,
    max_depth: usize,
}

impl<'a, V: fmt::Debug> fmt::Debug for DebugPattern<'a, V> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.pattern
            .fmt_debug_with_depth(f, self.depth, self.max_depth)
    }
}

impl<V: fmt::Display> Pattern<V> {
    fn fmt_display_with_depth(
        &self,
        f: &mut fmt::Formatter<'_>,
        depth: usize,
        max_depth: usize,
    ) -> fmt::Result {
        if depth > max_depth {
            return write!(f, "...");
        }

        write!(f, "(")?;
        write!(f, "{}", self.value)?;

        if !self.elements.is_empty() {
            write!(f, " ")?;
            for (i, elem) in self.elements.iter().enumerate() {
                if i > 0 {
                    write!(f, " ")?;
                }
                if i >= 5 && self.elements.len() > 10 {
                    write!(f, "... ({} more)", self.elements.len() - 5)?;
                    break;
                }
                elem.fmt_display_with_depth(f, depth + 1, max_depth)?;
            }
        }

        write!(f, ")")
    }
}

impl<V: fmt::Display> fmt::Display for Pattern<V> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.fmt_display_with_depth(f, 0, 10) // Max depth of 10 for truncation
    }
}

// Construction Functions

impl<V> Pattern<V> {
    /// Creates an atomic pattern (a pattern with no elements) from a value.
    ///
    /// This is the special case constructor for atomic patterns.
    /// Equivalent to gram-hs `point :: v -> Pattern v`.
    ///
    /// # Arguments
    ///
    /// * `value` - The value component of the pattern
    ///
    /// # Returns
    ///
    /// A new atomic `Pattern<V>` instance with the specified value and empty elements.
    ///
    /// # Examples
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// let atomic = Pattern::point("atom".to_string());
    /// assert_eq!(atomic.value, "atom");
    /// assert_eq!(atomic.elements.len(), 0);
    /// ```
    pub fn point(value: V) -> Self {
        Pattern {
            value,
            elements: vec![],
        }
    }

    /// Creates a pattern with a value and elements.
    ///
    /// This is the primary constructor for creating patterns. Takes a decoration value
    /// and a list of pattern elements. The elements form the pattern itself; the value
    /// provides decoration about that pattern.
    ///
    /// Equivalent to gram-hs `pattern :: v -> [Pattern v] -> Pattern v`.
    ///
    /// # Arguments
    ///
    /// * `value` - The value component of the pattern
    /// * `elements` - The nested collection of patterns
    ///
    /// # Returns
    ///
    /// A new `Pattern<V>` instance with the specified value and elements.
    ///
    /// # Examples
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// let pattern = Pattern::pattern("root".to_string(), vec![
    ///     Pattern::point("child".to_string()),
    /// ]);
    /// assert_eq!(pattern.value, "root");
    /// assert_eq!(pattern.elements.len(), 1);
    /// ```
    #[allow(clippy::self_named_constructors)]
    pub fn pattern(value: V, elements: Vec<Pattern<V>>) -> Self {
        Pattern { value, elements }
    }

    /// Creates a pattern from a list of values.
    ///
    /// Creates a pattern where the first argument is the decoration value,
    /// and the list of values are converted to atomic patterns and used as elements.
    /// Equivalent to gram-hs `fromList :: v -> [v] -> Pattern v`.
    ///
    /// # Arguments
    ///
    /// * `value` - The decoration value for the pattern
    /// * `values` - List of values to convert to atomic patterns as elements
    ///
    /// # Returns
    ///
    /// A new `Pattern<V>` instance with value as decoration and values converted to atomic patterns as elements.
    ///
    /// # Examples
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// let pattern = Pattern::from_list("root".to_string(), vec![
    ///     "a".to_string(),
    ///     "b".to_string(),
    ///     "c".to_string(),
    /// ]);
    /// assert_eq!(pattern.value, "root");
    /// assert_eq!(pattern.elements.len(), 3);
    /// ```
    pub fn from_list(value: V, values: Vec<V>) -> Self {
        Pattern {
            value,
            elements: values.into_iter().map(Pattern::point).collect(),
        }
    }

    /// Returns a reference to the pattern's value component.
    ///
    /// Equivalent to gram-hs `value :: Pattern v -> v` (record field accessor).
    ///
    /// # Returns
    ///
    /// An immutable reference to the pattern's value.
    ///
    /// # Examples
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// let pattern = Pattern::point("hello".to_string());
    /// let value = pattern.value(); // &String
    /// assert_eq!(value, "hello");
    /// ```
    pub fn value(&self) -> &V {
        &self.value
    }

    /// Returns a slice of the pattern's elements.
    ///
    /// Equivalent to gram-hs `elements :: Pattern v -> [Pattern v]` (record field accessor).
    ///
    /// # Returns
    ///
    /// An immutable slice of the pattern's nested elements.
    ///
    /// # Examples
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// let pattern = Pattern::pattern("parent".to_string(), vec![
    ///     Pattern::point("child1".to_string()),
    ///     Pattern::point("child2".to_string()),
    /// ]);
    /// let elements = pattern.elements();
    /// assert_eq!(elements.len(), 2);
    /// ```
    pub fn elements(&self) -> &[Pattern<V>] {
        &self.elements
    }

    /// Returns the number of direct elements in a pattern's sequence.
    ///
    /// Equivalent to gram-hs `length :: Pattern v -> Int`.
    ///
    /// # Returns
    ///
    /// The number of direct elements (not nested).
    ///
    /// # Examples
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// let pattern = Pattern::pattern("parent".to_string(), vec![
    ///     Pattern::point("child1".to_string()),
    ///     Pattern::point("child2".to_string()),
    /// ]);
    /// assert_eq!(pattern.length(), 2);
    /// ```
    pub fn length(&self) -> usize {
        self.elements.len()
    }

    /// Returns the total number of nodes in a pattern structure, including all nested patterns.
    ///
    /// Equivalent to gram-hs `size :: Pattern v -> Int`.
    ///
    /// # Returns
    ///
    /// The total number of nodes (root + all nested nodes).
    ///
    /// # Examples
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// let atomic = Pattern::point("atom".to_string());
    /// assert_eq!(atomic.size(), 1);
    ///
    /// let pattern = Pattern::pattern("root".to_string(), vec![
    ///     Pattern::point("child1".to_string()),
    ///     Pattern::point("child2".to_string()),
    /// ]);
    /// assert_eq!(pattern.size(), 3); // root + 2 children
    /// ```
    pub fn size(&self) -> usize {
        1 + self.elements.iter().map(|e| e.size()).sum::<usize>()
    }

    /// Returns the maximum nesting depth of a pattern structure.
    ///
    /// Equivalent to gram-hs `depth :: Pattern v -> Int`.
    ///
    /// # Returns
    ///
    /// The maximum nesting depth. Atomic patterns (patterns with no elements) have depth 0.
    ///
    /// # Examples
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// let atomic = Pattern::point("hello".to_string());
    /// assert_eq!(atomic.depth(), 0); // Atomic patterns have depth 0
    ///
    /// let nested = Pattern::pattern("parent".to_string(), vec![
    ///     Pattern::pattern("child".to_string(), vec![
    ///         Pattern::point("grandchild".to_string()),
    ///     ]),
    /// ]);
    /// assert_eq!(nested.depth(), 2);
    /// ```
    pub fn depth(&self) -> usize {
        if self.elements.is_empty() {
            0
        } else {
            1 + self.elements.iter().map(|e| e.depth()).max().unwrap_or(0)
        }
    }

    /// Checks if a pattern is atomic (has no elements).
    ///
    /// This is a convenience helper for pattern classification.
    ///
    /// # Returns
    ///
    /// `true` if the pattern has no elements, `false` otherwise.
    ///
    /// # Examples
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// let atomic = Pattern::point("hello".to_string());
    /// assert!(atomic.is_atomic());
    ///
    /// let nested = Pattern::pattern("parent".to_string(), vec![
    ///     Pattern::point("child".to_string()),
    /// ]);
    /// assert!(!nested.is_atomic());
    /// ```
    pub fn is_atomic(&self) -> bool {
        self.elements.is_empty()
    }

    /// Checks if at least one value in the pattern satisfies the given predicate.
    ///
    /// This operation traverses the pattern structure in pre-order (root first, then elements)
    /// and applies the predicate to each value. Returns `true` as soon as a value satisfies
    /// the predicate (short-circuit evaluation - both predicate evaluation AND traversal stop),
    /// or `false` if no values match.
    ///
    /// Equivalent to Haskell's `anyValue :: (v -> Bool) -> Pattern v -> Bool`.
    ///
    /// # Type Parameters
    ///
    /// * `F` - A function that takes a reference to a value and returns a boolean
    ///
    /// # Arguments
    ///
    /// * `predicate` - A function to test each value
    ///
    /// # Returns
    ///
    /// * `true` if at least one value satisfies the predicate
    /// * `false` if no values satisfy the predicate (including empty patterns)
    ///
    /// # Complexity
    ///
    /// * Time: O(n) worst case, O(1) to O(n) average (short-circuits on first match)
    /// * Space: O(1) heap, O(d) stack where d = maximum depth
    ///
    /// # Examples
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// let pattern = Pattern::pattern(5, vec![
    ///     Pattern::point(10),
    ///     Pattern::point(3),
    /// ]);
    ///
    /// // Check if any value is greater than 8
    /// assert!(pattern.any_value(|v| *v > 8));  // true (10 > 8)
    ///
    /// // Check if any value is negative
    /// assert!(!pattern.any_value(|v| *v < 0)); // false (all positive)
    /// ```
    ///
    /// # Short-Circuit Behavior
    ///
    /// The operation stops traversal as soon as a matching value is found:
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// let pattern = Pattern::pattern(1, vec![
    ///     Pattern::point(2),
    ///     Pattern::point(5), // Matches here - stops traversal
    ///     Pattern::point(3), // Not visited
    /// ]);
    ///
    /// assert!(pattern.any_value(|v| *v == 5));
    /// ```
    pub fn any_value<F>(&self, predicate: F) -> bool
    where
        F: Fn(&V) -> bool,
    {
        self.any_value_recursive(&predicate)
    }

    /// Helper function for any_value with early termination.
    fn any_value_recursive<F>(&self, predicate: &F) -> bool
    where
        F: Fn(&V) -> bool,
    {
        // Check current value (pre-order)
        if predicate(&self.value) {
            return true;
        }

        // Check elements recursively, stop on first match
        for element in &self.elements {
            if element.any_value_recursive(predicate) {
                return true;
            }
        }

        false
    }

    /// Checks if all values in the pattern satisfy the given predicate.
    ///
    /// This operation traverses the pattern structure in pre-order (root first, then elements)
    /// and applies the predicate to each value. Returns `false` as soon as a value is found
    /// that does not satisfy the predicate (short-circuit evaluation - both predicate evaluation
    /// AND traversal stop), or `true` if all values satisfy the predicate.
    ///
    /// Equivalent to Haskell's `allValues :: (v -> Bool) -> Pattern v -> Bool`.
    ///
    /// # Type Parameters
    ///
    /// * `F` - A function that takes a reference to a value and returns a boolean
    ///
    /// # Arguments
    ///
    /// * `predicate` - A function to test each value
    ///
    /// # Returns
    ///
    /// * `true` if all values satisfy the predicate (vacuous truth for patterns with no values)
    /// * `false` if at least one value does not satisfy the predicate
    ///
    /// # Complexity
    ///
    /// * Time: O(n) worst case, O(1) to O(n) average (short-circuits on first failure)
    /// * Space: O(1) heap, O(d) stack where d = maximum depth
    ///
    /// # Examples
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// let pattern = Pattern::pattern(5, vec![
    ///     Pattern::point(10),
    ///     Pattern::point(3),
    /// ]);
    ///
    /// // Check if all values are positive
    /// assert!(pattern.all_values(|v| *v > 0));  // true (all > 0)
    ///
    /// // Check if all values are greater than 8
    /// assert!(!pattern.all_values(|v| *v > 8)); // false (5 and 3 fail)
    /// ```
    ///
    /// # Short-Circuit Behavior
    ///
    /// The operation stops traversal as soon as a non-matching value is found:
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// let pattern = Pattern::pattern(1, vec![
    ///     Pattern::point(2),
    ///     Pattern::point(-5), // Fails here - stops traversal
    ///     Pattern::point(3),  // Not visited
    /// ]);
    ///
    /// assert!(!pattern.all_values(|v| *v > 0));
    /// ```
    ///
    /// # Relationship to any_value
    ///
    /// The following equivalence holds: `all_values(p) ≡ !any_value(!p)`
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// let pattern = Pattern::pattern(5, vec![Pattern::point(10)]);
    /// let predicate = |v: &i32| *v > 0;
    ///
    /// assert_eq!(
    ///     pattern.all_values(predicate),
    ///     !pattern.any_value(|v| !predicate(v))
    /// );
    /// ```
    pub fn all_values<F>(&self, predicate: F) -> bool
    where
        F: Fn(&V) -> bool,
    {
        self.all_values_recursive(&predicate)
    }

    /// Helper function for all_values with early termination.
    fn all_values_recursive<F>(&self, predicate: &F) -> bool
    where
        F: Fn(&V) -> bool,
    {
        // Check current value (pre-order)
        if !predicate(&self.value) {
            return false;
        }

        // Check elements recursively, stop on first failure
        for element in &self.elements {
            if !element.all_values_recursive(predicate) {
                return false;
            }
        }

        true
    }

    /// Filters subpatterns that satisfy the given pattern predicate.
    ///
    /// This operation traverses the pattern structure in pre-order (root first, then elements)
    /// and collects references to all patterns that satisfy the predicate. Unlike `any_value`
    /// and `all_values` which operate on values, this method operates on entire patterns,
    /// allowing predicates to test structural properties (length, depth, etc.) as well as values.
    ///
    /// Equivalent to Haskell's `filterPatterns :: (Pattern v -> Bool) -> Pattern v -> [Pattern v]`.
    ///
    /// # Type Parameters
    ///
    /// * `F` - A function that takes a reference to a pattern and returns a boolean
    ///
    /// # Arguments
    ///
    /// * `predicate` - A function to test each pattern (including the root)
    ///
    /// # Returns
    ///
    /// A vector of immutable references to patterns that satisfy the predicate, in pre-order
    /// traversal order. Returns an empty vector if no patterns match.
    ///
    /// # Complexity
    ///
    /// * Time: O(n) where n is the number of nodes (must visit all patterns)
    /// * Space: O(m) heap where m is the number of matches, O(d) stack where d = maximum depth
    ///
    /// # Examples
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// let pattern = Pattern::pattern(
    ///     "root",
    ///     vec![
    ///         Pattern::point("leaf1"),
    ///         Pattern::pattern("branch", vec![
    ///             Pattern::point("leaf2"),
    ///         ]),
    ///     ],
    /// );
    ///
    /// // Find all atomic (leaf) patterns
    /// let leaves = pattern.filter(|p| p.is_atomic());
    /// assert_eq!(leaves.len(), 2);  // leaf1, leaf2
    ///
    /// // Find all patterns with specific value
    /// let roots = pattern.filter(|p| p.value == "root");
    /// assert_eq!(roots.len(), 1);
    ///
    /// // Find patterns with elements (non-atomic)
    /// let branches = pattern.filter(|p| p.length() > 0);
    /// assert_eq!(branches.len(), 2);  // root, branch
    /// ```
    ///
    /// # Pre-Order Traversal
    ///
    /// Results are returned in pre-order traversal order (root first, then elements in order):
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// let pattern = Pattern::pattern(1, vec![
    ///     Pattern::point(2),
    ///     Pattern::pattern(3, vec![Pattern::point(4)]),
    ///     Pattern::point(5),
    /// ]);
    ///
    /// let all = pattern.filter(|_| true);
    /// assert_eq!(all.len(), 5);
    /// assert_eq!(all[0].value, 1); // root
    /// assert_eq!(all[1].value, 2); // first element
    /// assert_eq!(all[2].value, 3); // second element
    /// assert_eq!(all[3].value, 4); // nested in second element
    /// assert_eq!(all[4].value, 5); // third element
    /// ```
    ///
    /// # Combining with Other Operations
    ///
    /// Filter can be combined with value predicates:
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// let pattern = Pattern::pattern(5, vec![
    ///     Pattern::point(10),
    ///     Pattern::pattern(3, vec![]),
    /// ]);
    ///
    /// // Find patterns with large values
    /// let large = pattern.filter(|p| p.value > 8);
    /// assert_eq!(large.len(), 1); // Only point(10)
    ///
    /// // Find non-empty patterns with all values positive
    /// let branches = pattern.filter(|p| {
    ///     p.length() > 0 && p.all_values(|v| *v > 0)
    /// });
    /// ```
    ///
    /// # Lifetime and References
    ///
    /// The returned references borrow from the source pattern and have the same lifetime:
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// let pattern = Pattern::pattern("a", vec![Pattern::point("b")]);
    /// let matches = pattern.filter(|_| true);
    /// // matches[0] and matches[1] borrow from pattern
    /// // Cannot move or drop pattern while matches exist
    /// ```
    pub fn filter<F>(&self, predicate: F) -> Vec<&Pattern<V>>
    where
        F: Fn(&Pattern<V>) -> bool,
    {
        let mut result = Vec::new();
        self.filter_recursive(&predicate, &mut result);
        result
    }

    /// Helper function for recursive filter implementation.
    ///
    /// This performs a pre-order traversal, checking the current pattern first,
    /// then recursively filtering elements.
    fn filter_recursive<'a, F>(&'a self, predicate: &F, result: &mut Vec<&'a Pattern<V>>)
    where
        F: Fn(&Pattern<V>) -> bool,
    {
        // Check current pattern (pre-order: root first)
        if predicate(self) {
            result.push(self);
        }

        // Recursively filter elements
        for element in &self.elements {
            element.filter_recursive(predicate, result);
        }
    }

    /// Finds the first subpattern (including self) that satisfies a predicate.
    ///
    /// This method performs a depth-first pre-order traversal of the pattern structure
    /// (checking the root first, then elements recursively from left to right) and
    /// returns the first pattern that satisfies the predicate.
    ///
    /// # Arguments
    ///
    /// * `predicate` - A function that takes a pattern reference and returns `true`
    ///   if it matches the search criteria. The predicate can examine both the
    ///   pattern's value and its structure (element count, depth, etc.).
    ///
    /// # Returns
    ///
    /// * `Some(&Pattern<V>)` - A reference to the first matching pattern
    /// * `None` - If no pattern in the structure satisfies the predicate
    ///
    /// # Traversal Order
    ///
    /// The method uses depth-first pre-order traversal:
    /// 1. Check the root pattern first
    /// 2. Then check elements from left to right
    /// 3. For each element, recursively apply the same order
    ///
    /// This ensures consistent, predictable ordering and matches the behavior
    /// of other pattern traversal methods (`filter`, `fold`, `map`).
    ///
    /// # Short-Circuit Evaluation
    ///
    /// Unlike `filter`, which collects all matches, `find_first` stops immediately
    /// upon finding the first match. This makes it more efficient when you only
    /// need to know if a match exists or when you want the first occurrence.
    ///
    /// # Time Complexity
    ///
    /// * Best case: O(1) - if root matches
    /// * Average case: O(k) - where k is position of first match
    /// * Worst case: O(n) - if no match exists or match is last
    ///
    /// # Space Complexity
    ///
    /// O(d) where d is the maximum nesting depth (recursion stack)
    ///
    /// # Examples
    ///
    /// ## Finding by value
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// let pattern = Pattern::pattern("root", vec![
    ///     Pattern::point("child1"),
    ///     Pattern::point("target"),
    /// ]);
    ///
    /// let result = pattern.find_first(|p| p.value == "target");
    /// assert!(result.is_some());
    /// assert_eq!(result.unwrap().value, "target");
    /// ```
    ///
    /// ## Finding by structure
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// let pattern = Pattern::pattern("root", vec![
    ///     Pattern::pattern("branch", vec![
    ///         Pattern::point("leaf"),
    ///     ]),
    ///     Pattern::point("leaf2"),
    /// ]);
    ///
    /// // Find first atomic pattern (no elements)
    /// let leaf = pattern.find_first(|p| p.is_atomic());
    /// assert!(leaf.is_some());
    /// assert_eq!(leaf.unwrap().value, "leaf");  // First in pre-order
    /// ```
    ///
    /// ## No match returns None
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// let pattern = Pattern::point("single");
    /// let result = pattern.find_first(|p| p.value == "other");
    /// assert!(result.is_none());
    /// ```
    ///
    /// ## Combining value and structural predicates
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// let pattern = Pattern::pattern(5, vec![
    ///     Pattern::pattern(10, vec![
    ///         Pattern::point(3),
    ///         Pattern::point(7),
    ///     ]),
    ///     Pattern::point(15),
    /// ]);
    ///
    /// // Find first pattern with value > 8 AND has elements
    /// let result = pattern.find_first(|p| p.value > 8 && p.length() > 0);
    /// assert!(result.is_some());
    /// assert_eq!(result.unwrap().value, 10);
    /// ```
    ///
    /// ## Pre-order traversal demonstration
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// let pattern = Pattern::pattern(1, vec![
    ///     Pattern::pattern(2, vec![
    ///         Pattern::point(3),
    ///     ]),
    ///     Pattern::point(4),
    /// ]);
    ///
    /// // Traversal order: 1 (root), 2, 3, 4
    /// // First pattern with value > 1 is 2 (not 3)
    /// let result = pattern.find_first(|p| p.value > 1);
    /// assert_eq!(result.unwrap().value, 2);
    /// ```
    ///
    /// ## Integration with other methods
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// let pattern = Pattern::pattern(5, vec![
    ///     Pattern::pattern(10, vec![
    ///         Pattern::point(-3),
    ///         Pattern::point(7),
    ///     ]),
    ///     Pattern::pattern(2, vec![
    ///         Pattern::point(1),
    ///         Pattern::point(4),
    ///     ]),
    /// ]);
    ///
    /// // Find first pattern where all values are positive
    /// let result = pattern.find_first(|p| p.all_values(|v| *v > 0));
    /// assert!(result.is_some());
    /// assert_eq!(result.unwrap().value, 7);  // First point with all positive values
    /// ```
    ///
    /// # Panics
    ///
    /// This method does not panic. All inputs are valid:
    /// - Works with atomic patterns (no elements)
    /// - Works with patterns with empty elements
    /// - Works with deeply nested structures (limited only by stack size)
    /// - Handles all predicate results gracefully
    ///
    /// # Relationship to Other Methods
    ///
    /// * `filter` - Returns all matches, `find_first` returns only the first
    /// * `any_value` - Operates on values only, `find_first` operates on whole patterns
    /// * Consistency: `find_first(p).is_some()` implies `filter(p).len() > 0`
    /// * Consistency: If `find_first(p) == Some(x)`, then `filter(p)[0] == x`
    pub fn find_first<F>(&self, predicate: F) -> Option<&Pattern<V>>
    where
        F: Fn(&Pattern<V>) -> bool,
    {
        self.find_first_recursive(&predicate)
    }

    /// Helper function for recursive find_first implementation.
    ///
    /// This performs a pre-order traversal with early termination.
    /// Checks the current pattern first, then recursively searches elements.
    ///
    /// Returns `Some(&Pattern<V>)` on first match, `None` if no match found.
    fn find_first_recursive<'a, F>(&'a self, predicate: &F) -> Option<&'a Pattern<V>>
    where
        F: Fn(&Pattern<V>) -> bool,
    {
        // Check current pattern first (pre-order: root first)
        if predicate(self) {
            return Some(self);
        }

        // Recursively search elements (with early termination)
        for element in &self.elements {
            if let Some(found) = element.find_first_recursive(predicate) {
                return Some(found);
            }
        }

        // No match found
        None
    }

    /// Checks if two patterns have identical structure.
    ///
    /// This method performs structural equality checking, comparing both values and
    /// element arrangement recursively. Two patterns match if and only if:
    /// - Their values are equal (using `PartialEq`)
    /// - They have the same number of elements
    /// - All corresponding elements match recursively
    ///
    /// This is distinct from the `Eq` trait implementation and is intended for
    /// structural pattern matching operations. While currently equivalent to `==`
    /// for patterns where `V: Eq`, this method may diverge in the future to support
    /// wildcards, partial matching, or other pattern matching semantics.
    ///
    /// # Type Constraints
    ///
    /// Requires `V: PartialEq` so that values can be compared for equality.
    ///
    /// # Mathematical Properties
    ///
    /// * **Reflexive**: `p.matches(&p)` is always `true`
    /// * **Symmetric**: `p.matches(&q) == q.matches(&p)`
    /// * **Structural**: Distinguishes patterns with same values but different structures
    ///
    /// # Time Complexity
    ///
    /// * Best case: O(1) - if root values differ
    /// * Average case: O(min(n, m) / 2) - short-circuits on first mismatch
    /// * Worst case: O(min(n, m)) - if patterns are identical or differ only at end
    ///
    /// Where n and m are the number of nodes in each pattern.
    ///
    /// # Space Complexity
    ///
    /// O(min(d1, d2)) where d1 and d2 are the maximum nesting depths
    /// (recursion stack usage).
    ///
    /// # Examples
    ///
    /// ## Identical patterns match
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// let p1 = Pattern::pattern("root", vec![
    ///     Pattern::point("a"),
    ///     Pattern::point("b"),
    /// ]);
    /// let p2 = Pattern::pattern("root", vec![
    ///     Pattern::point("a"),
    ///     Pattern::point("b"),
    /// ]);
    ///
    /// assert!(p1.matches(&p2));
    /// ```
    ///
    /// ## Self-matching (reflexive)
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// let pattern = Pattern::point("a");
    /// assert!(pattern.matches(&pattern));
    /// ```
    ///
    /// ## Different values don't match
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// let p1 = Pattern::point("a");
    /// let p2 = Pattern::point("b");
    /// assert!(!p1.matches(&p2));
    /// ```
    ///
    /// ## Different structures don't match
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// let p1 = Pattern::pattern("a", vec![
    ///     Pattern::point("b"),
    ///     Pattern::point("c"),
    /// ]);
    /// let p2 = Pattern::pattern("a", vec![
    ///     Pattern::pattern("b", vec![
    ///         Pattern::point("c"),
    ///     ]),
    /// ]);
    ///
    /// // Same flattened values ["a", "b", "c"] but different structure
    /// assert!(!p1.matches(&p2));
    /// ```
    ///
    /// ## Symmetry property
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// let p1 = Pattern::point(42);
    /// let p2 = Pattern::point(99);
    ///
    /// // p1.matches(&p2) == p2.matches(&p1)
    /// assert_eq!(p1.matches(&p2), p2.matches(&p1));
    /// ```
    ///
    /// # Panics
    ///
    /// This method does not panic. All inputs are valid:
    /// - Works with atomic patterns
    /// - Works with patterns with empty elements
    /// - Works with deeply nested structures (limited only by stack size)
    ///
    /// # Relationship to Other Methods
    ///
    /// * **Eq trait**: Currently equivalent for `V: Eq`, may diverge in future
    /// * **contains**: `p.matches(&q)` implies `p.contains(&q)` (equality implies containment)
    pub fn matches(&self, other: &Pattern<V>) -> bool
    where
        V: PartialEq,
    {
        // Values must match
        if self.value != other.value {
            return false;
        }

        // Element counts must match
        if self.elements.len() != other.elements.len() {
            return false;
        }

        // All corresponding elements must match recursively
        self.elements
            .iter()
            .zip(other.elements.iter())
            .all(|(e1, e2)| e1.matches(e2))
    }

    /// Checks if this pattern contains another pattern as a subpattern.
    ///
    /// This method searches the entire pattern structure to determine if the given
    /// subpattern appears anywhere within it. A pattern contains a subpattern if:
    /// - The pattern matches the subpattern (using `matches`), OR
    /// - Any of its elements contains the subpattern (recursive search)
    ///
    /// This provides a structural containment check that goes beyond simple equality,
    /// allowing you to test whether a pattern appears as part of a larger structure.
    ///
    /// # Type Constraints
    ///
    /// Requires `V: PartialEq` because it uses `matches` internally for comparison.
    ///
    /// # Mathematical Properties
    ///
    /// * **Reflexive**: `p.contains(&p)` is always `true` (self-containment)
    /// * **Transitive**: If `a.contains(&b)` and `b.contains(&c)`, then `a.contains(&c)`
    /// * **Weaker than matches**: `p.matches(&q)` implies `p.contains(&q)`, but not vice versa
    /// * **Not symmetric**: `p.contains(&q)` does NOT imply `q.contains(&p)`
    ///
    /// # Time Complexity
    ///
    /// * Best case: O(1) - if root matches subpattern
    /// * Average case: O(n * m / 2) - where n = container size, m = subpattern size
    /// * Worst case: O(n * m) - if subpattern not found or found at end
    ///
    /// # Space Complexity
    ///
    /// O(d) where d is the maximum nesting depth (recursion stack usage).
    ///
    /// # Examples
    ///
    /// ## Self-containment
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// let pattern = Pattern::pattern("root", vec![
    ///     Pattern::point("child"),
    /// ]);
    ///
    /// // Every pattern contains itself
    /// assert!(pattern.contains(&pattern));
    /// ```
    ///
    /// ## Direct element containment
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// let pattern = Pattern::pattern("root", vec![
    ///     Pattern::point("a"),
    ///     Pattern::point("b"),
    /// ]);
    ///
    /// let subpattern = Pattern::point("a");
    /// assert!(pattern.contains(&subpattern));
    /// ```
    ///
    /// ## Nested descendant containment
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// let pattern = Pattern::pattern("root", vec![
    ///     Pattern::pattern("branch", vec![
    ///         Pattern::point("leaf"),
    ///     ]),
    /// ]);
    ///
    /// let subpattern = Pattern::point("leaf");
    /// assert!(pattern.contains(&subpattern));
    /// ```
    ///
    /// ## Non-existent subpattern
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// let pattern = Pattern::pattern("root", vec![
    ///     Pattern::point("a"),
    /// ]);
    ///
    /// let subpattern = Pattern::point("b");
    /// assert!(!pattern.contains(&subpattern));
    /// ```
    ///
    /// ## Transitivity
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// let a = Pattern::pattern("a", vec![
    ///     Pattern::pattern("b", vec![
    ///         Pattern::point("c"),
    ///     ]),
    /// ]);
    /// let b = Pattern::pattern("b", vec![
    ///     Pattern::point("c"),
    /// ]);
    /// let c = Pattern::point("c");
    ///
    /// // If a contains b and b contains c, then a contains c
    /// assert!(a.contains(&b));
    /// assert!(b.contains(&c));
    /// assert!(a.contains(&c));  // Transitive
    /// ```
    ///
    /// ## Contains is weaker than matches
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// let pattern = Pattern::pattern("root", vec![
    ///     Pattern::pattern("branch", vec![
    ///         Pattern::point("leaf"),
    ///     ]),
    /// ]);
    /// let subpattern = Pattern::point("leaf");
    ///
    /// // pattern contains subpattern, but they don't match
    /// assert!(pattern.contains(&subpattern));
    /// assert!(!pattern.matches(&subpattern));
    /// ```
    ///
    /// # Panics
    ///
    /// This method does not panic. All inputs are valid:
    /// - Works with atomic patterns
    /// - Works with patterns with empty elements
    /// - Works with deeply nested structures (limited only by stack size)
    /// - Handles multiple occurrences correctly
    ///
    /// # Relationship to Other Methods
    ///
    /// * **matches**: `p.matches(&q)` implies `p.contains(&q)`, but not vice versa
    /// * **Short-circuit**: Returns `true` as soon as a match is found
    pub fn contains(&self, subpattern: &Pattern<V>) -> bool
    where
        V: PartialEq,
    {
        // Check if this pattern matches the subpattern
        if self.matches(subpattern) {
            return true;
        }

        // Recursively check if any element contains the subpattern
        self.elements
            .iter()
            .any(|element| element.contains(subpattern))
    }

    /// Maps a function over all values in the pattern, preserving structure.
    ///
    /// This is equivalent to Haskell's `fmap` for the Functor typeclass,
    /// but follows Rust naming conventions. The transformation applies to
    /// all values recursively while preserving the pattern structure
    /// (number of elements, nesting depth, element order).
    ///
    /// # Functor Laws
    ///
    /// This implementation satisfies the functor laws:
    /// - **Identity**: `pattern.map(|x| x.clone()) == pattern`
    /// - **Composition**: `pattern.map(|x| g(&f(x))) == pattern.map(f).map(g)`
    ///
    /// # Type Parameters
    ///
    /// * `W` - The output value type (can be different from `V`)
    /// * `F` - The transformation function type
    ///
    /// # Arguments
    ///
    /// * `f` - Transformation function that takes a reference to a value (`&V`)
    ///   and returns a new value (`W`)
    ///
    /// # Returns
    ///
    /// A new `Pattern<W>` with the same structure but transformed values
    ///
    /// # Examples
    ///
    /// ## String transformation
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// let pattern = Pattern::point("hello");
    /// let upper = pattern.map(|s| s.to_uppercase());
    /// assert_eq!(upper.value, "HELLO");
    /// ```
    ///
    /// ## Type conversion
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// let numbers = Pattern::point(42);
    /// let strings = numbers.map(|n| n.to_string());
    /// assert_eq!(strings.value, "42");
    /// ```
    ///
    /// ## Nested patterns
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// let pattern = Pattern::pattern("root", vec![
    ///     Pattern::point("child1"),
    ///     Pattern::point("child2"),
    /// ]);
    /// let upper = pattern.map(|s| s.to_uppercase());
    /// assert_eq!(upper.value, "ROOT");
    /// assert_eq!(upper.elements[0].value, "CHILD1");
    /// assert_eq!(upper.elements[1].value, "CHILD2");
    /// ```
    ///
    /// ## Composition
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// let result = Pattern::point(5)
    ///     .map(|n| n * 2)
    ///     .map(|n| n + 1);
    /// assert_eq!(result.value, 11);
    /// ```
    ///
    /// # Performance
    ///
    /// - Time complexity: O(n) where n is the total number of nodes
    /// - Space complexity: O(n) for the new pattern + O(d) for recursion stack
    ///   where d is the maximum nesting depth
    /// - Handles patterns with 100+ nesting levels without stack overflow
    /// - Handles patterns with 10,000+ nodes efficiently
    pub fn map<W, F>(self, f: F) -> Pattern<W>
    where
        F: Fn(&V) -> W,
    {
        self.map_with(&f)
    }

    /// Internal helper for map that takes function by reference.
    /// This enables efficient recursion without cloning the closure.
    fn map_with<W, F>(self, f: &F) -> Pattern<W>
    where
        F: Fn(&V) -> W,
    {
        Pattern {
            value: f(&self.value),
            elements: self
                .elements
                .into_iter()
                .map(|elem| elem.map_with(f))
                .collect(),
        }
    }

    /// Folds the pattern into a single value by applying a function to each value with an accumulator.
    ///
    /// Processes values in depth-first, root-first order (pre-order traversal).
    /// The root value is processed first, then elements are processed left to right, recursively.
    /// Each value in the pattern is processed exactly once, and the accumulator is threaded through
    /// all processing steps.
    ///
    /// # Type Parameters
    ///
    /// * `B` - The accumulator type (can be different from `V`)
    /// * `F` - The folding function type
    ///
    /// # Arguments
    ///
    /// * `init` - Initial accumulator value
    /// * `f` - Folding function with signature `Fn(B, &V) -> B`
    ///   - First parameter: Accumulator (passed by value)
    ///   - Second parameter: Value reference (borrowed from pattern)
    ///   - Returns: New accumulator value
    ///
    /// # Returns
    ///
    /// The final accumulated value of type `B`
    ///
    /// # Examples
    ///
    /// ## Sum all integers
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// let pattern = Pattern::pattern(10, vec![
    ///     Pattern::point(20),
    ///     Pattern::point(30),
    /// ]);
    /// let sum = pattern.fold(0, |acc, v| acc + v);
    /// assert_eq!(sum, 60);  // 10 + 20 + 30
    /// ```
    ///
    /// ## Count values
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// let pattern = Pattern::pattern("root", vec![
    ///     Pattern::point("child1"),
    ///     Pattern::point("child2"),
    /// ]);
    /// let count = pattern.fold(0, |acc, _| acc + 1);
    /// assert_eq!(count, 3);  // root + 2 children
    /// assert_eq!(count, pattern.size());
    /// ```
    ///
    /// ## Concatenate strings
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// let pattern = Pattern::pattern("Hello", vec![
    ///     Pattern::point(" "),
    ///     Pattern::point("World"),
    /// ]);
    /// let result = pattern.fold(String::new(), |acc, s| acc + s);
    /// assert_eq!(result, "Hello World");
    /// ```
    ///
    /// ## Type transformation (string lengths to sum)
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// let pattern = Pattern::pattern("hello", vec![
    ///     Pattern::point("world"),
    ///     Pattern::point("!"),
    /// ]);
    /// let total_length: usize = pattern.fold(0, |acc, s| acc + s.len());
    /// assert_eq!(total_length, 11);  // 5 + 5 + 1
    /// ```
    ///
    /// ## Build a vector
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// let pattern = Pattern::pattern(1, vec![
    ///     Pattern::point(2),
    ///     Pattern::point(3),
    /// ]);
    /// let values: Vec<i32> = pattern.fold(Vec::new(), |mut acc, v| {
    ///     acc.push(*v);
    ///     acc
    /// });
    /// assert_eq!(values, vec![1, 2, 3]);
    /// ```
    ///
    /// ## Verify traversal order
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// let pattern = Pattern::pattern("A", vec![
    ///     Pattern::point("B"),
    ///     Pattern::pattern("C", vec![
    ///         Pattern::point("D"),
    ///     ]),
    /// ]);
    /// // Root first, then elements in order, depth-first
    /// let result = pattern.fold(String::new(), |acc, s| acc + s);
    /// assert_eq!(result, "ABCD");
    /// ```
    ///
    /// # Performance
    ///
    /// - Time complexity: O(n) where n is the total number of values
    /// - Space complexity: O(d) for recursion stack where d is the maximum nesting depth
    /// - Handles patterns with 100+ nesting levels without stack overflow
    /// - Handles patterns with 10,000+ nodes efficiently
    ///
    /// # Behavioral Guarantees
    ///
    /// 1. **Completeness**: Every value in the pattern is processed exactly once
    /// 2. **Order**: Values processed in depth-first, root-first order
    /// 3. **Non-destructive**: Pattern structure is not modified (borrows only)
    /// 4. **Reusability**: Pattern can be folded multiple times
    pub fn fold<B, F>(&self, init: B, f: F) -> B
    where
        F: Fn(B, &V) -> B,
    {
        self.fold_with(init, &f)
    }

    /// Internal helper for fold that takes function by reference.
    ///
    /// This enables efficient recursion without cloning the closure.
    /// Public `fold` passes closure by value for ergonomics,
    /// internal `fold_with` passes closure by reference for efficiency.
    fn fold_with<B, F>(&self, acc: B, f: &F) -> B
    where
        F: Fn(B, &V) -> B,
    {
        // Process root value first
        let acc = f(acc, &self.value);

        // Process elements recursively (left to right)
        self.elements
            .iter()
            .fold(acc, |acc, elem| elem.fold_with(acc, f))
    }

    /// Collects all values from the pattern into a vector in traversal order.
    ///
    /// Returns references to all values in the pattern, maintaining depth-first,
    /// root-first order (same as `fold`). The root value appears first in the vector,
    /// followed by element values in traversal order.
    ///
    /// This method uses `fold` internally and is a convenience for the common case
    /// of collecting all pattern values into a standard collection.
    ///
    /// # Returns
    ///
    /// A `Vec<&V>` containing references to all values in traversal order
    ///
    /// # Examples
    ///
    /// ## Get all values
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// let pattern = Pattern::pattern(1, vec![
    ///     Pattern::point(2),
    ///     Pattern::point(3),
    /// ]);
    /// let values: Vec<&i32> = pattern.values();
    /// assert_eq!(values, vec![&1, &2, &3]);
    /// assert_eq!(values.len(), pattern.size());
    /// ```
    ///
    /// ## Verify order
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// let pattern = Pattern::pattern(1, vec![
    ///     Pattern::point(2),
    ///     Pattern::pattern(3, vec![
    ///         Pattern::point(4),
    ///     ]),
    /// ]);
    /// let values = pattern.values();
    /// assert_eq!(values, vec![&1, &2, &3, &4]);
    /// ```
    ///
    /// ## Use with Iterator methods
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// let pattern = Pattern::pattern(1, vec![
    ///     Pattern::point(2),
    ///     Pattern::point(3),
    ///     Pattern::point(4),
    /// ]);
    /// let sum: i32 = pattern.values().iter().map(|&&v| v).sum();
    /// assert_eq!(sum, 10);
    ///
    /// let all_positive = pattern.values().iter().all(|&&v| v > 0);
    /// assert!(all_positive);
    /// ```
    ///
    /// ## Nested patterns
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// let pattern = Pattern::pattern(1, vec![
    ///     Pattern::pattern(2, vec![
    ///         Pattern::point(3),
    ///     ]),
    /// ]);
    /// let values: Vec<&i32> = pattern.values();
    /// assert_eq!(values, vec![&1, &2, &3]);
    /// ```
    ///
    /// # Performance
    ///
    /// - Time complexity: O(n) where n is the total number of values
    /// - Space complexity: O(n) for the result vector
    /// - Efficient single-pass collection using fold
    pub fn values(&self) -> Vec<&V> {
        // Collect all values into a vector using fold
        let mut result = Vec::with_capacity(self.size());
        self.collect_values(&mut result);
        result
    }

    /// Internal helper to recursively collect values into a vector.
    fn collect_values<'a>(&'a self, result: &mut Vec<&'a V>) {
        result.push(&self.value);
        for elem in &self.elements {
            elem.collect_values(result);
        }
    }

    /// Paramorphism: structure-aware folding over patterns.
    ///
    /// Folds the pattern into a single value using a structure-aware folding function.
    /// Unlike `fold` (which only provides values), paramorphism gives the folding function
    /// access to the full pattern structure at each position, enabling sophisticated
    /// aggregations that consider depth, element count, and nesting level.
    ///
    /// # Type Parameters
    ///
    /// * `R` - Result type produced by the folding function (can differ from `V`)
    /// * `F` - Folding function type `Fn(&Pattern<V>, &[R]) -> R`
    ///
    /// # Parameters
    ///
    /// * `f` - Folding function with signature `Fn(&Pattern<V>, &[R]) -> R`
    ///   - First parameter: Reference to the current pattern subtree
    ///   - Second parameter: Slice of results from the pattern's elements (left-to-right order)
    ///   - Returns: Result for this node (type `R`)
    ///
    /// # Returns
    ///
    /// The result produced by applying the folding function at the root after all elements
    /// have been processed recursively.
    ///
    /// # Semantics
    ///
    /// - **Evaluation order**: Bottom-up. For each node, para is first applied to all
    ///   elements (left to right); then the folding function is called with the current
    ///   pattern and the slice of those results.
    /// - **Atomic patterns**: If the pattern has no elements, the folding function receives
    ///   an empty slice `&[]` for the second argument.
    /// - **Element order**: The slice of results is in the same order as `self.elements()`.
    /// - **Non-destructive**: The pattern is not modified. The pattern can be reused after the call.
    /// - **Single traversal**: Each node is visited exactly once.
    ///
    /// # Complexity
    ///
    /// - **Time**: O(n) where n = total number of nodes in the pattern
    /// - **Space**: O(n) for collecting element results (plus O(d) stack where d = max depth)
    ///
    /// # Relationship to Other Operations
    ///
    /// | Operation | Access | Use when |
    /// |-----------|--------|----------|
    /// | `fold` | Values only | Reducing to a single value without structure (e.g. sum, count) |
    /// | `para` | Pattern + element results | Structure-aware aggregation (e.g. depth-weighted sum) |
    /// | `extend` | Pattern for transformation | Structure-aware transformation returning new Pattern |
    ///
    /// # Examples
    ///
    /// ## Sum all values (equivalent to fold)
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// let p = Pattern::pattern(10, vec![Pattern::point(5), Pattern::point(3)]);
    /// let sum: i32 = p.para(|pat, rs| *pat.value() + rs.iter().sum::<i32>());
    /// assert_eq!(sum, 18);  // 10 + 5 + 3
    /// ```
    ///
    /// ## Depth-weighted sum
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// let p = Pattern::pattern(10, vec![Pattern::point(5), Pattern::point(3)]);
    /// let depth_weighted: i32 = p.para(|pat, rs| {
    ///     *pat.value() * pat.depth() as i32 + rs.iter().sum::<i32>()
    /// });
    /// // Root: 10*1 + (0+0) = 10
    /// // Elements are atomic (depth 0): 5*0=0, 3*0=0
    /// assert_eq!(depth_weighted, 10);
    /// ```
    ///
    /// ## Atomic pattern receives empty slice
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// let atom = Pattern::point(42);
    /// let result = atom.para(|pat, rs| {
    ///     assert!(rs.is_empty());  // Atomic pattern has no elements
    ///     *pat.value()
    /// });
    /// assert_eq!(result, 42);
    /// ```
    ///
    /// ## Nesting statistics (sum, count, max_depth)
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// let p = Pattern::pattern(1, vec![
    ///     Pattern::pattern(2, vec![Pattern::point(3)]),
    /// ]);
    ///
    /// let (sum, count, max_depth): (i32, usize, usize) = p.para(|pat, rs| {
    ///     let (child_sum, child_count, child_depth) = rs.iter()
    ///         .fold((0_i32, 0_usize, 0_usize), |(s, c, d), (s2, c2, d2)| {
    ///             (s + s2, c + c2, d.max(*d2))
    ///         });
    ///     (*pat.value() + child_sum, 1 + child_count, pat.depth().max(child_depth))
    /// });
    ///
    /// assert_eq!(sum, 6);        // 1 + 2 + 3
    /// assert_eq!(count, 3);      // 3 nodes total
    /// assert_eq!(max_depth, 2);  // Maximum nesting depth (root -> pattern(2) -> point(3))
    /// ```
    ///
    /// # Reference
    ///
    /// Ported from gram-hs: `../pattern-hs/libs/pattern/src/Pattern/Core.hs` (lines 1188-1190)
    pub fn para<R, F>(&self, f: F) -> R
    where
        F: Fn(&Pattern<V>, &[R]) -> R,
    {
        self.para_with(&f)
    }

    /// Internal helper for paramorphism that takes the folding function by reference.
    ///
    /// This avoids moving the closure on each recursive call, which would require
    /// the closure to be `Clone`. By taking `&F` instead of `F`, we can recursively
    /// call `para_with` without ownership issues.
    fn para_with<R, F>(&self, f: &F) -> R
    where
        F: Fn(&Pattern<V>, &[R]) -> R,
    {
        // Recursively compute results for all elements (left to right)
        let child_results: Vec<R> = self
            .elements
            .iter()
            .map(|child| child.para_with(f))
            .collect();

        // Apply folding function to current pattern and element results
        f(self, &child_results)
    }

    /// Validates pattern structure against configurable rules and constraints.
    ///
    /// Returns `Ok(())` if the pattern is valid according to the rules,
    /// or `Err(ValidationError)` if validation fails.
    ///
    /// # Arguments
    ///
    /// * `rules` - Validation rules to apply
    ///
    /// # Returns
    ///
    /// * `Ok(())` if pattern is valid
    /// * `Err(ValidationError)` if validation fails, containing detailed error information
    ///
    /// # Examples
    ///
    /// ```
    /// use pattern_core::{Pattern, ValidationRules};
    ///
    /// let pattern = Pattern::pattern("root".to_string(), vec![/* ... */]);
    ///
    /// let rules = ValidationRules {
    ///     max_depth: Some(10),
    ///     ..Default::default()
    /// };
    ///
    /// match pattern.validate(&rules) {
    ///     Ok(()) => println!("Pattern is valid"),
    ///     Err(e) => println!("Validation failed: {} at {:?}", e.message, e.location),
    /// }
    /// ```
    ///
    /// # Performance
    ///
    /// This operation is O(n) where n is the number of nodes in the pattern.
    /// Must handle at least 100 nesting levels without stack overflow.
    pub fn validate(&self, rules: &ValidationRules) -> Result<(), ValidationError> {
        self.validate_recursive(rules, 0, &mut Vec::new())
    }

    /// Internal recursive validation helper
    fn validate_recursive(
        &self,
        rules: &ValidationRules,
        current_depth: usize,
        location: &mut Vec<String>,
    ) -> Result<(), ValidationError> {
        // Check max_depth constraint
        if let Some(max_depth) = rules.max_depth {
            if current_depth > max_depth {
                return Err(ValidationError {
                    message: format!(
                        "Pattern depth {} exceeds maximum allowed depth {}",
                        current_depth, max_depth
                    ),
                    rule_violated: "max_depth".to_string(),
                    location: location.clone(),
                });
            }
        }

        // Check max_elements constraint at current level
        if let Some(max_elements) = rules.max_elements {
            if self.elements.len() > max_elements {
                return Err(ValidationError {
                    message: format!(
                        "Pattern has {} elements, exceeding maximum allowed {}",
                        self.elements.len(),
                        max_elements
                    ),
                    rule_violated: "max_elements".to_string(),
                    location: location.clone(),
                });
            }
        }

        // Recursively validate all elements
        for (index, element) in self.elements.iter().enumerate() {
            location.push("elements".to_string());
            location.push(index.to_string());

            element.validate_recursive(rules, current_depth + 1, location)?;

            location.pop(); // Remove index
            location.pop(); // Remove "elements"
        }

        Ok(())
    }

    /// Analyzes pattern structure and returns detailed information about structural characteristics.
    ///
    /// Provides comprehensive structural analysis including depth distribution, element counts,
    /// nesting patterns, and a human-readable summary.
    ///
    /// # Returns
    ///
    /// `StructureAnalysis` containing:
    /// - Depth distribution: Count of nodes at each depth level
    /// - Element counts: Maximum element count at each level (for pattern identification)
    /// - Nesting patterns: Identified structural patterns
    /// - Summary: Human-readable text summary
    ///
    /// # Examples
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// let pattern = Pattern::pattern("root".to_string(), vec![/* ... */]);
    /// let analysis = pattern.analyze_structure();
    ///
    /// println!("Depth distribution: {:?}", analysis.depth_distribution);
    /// println!("Element counts: {:?}", analysis.element_counts);
    /// println!("Nesting patterns: {:?}", analysis.nesting_patterns);
    /// println!("Summary: {}", analysis.summary);
    /// ```
    ///
    /// # Performance
    ///
    /// This operation is O(n) where n is the number of nodes in the pattern.
    /// Must handle at least 100 nesting levels without stack overflow.
    /// Must handle at least 10,000 elements efficiently.
    pub fn analyze_structure(&self) -> StructureAnalysis {
        let mut depth_distribution = Vec::new();
        let mut element_counts = Vec::new();

        self.analyze_recursive(0, &mut depth_distribution, &mut element_counts);

        // Trim trailing zeros from element_counts (leaf levels with 0 elements)
        // According to spec: atomic pattern should have [], 2-level tree should have [count], not [count, 0]
        while let Some(&0) = element_counts.last() {
            element_counts.pop();
        }

        // Identify nesting patterns
        let nesting_patterns = self.identify_nesting_patterns(&depth_distribution, &element_counts);

        // Generate summary
        let summary =
            self.generate_summary(&depth_distribution, &element_counts, &nesting_patterns);

        StructureAnalysis {
            depth_distribution,
            element_counts,
            nesting_patterns,
            summary,
        }
    }

    /// Internal recursive analysis helper
    /// Tracks maximum element count at each level for pattern identification
    fn analyze_recursive(
        &self,
        current_depth: usize,
        depth_distribution: &mut Vec<usize>,
        element_counts: &mut Vec<usize>,
    ) {
        // Ensure vectors are large enough
        while depth_distribution.len() <= current_depth {
            depth_distribution.push(0);
        }
        while element_counts.len() <= current_depth {
            element_counts.push(0);
        }

        // Count this node at current depth
        depth_distribution[current_depth] += 1;

        // Track maximum element count at current level
        // Maximum is used for linear/tree pattern detection (all nodes <= 1 vs any node > 1)
        // For balanced patterns, we compare maximums across levels, which works correctly
        // with the fixed balanced pattern logic (ratio between 0.5 and 2.0)
        let current_count = self.elements.len();
        if current_count > element_counts[current_depth] {
            element_counts[current_depth] = current_count;
        }

        // Recursively analyze elements
        for element in &self.elements {
            element.analyze_recursive(current_depth + 1, depth_distribution, element_counts);
        }
    }

    /// Identify structural patterns from depth distribution and element counts
    fn identify_nesting_patterns(
        &self,
        depth_distribution: &[usize],
        element_counts: &[usize],
    ) -> Vec<String> {
        let mut patterns = Vec::new();

        if depth_distribution.len() <= 1 {
            patterns.push("atomic".to_string());
            return patterns;
        }

        // Check for linear pattern (one element per level)
        let is_linear = element_counts.iter().all(|&count| count <= 1);
        if is_linear {
            patterns.push("linear".to_string());
        }

        // Check for tree-like pattern (multiple elements, decreasing with depth)
        let has_branching = element_counts.iter().any(|&count| count > 1);
        if has_branching {
            patterns.push("tree".to_string());
        }

        // Check for balanced pattern (similar element counts across levels)
        // Balanced means counts are within 50% of each other (ratio between 0.5 and 2.0)
        // Note: element_counts already has trailing zeros trimmed, so all entries are non-zero
        if element_counts.len() >= 2 {
            let first_count = element_counts[0];
            if first_count > 0 {
                // Check all levels (trailing zeros already trimmed)
                let similar_counts = element_counts.iter().skip(1).all(|&count| {
                    let ratio = count as f64 / first_count as f64;
                    // Balanced if ratio is between 0.5 and 2.0 (within 50% of first_count)
                    (0.5..=2.0).contains(&ratio)
                });
                if similar_counts && first_count > 1 {
                    patterns.push("balanced".to_string());
                }
            }
        }

        if patterns.is_empty() {
            patterns.push("irregular".to_string());
        }

        patterns
    }

    /// Generate human-readable summary of structure
    fn generate_summary(
        &self,
        depth_distribution: &[usize],
        _element_counts: &[usize], // Reserved for future use in summary generation
        nesting_patterns: &[String],
    ) -> String {
        let total_nodes: usize = depth_distribution.iter().sum();
        let max_depth = depth_distribution.len().saturating_sub(1);
        let pattern_desc = if nesting_patterns.is_empty() {
            "unknown"
        } else {
            &nesting_patterns[0]
        };

        format!(
            "Pattern with {} level{}, {} node{}, {}-like structure",
            max_depth + 1,
            if max_depth == 0 { "" } else { "s" },
            total_nodes,
            if total_nodes == 1 { "" } else { "s" },
            pattern_desc
        )
    }

    // ====================================================================================
    // Traversable Operations
    // ====================================================================================

    /// Applies an effectful function returning `Option` to all values in the pattern.
    ///
    /// Traverses the pattern in depth-first, root-first order (pre-order traversal).
    /// If any transformation returns `None`, the entire operation returns `None`.
    /// If all transformations return `Some`, returns `Some(Pattern<W>)` with transformed values.
    ///
    /// This implements the Traversable pattern for Option, providing:
    /// - Structure preservation: Output pattern has same shape as input
    /// - Effect sequencing: Short-circuits on first None
    /// - All-or-nothing semantics: All values must be Some for success
    ///
    /// # Type Parameters
    ///
    /// * `W` - The type of transformed values
    /// * `F` - The transformation function type
    ///
    /// # Arguments
    ///
    /// * `f` - A function that transforms values of type `&V` to `Option<W>`
    ///
    /// # Returns
    ///
    /// * `Some(Pattern<W>)` if all transformations succeed
    /// * `None` if any transformation returns None (short-circuit)
    ///
    /// # Examples
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// // Successful traversal - all values parse
    /// let pattern = Pattern::pattern("1", vec![Pattern::point("2")]);
    /// let result = pattern.traverse_option(|s| s.parse::<i32>().ok());
    /// assert!(result.is_some());
    /// assert_eq!(result.unwrap().value, 1);
    ///
    /// // Failed traversal - one value doesn't parse
    /// let pattern = Pattern::pattern("1", vec![Pattern::point("invalid")]);
    /// let result = pattern.traverse_option(|s| s.parse::<i32>().ok());
    /// assert!(result.is_none());
    /// ```
    ///
    /// # Traversable Laws
    ///
    /// This implementation satisfies the traversable laws:
    /// - Identity: `pattern.traverse_option(|v| Some(*v)) == Some(pattern.clone())`
    /// - Structure preservation: If successful, output has same size, depth, and length
    ///
    /// # Performance
    ///
    /// - Time: O(n) where n is the number of nodes
    /// - Space: O(n) for the new pattern + O(d) stack for recursion depth d
    /// - Short-circuits on first None without processing remaining values
    pub fn traverse_option<W, F>(&self, f: F) -> Option<Pattern<W>>
    where
        F: Fn(&V) -> Option<W>,
    {
        self.traverse_option_with(&f)
    }

    /// Internal helper for `traverse_option` that takes function by reference.
    ///
    /// This enables efficient recursion without cloning the closure.
    /// Public `traverse_option` passes closure by value for ergonomics,
    /// internal `traverse_option_with` passes closure by reference for efficiency.
    fn traverse_option_with<W, F>(&self, f: &F) -> Option<Pattern<W>>
    where
        F: Fn(&V) -> Option<W>,
    {
        // Transform root value first (short-circuits on None via ?)
        let new_value = f(&self.value)?;

        // Transform elements recursively (left to right)
        // Iterator::collect() handles Option sequencing - stops on first None
        let new_elements: Option<Vec<Pattern<W>>> = self
            .elements
            .iter()
            .map(|elem| elem.traverse_option_with(f))
            .collect();

        // Construct new pattern with transformed value and elements
        Some(Pattern {
            value: new_value,
            elements: new_elements?,
        })
    }

    /// Applies an effectful function returning `Result` to all values in the pattern.
    ///
    /// Traverses the pattern in depth-first, root-first order (pre-order traversal).
    /// If any transformation returns `Err`, the entire operation returns `Err` (short-circuits).
    /// If all transformations return `Ok`, returns `Ok(Pattern<W>)` with transformed values.
    ///
    /// This implements the Traversable pattern for Result, providing:
    /// - Structure preservation: Output pattern has same shape as input
    /// - Effect sequencing: Short-circuits on first Err
    /// - All-or-nothing semantics: All values must be Ok for success
    /// - Error propagation: First error encountered is returned
    ///
    /// # Type Parameters
    ///
    /// * `W` - The type of transformed values
    /// * `E` - The error type
    /// * `F` - The transformation function type
    ///
    /// # Arguments
    ///
    /// * `f` - A function that transforms values of type `&V` to `Result<W, E>`
    ///
    /// # Returns
    ///
    /// * `Ok(Pattern<W>)` if all transformations succeed
    /// * `Err(E)` with the first error encountered (short-circuit)
    ///
    /// # Examples
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// // Successful traversal - all values parse
    /// let pattern = Pattern::pattern("1", vec![Pattern::point("2")]);
    /// let result: Result<Pattern<i32>, String> = pattern.traverse_result(|s| {
    ///     s.parse::<i32>().map_err(|e| format!("parse error: {}", e))
    /// });
    /// assert!(result.is_ok());
    /// assert_eq!(result.unwrap().value, 1);
    ///
    /// // Failed traversal - one value doesn't parse
    /// let pattern = Pattern::pattern("1", vec![Pattern::point("invalid")]);
    /// let result: Result<Pattern<i32>, String> = pattern.traverse_result(|s| {
    ///     s.parse::<i32>().map_err(|e| format!("parse error: {}", e))
    /// });
    /// assert!(result.is_err());
    /// ```
    ///
    /// # Traversable Laws
    ///
    /// This implementation satisfies the traversable laws:
    /// - Identity: `pattern.traverse_result(|v| Ok(*v)) == Ok(pattern.clone())`
    /// - Structure preservation: If successful, output has same size, depth, and length
    ///
    /// # Short-Circuiting
    ///
    /// The traversal stops immediately when the first error is encountered:
    /// - Root value is checked first
    /// - Elements are processed left-to-right
    /// - Nested patterns are traversed depth-first
    /// - No further values are processed after an error
    ///
    /// # Performance
    ///
    /// - Time: O(n) where n is the number of nodes (best case: O(1) if root errors)
    /// - Space: O(n) for the new pattern + O(d) stack for recursion depth d
    /// - Short-circuits on first Err without processing remaining values
    pub fn traverse_result<W, E, F>(&self, f: F) -> Result<Pattern<W>, E>
    where
        F: Fn(&V) -> Result<W, E>,
    {
        self.traverse_result_with(&f)
    }

    /// Internal helper for `traverse_result` that takes function by reference.
    ///
    /// This enables efficient recursion without cloning the closure.
    /// Public `traverse_result` passes closure by value for ergonomics,
    /// internal `traverse_result_with` passes closure by reference for efficiency.
    fn traverse_result_with<W, E, F>(&self, f: &F) -> Result<Pattern<W>, E>
    where
        F: Fn(&V) -> Result<W, E>,
    {
        // Transform root value first (short-circuits on Err via ?)
        let new_value = f(&self.value)?;

        // Transform elements recursively (left to right)
        // Iterator::collect() handles Result sequencing - stops on first Err
        let new_elements: Result<Vec<Pattern<W>>, E> = self
            .elements
            .iter()
            .map(|elem| elem.traverse_result_with(f))
            .collect();

        // Construct new pattern with transformed value and elements
        Ok(Pattern {
            value: new_value,
            elements: new_elements?,
        })
    }
}

impl<V: Clone> Pattern<Option<V>> {
    /// Flips the layers of structure from `Pattern<Option<V>>` to `Option<Pattern<V>>`.
    ///
    /// This is the `sequence` operation for Option, which "sequences" or "flips" the
    /// nested structure layers. If all values in the pattern are `Some`, returns
    /// `Some(Pattern<V>)` with the unwrapped values. If any value is `None`, returns `None`.
    ///
    /// This operation is equivalent to `traverse_option` with the identity function,
    /// and demonstrates the relationship: `sequence = traverse(id)`.
    ///
    /// # Type Parameters
    ///
    /// * `V` - The type inside the Option values (must implement Clone)
    ///
    /// # Returns
    ///
    /// * `Some(Pattern<V>)` if all values are Some (unwrapped)
    /// * `None` if any value in the pattern is None
    ///
    /// # Examples
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// // All Some values → Some(Pattern)
    /// let pattern = Pattern::pattern(Some(1), vec![Pattern::point(Some(2))]);
    /// let result = pattern.sequence_option();
    /// assert!(result.is_some());
    /// assert_eq!(result.unwrap().value, 1);
    ///
    /// // Any None → None
    /// let pattern = Pattern::pattern(Some(1), vec![Pattern::point(None)]);
    /// let result = pattern.sequence_option();
    /// assert!(result.is_none());
    /// ```
    ///
    /// # All-or-Nothing Semantics
    ///
    /// - If all values are `Some`, returns `Some` with unwrapped pattern
    /// - If any value is `None`, returns `None` (short-circuits)
    /// - Preserves pattern structure when successful
    ///
    /// # Use Cases
    ///
    /// - Converting `Pattern<Option<V>>` from multiple optional lookups into `Option<Pattern<V>>`
    /// - Validating that all values in a pattern are present
    /// - Implementing all-or-nothing processing for optional data
    ///
    /// # Performance
    ///
    /// - Time: O(n) where n is the number of nodes (best case: O(1) if root is None)
    /// - Space: O(n) for the new pattern + O(d) stack for recursion depth d
    /// - Short-circuits on first None without processing remaining values
    pub fn sequence_option(self) -> Option<Pattern<V>> {
        self.traverse_option(|opt| opt.as_ref().cloned())
    }
}

impl<V, E> Pattern<Result<V, E>> {
    /// Flips the layers of structure from `Pattern<Result<V, E>>` to `Result<Pattern<V>, E>`.
    ///
    /// This is the `sequence` operation for Result, which "sequences" or "flips" the
    /// nested structure layers. If all values in the pattern are `Ok`, returns
    /// `Ok(Pattern<V>)` with the unwrapped values. If any value is `Err`, returns that `Err`.
    ///
    /// This operation is equivalent to `traverse_result` with the identity function,
    /// and demonstrates the relationship: `sequence = traverse(id)`.
    ///
    /// # Type Parameters
    ///
    /// * `V` - The success type inside the Result values
    /// * `E` - The error type
    ///
    /// # Returns
    ///
    /// * `Ok(Pattern<V>)` if all values are Ok (unwrapped)
    /// * `Err(E)` with the first error encountered
    ///
    /// # Examples
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// // All Ok values → Ok(Pattern)
    /// let pattern: Pattern<Result<i32, String>> = Pattern::pattern(
    ///     Ok(1),
    ///     vec![Pattern::point(Ok(2))]
    /// );
    /// let result = pattern.sequence_result();
    /// assert!(result.is_ok());
    /// assert_eq!(result.unwrap().value, 1);
    ///
    /// // Any Err → Err
    /// let pattern: Pattern<Result<i32, String>> = Pattern::pattern(
    ///     Ok(1),
    ///     vec![Pattern::point(Err("error".to_string()))]
    /// );
    /// let result = pattern.sequence_result();
    /// assert!(result.is_err());
    /// ```
    ///
    /// # All-or-Nothing Semantics
    ///
    /// - If all values are `Ok`, returns `Ok` with unwrapped pattern
    /// - If any value is `Err`, returns first `Err` encountered (short-circuits)
    /// - Preserves pattern structure when successful
    ///
    /// # Use Cases
    ///
    /// - Converting `Pattern<Result<V, E>>` from multiple fallible operations into `Result<Pattern<V>, E>`
    /// - Validating that all operations in a pattern succeeded
    /// - Implementing all-or-nothing processing for fallible operations
    ///
    /// # Performance
    ///
    /// - Time: O(n) where n is the number of nodes (best case: O(1) if root is Err)
    /// - Space: O(n) for the new pattern + O(d) stack for recursion depth d
    /// - Short-circuits on first Err without processing remaining values
    pub fn sequence_result(self) -> Result<Pattern<V>, E>
    where
        V: Clone,
        E: Clone,
    {
        self.traverse_result(|res| res.clone())
    }
}

impl<V> Pattern<V> {
    /// Applies a validation function to all values and collects ALL errors.
    ///
    /// Unlike `traverse_result` which short-circuits on the first error, `validate_all`
    /// processes the entire pattern and collects all errors encountered. This is useful
    /// for comprehensive validation where you want to report all issues at once.
    ///
    /// Traverses in depth-first, root-first order (pre-order). If all validations succeed,
    /// returns `Ok(Pattern<W>)` with transformed values. If any validation fails, returns
    /// `Err(Vec<E>)` with ALL errors collected in traversal order.
    ///
    /// # Type Parameters
    ///
    /// * `W` - The type of transformed values
    /// * `E` - The error type
    /// * `F` - The validation function type
    ///
    /// # Arguments
    ///
    /// * `f` - A function that validates and transforms values of type `&V` to `Result<W, E>`
    ///
    /// # Returns
    ///
    /// * `Ok(Pattern<W>)` if all validations succeed
    /// * `Err(Vec<E>)` with ALL errors collected in traversal order
    ///
    /// # Examples
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// // All validations succeed
    /// let pattern = Pattern::pattern(1, vec![Pattern::point(2), Pattern::point(3)]);
    /// let result: Result<Pattern<i32>, Vec<String>> = pattern.validate_all(|v| {
    ///     if *v > 0 { Ok(*v * 10) } else { Err(format!("negative: {}", v)) }
    /// });
    /// assert!(result.is_ok());
    ///
    /// // Multiple validations fail - ALL errors collected
    /// let pattern = Pattern::pattern(-1, vec![Pattern::point(2), Pattern::point(-3)]);
    /// let result: Result<Pattern<i32>, Vec<String>> = pattern.validate_all(|v| {
    ///     if *v > 0 { Ok(*v * 10) } else { Err(format!("negative: {}", v)) }
    /// });
    /// assert!(result.is_err());
    /// let errors = result.unwrap_err();
    /// assert_eq!(errors.len(), 2); // Both -1 and -3 reported
    /// ```
    ///
    /// # Comparison with traverse_result
    ///
    /// **traverse_result**: Returns first error (short-circuits)
    /// - Use when: You want to fail fast and stop processing
    /// - Performance: O(1) to O(n) depending on error location
    /// - Behavior: Stops at first error
    ///
    /// **validate_all**: Returns ALL errors (no short-circuit)
    /// - Use when: You want comprehensive error reporting
    /// - Performance: Always O(n) - processes entire pattern
    /// - Behavior: Collects all errors, then returns
    ///
    /// # Error Ordering
    ///
    /// Errors are collected in traversal order (root first, then elements left to right).
    /// This provides predictable and consistent error reporting.
    ///
    /// # Performance
    ///
    /// - Time: Always O(n) where n is the number of nodes (no short-circuiting)
    /// - Space: O(n) for the new pattern + O(e) for error collection + O(d) stack depth
    /// - Processes every value regardless of errors
    pub fn validate_all<W, E, F>(&self, f: F) -> Result<Pattern<W>, Vec<E>>
    where
        F: Fn(&V) -> Result<W, E>,
    {
        self.validate_all_with(&f)
    }

    /// Internal helper for `validate_all` that takes function by reference.
    ///
    /// This enables efficient recursion without cloning the closure.
    /// Collects errors during traversal and returns them all at the end.
    ///
    /// Uses a single-pass approach:
    /// 1. Apply function to all values once, collecting both successes and errors
    /// 2. If no errors: Build the transformed pattern from collected successes
    /// 3. If errors: Return all collected errors
    fn validate_all_with<W, E, F>(&self, f: &F) -> Result<Pattern<W>, Vec<E>>
    where
        F: Fn(&V) -> Result<W, E>,
    {
        // Helper to recursively collect all results in pre-order (root first, then elements)
        fn collect_results<V, W, E, F>(
            pattern: &Pattern<V>,
            f: &F,
            successes: &mut Vec<W>,
            errors: &mut Vec<E>,
        ) where
            F: Fn(&V) -> Result<W, E>,
        {
            // Process root value first
            match f(&pattern.value) {
                Ok(w) => successes.push(w),
                Err(e) => errors.push(e),
            }

            // Process elements recursively (left to right)
            for elem in &pattern.elements {
                collect_results(elem, f, successes, errors);
            }
        }

        // Single pass: apply function to all values, collecting results
        let mut successes = Vec::new();
        let mut errors = Vec::new();
        collect_results(self, f, &mut successes, &mut errors);

        // If any errors occurred, return them all
        if !errors.is_empty() {
            return Err(errors);
        }

        // All validations succeeded - rebuild pattern from collected values
        // Values are in pre-order, so we consume them in the same order
        fn rebuild<V, W>(pattern: &Pattern<V>, values: &mut impl Iterator<Item = W>) -> Pattern<W> {
            // Get root value (next in pre-order sequence)
            let value = values
                .next()
                .expect("validate_all: insufficient transformed values");

            // Rebuild elements recursively
            let elements = pattern
                .elements
                .iter()
                .map(|elem| rebuild(elem, values))
                .collect();

            Pattern { value, elements }
        }

        Ok(rebuild(self, &mut successes.into_iter()))
    }
}

// ============================================================================
// Ordering Trait Implementations
// ============================================================================

/// `PartialOrd` implementation for `Pattern`.
///
/// Provides lexicographic ordering for patterns based on their structure.
/// Patterns are compared by their value first, then by their elements recursively.
///
/// This implementation follows the same semantics as the Haskell reference implementation
/// in `gram-hs/libs/pattern/src/Pattern/Core.hs`.
///
/// # Ordering Rules
///
/// 1. **Value-first comparison**: Compare pattern values first using the value type's `PartialOrd` instance
/// 2. **Element comparison**: If values are equal, compare element vectors lexicographically
/// 3. **Lexicographic elements**: Elements are compared left-to-right, stopping at first difference
/// 4. **Length comparison**: If all compared elements are equal, shorter < longer
///
/// # Examples
///
/// ```
/// use pattern_core::Pattern;
///
/// // Comparing atomic patterns
/// let p1 = Pattern::point(1);
/// let p2 = Pattern::point(2);
/// assert!(p1 < p2);
///
/// // Comparing patterns with same value but different elements
/// let p3 = Pattern::pattern(5, vec![Pattern::point(1)]);
/// let p4 = Pattern::pattern(5, vec![Pattern::point(2)]);
/// assert!(p3 < p4); // Values equal, first element 1 < 2
///
/// // Value takes precedence over elements
/// let p5 = Pattern::pattern(3, vec![Pattern::point(100)]);
/// let p6 = Pattern::pattern(4, vec![Pattern::point(1)]);
/// assert!(p5 < p6); // 3 < 4, elements not compared
/// ```
///
/// # Comparison with Haskell
///
/// This implementation is behaviorally equivalent to the Haskell `Ord` instance:
///
/// ```haskell
/// instance Ord v => Ord (Pattern v) where
///   compare (Pattern v1 es1) (Pattern v2 es2) =
///     case compare v1 v2 of
///       EQ -> compare es1 es2
///       other -> other
/// ```
impl<V: PartialOrd> PartialOrd for Pattern<V> {
    /// Compares two patterns, returning `Some(ordering)` if comparable, `None` otherwise.
    ///
    /// Uses value-first lexicographic comparison:
    /// 1. Compare pattern values using `V::partial_cmp`
    /// 2. If equal (or both None), compare element vectors lexicographically
    /// 3. If values differ, return that ordering
    ///
    /// # Returns
    ///
    /// - `Some(Ordering::Less)` if `self < other`
    /// - `Some(Ordering::Equal)` if `self == other`
    /// - `Some(Ordering::Greater)` if `self > other`
    /// - `None` if values cannot be compared (e.g., NaN in floats)
    ///
    /// # Performance
    ///
    /// - **Best case**: O(1) - Values differ, immediate return
    /// - **Average case**: O(log n) - Finds difference early in elements
    /// - **Worst case**: O(n) - Must compare all nodes where n = total nodes
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        match self.value.partial_cmp(&other.value) {
            Some(Ordering::Equal) => self.elements.partial_cmp(&other.elements),
            other => other,
        }
    }
}

/// `Ord` implementation for `Pattern`.
///
/// Provides total ordering for patterns where the value type implements `Ord`.
/// This enables patterns to be used as keys in ordered data structures like
/// `BTreeMap`, `BTreeSet`, and `BinaryHeap`.
///
/// # Ordering Rules
///
/// Same as `PartialOrd`:
/// 1. Compare values first
/// 2. If equal, compare elements lexicographically
///
/// # Properties
///
/// This implementation satisfies all `Ord` trait requirements:
///
/// - **Reflexivity**: `x.cmp(&x) == Ordering::Equal` for all x
/// - **Antisymmetry**: if `x.cmp(&y) == Less` then `y.cmp(&x) == Greater`
/// - **Transitivity**: if `x < y` and `y < z` then `x < z`
/// - **Totality**: For all x, y, exactly one of `x < y`, `x == y`, `x > y` holds
/// - **Consistency with Eq**: `x == y` implies `x.cmp(&y) == Equal`
///
/// These properties are verified through property-based tests.
///
/// # Examples
///
/// ```
/// use pattern_core::Pattern;
/// use std::cmp::Ordering;
///
/// let p1 = Pattern::point(1);
/// let p2 = Pattern::point(2);
///
/// // Using cmp directly
/// assert_eq!(p1.cmp(&p2), Ordering::Less);
///
/// // Using comparison operators
/// assert!(p1 < p2);
/// assert!(p1 <= p2);
/// assert!(p2 > p1);
/// assert!(p2 >= p1);
///
/// // Sorting collections
/// let mut patterns = vec![p2.clone(), p1.clone()];
/// patterns.sort();
/// assert_eq!(patterns, vec![p1, p2]);
/// ```
///
/// # Usage in Data Structures
///
/// ```
/// use pattern_core::Pattern;
/// use std::collections::{BTreeMap, BTreeSet};
///
/// // As BTreeSet elements
/// let mut set = BTreeSet::new();
/// set.insert(Pattern::point(3));
/// set.insert(Pattern::point(1));
/// set.insert(Pattern::point(2));
/// // Iteration in sorted order: 1, 2, 3
///
/// // As BTreeMap keys
/// let mut map = BTreeMap::new();
/// map.insert(Pattern::point(1), "first");
/// map.insert(Pattern::point(2), "second");
/// ```
impl<V: Ord> Ord for Pattern<V> {
    /// Compares two patterns, returning their ordering.
    ///
    /// Uses value-first lexicographic comparison:
    /// 1. Compare pattern values using `V::cmp`
    /// 2. If equal, compare element vectors lexicographically
    /// 3. If values differ, return that ordering
    ///
    /// This method always returns a definitive ordering (never None).
    ///
    /// # Performance
    ///
    /// - **Best case**: O(1) - Values differ, immediate return
    /// - **Average case**: O(log n) - Finds difference early in elements
    /// - **Worst case**: O(n) - Must compare all nodes where n = total nodes
    ///
    /// # Short-Circuit Optimization
    ///
    /// Comparison stops as soon as a difference is found:
    /// - If values differ, elements are never compared
    /// - If elements differ, remaining elements are not compared
    ///
    /// This provides efficient comparison even for large patterns.
    fn cmp(&self, other: &Self) -> Ordering {
        match self.value.cmp(&other.value) {
            Ordering::Equal => self.elements.cmp(&other.elements),
            non_equal => non_equal,
        }
    }
}

// ============================================================================
// Pattern Combination
// ============================================================================

impl<V: crate::Combinable> Pattern<V> {
    /// Combines two patterns associatively.
    ///
    /// Creates a new pattern by:
    /// 1. Combining the values using `V::combine`
    /// 2. Concatenating the element vectors (left first, then right)
    ///
    /// The operation is associative: `(a.combine(b)).combine(c)` equals `a.combine(b.combine(c))`.
    ///
    /// # Parameters
    ///
    /// * `self` - The first pattern (consumed)
    /// * `other` - The second pattern to combine with (consumed)
    ///
    /// # Returns
    ///
    /// A new `Pattern<V>` with:
    /// * `value`: Result of `self.value.combine(other.value)`
    /// * `elements`: Concatenation of `self.elements` and `other.elements`
    ///
    /// # Examples
    ///
    /// ## Atomic Patterns
    ///
    /// ```rust
    /// use pattern_core::Pattern;
    ///
    /// let p1 = Pattern::point("hello".to_string());
    /// let p2 = Pattern::point(" world".to_string());
    /// let result = p1.combine(p2);
    ///
    /// assert_eq!(result.value(), "hello world");
    /// assert_eq!(result.length(), 0);  // No elements
    /// ```
    ///
    /// ## Patterns with Elements
    ///
    /// ```rust
    /// use pattern_core::Pattern;
    ///
    /// let p1 = Pattern::pattern("a".to_string(), vec![
    ///     Pattern::point("b".to_string()),
    ///     Pattern::point("c".to_string()),
    /// ]);
    ///
    /// let p2 = Pattern::pattern("d".to_string(), vec![
    ///     Pattern::point("e".to_string()),
    /// ]);
    ///
    /// let result = p1.combine(p2);
    ///
    /// assert_eq!(result.value(), "ad");
    /// assert_eq!(result.length(), 3);  // [b, c, e]
    /// ```
    ///
    /// ## Associativity
    ///
    /// ```rust
    /// use pattern_core::Pattern;
    ///
    /// let a = Pattern::point("a".to_string());
    /// let b = Pattern::point("b".to_string());
    /// let c = Pattern::point("c".to_string());
    ///
    /// let left = a.clone().combine(b.clone()).combine(c.clone());
    /// let right = a.combine(b.combine(c));
    ///
    /// assert_eq!(left, right);  // Associativity holds
    /// ```
    ///
    /// # Performance
    ///
    /// * **Time Complexity**: O(|elements1| + |elements2| + value_combine_cost)
    /// * **Space Complexity**: O(|elements1| + |elements2|)
    ///
    /// Element concatenation uses `Vec::extend` for efficiency.
    ///
    /// **Benchmark Results** (on typical hardware):
    /// * Atomic patterns: ~100 ns
    /// * 100 elements: ~11 µs
    /// * 1000 elements: ~119 µs
    /// * 100-pattern fold: ~17 µs
    ///
    /// All operations complete in microseconds, making combination suitable
    /// for performance-critical applications.
    pub fn combine(self, other: Self) -> Self {
        // Step 1: Combine values using V's Combinable implementation
        let combined_value = self.value.combine(other.value);

        // Step 2: Concatenate elements (left first, then right)
        let mut combined_elements = self.elements;
        combined_elements.extend(other.elements);

        // Step 3: Return new pattern
        Pattern {
            value: combined_value,
            elements: combined_elements,
        }
    }

    /// Creates patterns by combining three lists pointwise (zipWith3).
    ///
    /// Takes three lists of equal length and combines them element-wise to create
    /// new patterns. Each resulting pattern has:
    /// - **value**: From the `values` list
    /// - **elements**: A pair `[left, right]` from the corresponding positions
    ///
    /// This is useful for creating relationship patterns from separate lists of
    /// source nodes, target nodes, and relationship values.
    ///
    /// # Arguments
    ///
    /// * `left` - First list of patterns (e.g., source nodes)
    /// * `right` - Second list of patterns (e.g., target nodes)
    /// * `values` - List of values for the new patterns (e.g., relationship types)
    ///
    /// # Returns
    ///
    /// A vector of patterns where each pattern has value from `values` and
    /// elements `[left[i], right[i]]`.
    ///
    /// # Behavior
    ///
    /// - Stops at the length of the shortest input list
    /// - Consumes all three input vectors
    ///
    /// # Examples
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// // Create relationship patterns
    /// let sources = vec![
    ///     Pattern::point("Alice".to_string()),
    ///     Pattern::point("Bob".to_string()),
    /// ];
    /// let targets = vec![
    ///     Pattern::point("Company".to_string()),
    ///     Pattern::point("Project".to_string()),
    /// ];
    /// let rel_types = vec!["WORKS_FOR".to_string(), "MANAGES".to_string()];
    ///
    /// let relationships = Pattern::zip3(sources, targets, rel_types);
    ///
    /// assert_eq!(relationships.len(), 2);
    /// assert_eq!(relationships[0].value, "WORKS_FOR");
    /// assert_eq!(relationships[0].elements.len(), 2);
    /// ```
    pub fn zip3(left: Vec<Pattern<V>>, right: Vec<Pattern<V>>, values: Vec<V>) -> Vec<Pattern<V>> {
        left.into_iter()
            .zip(right)
            .zip(values)
            .map(|((l, r), v)| Pattern::pattern(v, vec![l, r]))
            .collect()
    }

    /// Creates patterns by applying a function to pairs from two lists (zipWith2).
    ///
    /// Takes two lists of patterns and applies a function to each pair to compute
    /// the value for the resulting pattern. Each resulting pattern has:
    /// - **value**: Computed by applying `value_fn` to the pair
    /// - **elements**: A pair `[left, right]` from the corresponding positions
    ///
    /// This is useful when relationship values are derived from the patterns being
    /// connected, rather than from a pre-computed list.
    ///
    /// # Arguments
    ///
    /// * `left` - First list of patterns (e.g., source nodes)
    /// * `right` - Second list of patterns (e.g., target nodes)
    /// * `value_fn` - Function that computes the value from each pair
    ///
    /// # Returns
    ///
    /// A vector of patterns where each pattern has value computed by `value_fn`
    /// and elements `[left[i], right[i]]`.
    ///
    /// # Behavior
    ///
    /// - Stops at the length of the shortest input list
    /// - Borrows patterns (uses references) to allow inspection without consuming
    ///
    /// # Examples
    ///
    /// ```
    /// use pattern_core::Pattern;
    ///
    /// let people = vec![
    ///     Pattern::point("Alice".to_string()),
    ///     Pattern::point("Bob".to_string()),
    /// ];
    /// let companies = vec![
    ///     Pattern::point("TechCorp".to_string()),
    ///     Pattern::point("StartupInc".to_string()),
    /// ];
    ///
    /// // Derive relationship type from patterns
    /// let relationships = Pattern::zip_with(people, companies, |person, company| {
    ///     format!("{}_WORKS_AT_{}", person.value, company.value)
    /// });
    ///
    /// assert_eq!(relationships[0].value, "Alice_WORKS_AT_TechCorp");
    /// ```
    pub fn zip_with<F>(
        left: Vec<Pattern<V>>,
        right: Vec<Pattern<V>>,
        value_fn: F,
    ) -> Vec<Pattern<V>>
    where
        F: Fn(&Pattern<V>, &Pattern<V>) -> V,
    {
        left.into_iter()
            .zip(right)
            .map(|(l, r)| {
                let value = value_fn(&l, &r);
                Pattern::pattern(value, vec![l, r])
            })
            .collect()
    }
}

// ============================================================================
// Default Trait Implementation - Identity Element for Monoid
// ============================================================================

/// Provides a default (identity) pattern for value types that implement `Default`.
///
/// The default pattern serves as the identity element for pattern combination,
/// completing the monoid algebraic structure (associative operation + identity).
/// The default pattern has the default value for type `V` and an empty elements list.
///
/// # Monoid Laws
///
/// When combined with the [`Combinable`] trait, patterns form a complete monoid
/// satisfying these identity laws:
///
/// - **Left Identity**: `Pattern::default().combine(p) == p` for all patterns `p`
/// - **Right Identity**: `p.combine(Pattern::default()) == p` for all patterns `p`
///
/// These laws ensure that the default pattern acts as a neutral element: combining
/// any pattern with the default pattern (on either side) yields the original pattern
/// unchanged.
///
/// # Implementation
///
/// The default pattern is created using [`Pattern::point`] with the default value
/// for type `V`. This results in:
/// ```text
/// Pattern {
///     value: V::default(),
///     elements: vec![]
/// }
/// ```
///
/// # Examples
///
/// ## Basic Usage
///
/// ```rust
/// use pattern_core::Pattern;
///
/// // Create default pattern for String
/// let empty: Pattern<String> = Pattern::default();
/// assert_eq!(empty.value(), "");
/// assert_eq!(empty.length(), 0);
///
/// // Create default pattern for Vec<i32>
/// let empty: Pattern<Vec<i32>> = Pattern::default();
/// let expected: Vec<i32> = vec![];
/// assert_eq!(empty.value(), &expected);
/// assert_eq!(empty.length(), 0);
///
/// // Create default pattern for unit type
/// let empty: Pattern<()> = Pattern::default();
/// assert_eq!(empty.value(), &());
/// assert_eq!(empty.length(), 0);
/// ```
///
/// ## Identity Laws
///
/// ```rust
/// use pattern_core::{Pattern, Combinable};
///
/// let p = Pattern::point("hello".to_string());
/// let empty = Pattern::<String>::default();
///
/// // Left identity: empty.combine(p) == p
/// assert_eq!(empty.clone().combine(p.clone()), p);
///
/// // Right identity: p.combine(empty) == p
/// assert_eq!(p.clone().combine(empty.clone()), p);
/// ```
///
/// ## Usage with Iterators
///
/// ```rust
/// use pattern_core::{Pattern, Combinable};
///
/// let patterns = vec![
///     Pattern::point("hello".to_string()),
///     Pattern::point(" ".to_string()),
///     Pattern::point("world".to_string()),
/// ];
///
/// // Fold with default as initial value
/// let result = patterns.into_iter()
///     .fold(Pattern::default(), |acc, p| acc.combine(p));
///
/// assert_eq!(result.value(), "hello world");
/// ```
///
/// ## Handling Empty Collections
///
/// ```rust
/// use pattern_core::{Pattern, Combinable};
///
/// let empty_vec: Vec<Pattern<String>> = vec![];
///
/// // Folding empty collection returns default
/// let result = empty_vec.into_iter()
///     .fold(Pattern::default(), |acc, p| acc.combine(p));
///
/// assert_eq!(result, Pattern::default());
/// ```
///
/// # See Also
///
/// - [`Pattern::point`] - Used internally to create the default pattern
/// - [`Pattern::combine`] - The associative combination operation
/// - [`Combinable`] - Trait for types supporting associative combination
///
/// [`Combinable`]: crate::Combinable
impl<V> Default for Pattern<V>
where
    V: Default,
{
    /// Creates a default pattern with the default value and empty elements.
    ///
    /// This is the identity element for pattern combination operations.
    ///
    /// # Returns
    ///
    /// A pattern with `V::default()` as the value and an empty elements vector.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use pattern_core::Pattern;
    ///
    /// let empty: Pattern<String> = Pattern::default();
    /// assert_eq!(empty.value(), "");
    /// assert_eq!(empty.length(), 0);
    /// assert!(empty.is_atomic());
    /// ```
    fn default() -> Self {
        Pattern::point(V::default())
    }
}

// ============================================================================
// Hash Trait Implementation
// ============================================================================

/// Provides hashing support for patterns where the value type implements `Hash`.
///
/// This enables patterns to be used as keys in `HashMap` and elements in `HashSet`,
/// enabling efficient pattern deduplication, caching, and set-based operations.
///
/// # Hash/Eq Consistency
///
/// This implementation guarantees that equal patterns produce equal hashes:
/// - If `p1 == p2`, then `hash(p1) == hash(p2)`
/// - This consistency is required for correct HashMap/HashSet behavior
///
/// # Structure-Preserving Hashing
///
/// The hash incorporates both the value and the element structure recursively:
/// - Different patterns with the same values produce different hashes
/// - The nesting structure and element order affect the hash
/// - Atomic patterns hash differently from compound patterns
///
/// # Implementation
///
/// The implementation hashes both components of a pattern:
/// 1. Hash the value using `V::hash`
/// 2. Hash the elements vector (which recursively hashes nested patterns)
///
/// This approach leverages `Vec<T>`'s built-in `Hash` implementation, which
/// automatically handles recursive hashing of nested patterns correctly.
///
/// # Type Constraints
///
/// Only patterns where `V: Hash` can be hashed. This means:
/// - ✅ `Pattern<String>` is hashable (String implements Hash)
/// - ✅ `Pattern<Symbol>` is hashable (Symbol implements Hash)
/// - ✅ `Pattern<i32>` is hashable (integers implement Hash)
/// - ❌ `Pattern<Subject>` is NOT hashable (Subject contains f64)
/// - ❌ `Pattern<f64>` is NOT hashable (floats don't implement Hash)
///
/// This is correct behavior - the type system prevents hashing types that
/// shouldn't be hashed due to problematic equality semantics (e.g., NaN != NaN for floats).
///
/// # Examples
///
/// ## Using Patterns in HashSet (Deduplication)
///
/// ```rust
/// use pattern_core::Pattern;
/// use std::collections::HashSet;
///
/// let p1 = Pattern::point("hello".to_string());
/// let p2 = Pattern::point("world".to_string());
/// let p3 = Pattern::point("hello".to_string());  // Duplicate of p1
///
/// let mut set = HashSet::new();
/// set.insert(p1);
/// set.insert(p2);
/// set.insert(p3);  // Automatically deduplicated
///
/// assert_eq!(set.len(), 2);  // Only unique patterns
/// ```
///
/// ## Using Patterns as HashMap Keys (Caching)
///
/// ```rust
/// use pattern_core::Pattern;
/// use std::collections::HashMap;
///
/// let mut cache: HashMap<Pattern<String>, i32> = HashMap::new();
///
/// let p1 = Pattern::point("key1".to_string());
/// let p2 = Pattern::point("key2".to_string());
///
/// cache.insert(p1.clone(), 42);
/// cache.insert(p2.clone(), 100);
///
/// assert_eq!(cache.get(&p1), Some(&42));
/// assert_eq!(cache.get(&p2), Some(&100));
/// ```
///
/// ## Hash Consistency with Equality
///
/// ```rust
/// use pattern_core::Pattern;
/// use std::collections::hash_map::DefaultHasher;
/// use std::hash::{Hash, Hasher};
///
/// fn hash_pattern<V: Hash>(p: &Pattern<V>) -> u64 {
///     let mut hasher = DefaultHasher::new();
///     p.hash(&mut hasher);
///     hasher.finish()
/// }
///
/// let p1 = Pattern::point("test".to_string());
/// let p2 = Pattern::point("test".to_string());
///
/// // Equal patterns have equal hashes
/// assert_eq!(p1, p2);
/// assert_eq!(hash_pattern(&p1), hash_pattern(&p2));
/// ```
///
/// ## Structure Distinguishes Hashes
///
/// ```rust
/// use pattern_core::Pattern;
/// use std::collections::hash_map::DefaultHasher;
/// use std::hash::{Hash, Hasher};
///
/// fn hash_pattern<V: Hash>(p: &Pattern<V>) -> u64 {
///     let mut hasher = DefaultHasher::new();
///     p.hash(&mut hasher);
///     hasher.finish()
/// }
///
/// // Same values, different structures
/// let atomic = Pattern::point("value".to_string());
/// let compound = Pattern::pattern(
///     "value".to_string(),
///     vec![Pattern::point("child".to_string())]
/// );
///
/// // Different structures produce different hashes
/// assert_ne!(atomic, compound);
/// // Note: Hash inequality is not guaranteed but expected
/// // (hash collisions are possible but rare)
/// ```
///
/// # Performance
///
/// - **Time Complexity**: O(n) where n is the total number of nodes in the pattern
/// - **Space Complexity**: O(1) (hash computation uses constant space)
/// - Hashing is typically very fast (microseconds even for large patterns)
/// - Results are cached in HashMap/HashSet (computed once per pattern)
///
/// # Comparison with Haskell
///
/// This implementation is behaviorally equivalent to the Haskell `Hashable` instance:
///
/// ```haskell
/// instance Hashable v => Hashable (Pattern v) where
///   hashWithSalt salt (Pattern v es) =
///     salt `hashWithSalt` v `hashWithSalt` es
/// ```
///
/// Both implementations hash the value and elements in the same order, ensuring
/// equivalent hash values for equivalent patterns.
///
/// # See Also
///
/// - `HashMap` - For using patterns as keys in hash-based maps
/// - `HashSet` - For pattern deduplication and set operations
/// - [`Pattern::combine`] - Pattern combination (works well with cached patterns)
/// - [`Eq`] - Equality trait that Hash must be consistent with
impl<V: Hash> Hash for Pattern<V> {
    /// Hashes this pattern into the provided hasher.
    ///
    /// Computes the hash by:
    /// 1. Hashing the value component
    /// 2. Hashing the elements vector (recursively hashes nested patterns)
    ///
    /// This ensures that equal patterns produce equal hashes while different
    /// structures produce different hashes.
    ///
    /// # Parameters
    ///
    /// * `state` - The hasher to write the hash into
    ///
    /// # Examples
    ///
    /// ```rust
    /// use pattern_core::Pattern;
    /// use std::collections::hash_map::DefaultHasher;
    /// use std::hash::{Hash, Hasher};
    ///
    /// let pattern = Pattern::point("test".to_string());
    ///
    /// let mut hasher = DefaultHasher::new();
    /// pattern.hash(&mut hasher);
    /// let hash_value = hasher.finish();
    /// ```
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.value.hash(state);
        self.elements.hash(state);
    }
}

// ============================================================================
// Paramorphism Tests
// ============================================================================

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

    // ========================================================================
    // Phase 3: User Story 1 – Pattern-of-Elements Analysis
    // ========================================================================

    /// T007: Atomic pattern receives empty slice
    #[test]
    fn para_atomic_pattern_receives_empty_slice() {
        let atom = Pattern::point(42);
        let result = atom.para(|p, rs| {
            // Verify atomic pattern has no elements
            assert!(rs.is_empty(), "Atomic pattern should receive empty slice");
            assert_eq!(
                p.elements().len(),
                0,
                "Atomic pattern should have no elements"
            );
            *p.value()
        });
        assert_eq!(result, 42);
    }

    /// T008: Pattern with elements receives results in element order
    #[test]
    fn para_preserves_element_order() {
        // Build pattern: root(10) with elements [point(5), point(3), point(7)]
        let p = Pattern::pattern(
            10,
            vec![Pattern::point(5), Pattern::point(3), Pattern::point(7)],
        );

        // Use para to collect values in pre-order (root first, then elements left-to-right)
        let values: Vec<i32> = p.para(|pat, child_results| {
            let mut result = vec![*pat.value()];
            for child_vec in child_results {
                result.extend(child_vec);
            }
            result
        });

        // Should be: [10, 5, 3, 7] (root, then elements in order)
        assert_eq!(values, vec![10, 5, 3, 7]);
    }

    /// T008 (additional): Nested pattern preserves element order
    #[test]
    fn para_preserves_element_order_nested() {
        // Build nested pattern:
        // root(1) with elements [
        //   pattern(2) with [point(3), point(4)],
        //   point(5)
        // ]
        let p = Pattern::pattern(
            1,
            vec![
                Pattern::pattern(2, vec![Pattern::point(3), Pattern::point(4)]),
                Pattern::point(5),
            ],
        );

        // Collect values in pre-order
        let values: Vec<i32> = p.para(|pat, child_results| {
            let mut result = vec![*pat.value()];
            for child_vec in child_results {
                result.extend(child_vec);
            }
            result
        });

        // Should be: [1, 2, 3, 4, 5] (pre-order traversal)
        assert_eq!(values, vec![1, 2, 3, 4, 5]);
    }

    /// T009: Structure access – para can access pattern structure
    #[test]
    fn para_provides_structure_access() {
        // Build pattern with known structure
        // Root(10) with [Pattern(20, [Point(30)]), Point(40)]
        // Depth: 2 (root -> pattern(20) -> point(30))
        let p = Pattern::pattern(
            10,
            vec![
                Pattern::pattern(20, vec![Pattern::point(30)]),
                Pattern::point(40),
            ],
        );

        // Test 1: Access depth at each position
        let depth_at_root = p.para(|pat, _| pat.depth());
        assert_eq!(depth_at_root, 2, "Root should have depth 2 (max nesting)");

        // Test 2: Access element count at each position
        let element_count_at_root = p.para(|pat, _| pat.elements().len());
        assert_eq!(element_count_at_root, 2, "Root should have 2 elements");

        // Test 3: Verify structure access matches direct calls
        assert_eq!(p.depth(), depth_at_root);
        assert_eq!(p.elements().len(), element_count_at_root);
    }

    /// T009 (additional): Structure access for nested patterns
    #[test]
    fn para_structure_access_nested() {
        // Pattern structure:
        // Root(1) with [Pattern(2, [Point(3), Point(4)]), Point(5)]
        // Depth: 2 (root -> pattern(2) -> point(3/4))
        let p = Pattern::pattern(
            1,
            vec![
                Pattern::pattern(2, vec![Pattern::point(3), Pattern::point(4)]),
                Pattern::point(5),
            ],
        );

        // Collect (value, depth, element_count) at each position
        type Info = (i32, usize, usize);
        let info: Info = p.para(|pat, child_infos: &[Info]| {
            let value = *pat.value();
            let depth = pat.depth();
            let elem_count = pat.elements().len();

            // Verify child infos match expected structure
            if value == 1 {
                // Root: should have 2 children
                assert_eq!(child_infos.len(), 2);
                assert_eq!(child_infos[0].0, 2); // First child value
                assert_eq!(child_infos[1].0, 5); // Second child value
            } else if value == 2 {
                // Middle node: should have 2 children
                assert_eq!(child_infos.len(), 2);
                assert_eq!(child_infos[0].0, 3);
                assert_eq!(child_infos[1].0, 4);
            } else {
                // Leaf nodes: no children
                assert_eq!(child_infos.len(), 0);
            }

            (value, depth, elem_count)
        });

        assert_eq!(info.0, 1); // Root value
        assert_eq!(info.1, 2); // Root depth (max nesting: root -> pattern(2) -> point)
        assert_eq!(info.2, 2); // Root has 2 elements
    }

    // ========================================================================
    // Phase 4: User Story 2 – Element-Count-Aware Computation
    // ========================================================================

    /// T010: Element-count-weighted computation
    #[test]
    fn para_element_count_weighted_computation() {
        // Pattern: root(10) with [point(5), point(3)]
        // Formula: value * element_count + sum(element_results)
        // Expected: 10*2 + (5*0 + 3*0) = 20 + 0 = 20
        let p = Pattern::pattern(10, vec![Pattern::point(5), Pattern::point(3)]);

        let result: i32 = p.para(|pat, rs| {
            let value = *pat.value();
            let elem_count = pat.elements().len() as i32;
            let element_sum: i32 = rs.iter().sum();
            value * elem_count + element_sum
        });

        assert_eq!(result, 20, "Root: 10*2 + (0+0) = 20");
    }

    /// T010 (additional): Element-count-weighted with nested pattern
    #[test]
    fn para_element_count_weighted_nested() {
        // Pattern: root(10) with [pattern(5, [point(2)]), point(3)]
        // Root: 10*2 + (middle_result + 0) = 20 + middle_result
        // Middle: 5*1 + (0) = 5
        // Expected: 20 + 5 = 25
        let p = Pattern::pattern(
            10,
            vec![
                Pattern::pattern(5, vec![Pattern::point(2)]),
                Pattern::point(3),
            ],
        );

        let result: i32 = p.para(|pat, rs| {
            let value = *pat.value();
            let elem_count = pat.elements().len() as i32;
            let element_sum: i32 = rs.iter().sum();
            value * elem_count + element_sum
        });

        // Root: 10*2 + (5 + 0) = 25
        // Middle pattern(5): 5*1 + 0 = 5
        // Leaves: 2*0=0, 3*0=0
        assert_eq!(result, 25);
    }

    /// T011: Nested patterns with varying element counts
    #[test]
    fn para_varying_element_counts() {
        // Build pattern with varying element counts at each level:
        // root(1) with [
        //   pattern(2, [point(3), point(4)]),  // 2 elements
        //   pattern(5, [point(6)]),             // 1 element
        //   point(7)                            // 0 elements
        // ]
        let p = Pattern::pattern(
            1,
            vec![
                Pattern::pattern(2, vec![Pattern::point(3), Pattern::point(4)]),
                Pattern::pattern(5, vec![Pattern::point(6)]),
                Pattern::point(7),
            ],
        );

        // Aggregate element counts at each level
        type CountInfo = (i32, usize); // (value, total_element_count_in_subtree)
        let result: CountInfo = p.para(|pat, rs: &[CountInfo]| {
            let value = *pat.value();
            let elem_count = pat.elements().len();
            let subtree_count: usize = rs.iter().map(|(_, count)| count).sum();
            (value, elem_count + subtree_count)
        });

        // Root has 3 direct elements
        // First element has 2 elements
        // Second element has 1 element
        // Third element has 0 elements
        // Total: 3 + 2 + 1 + 0 = 6
        assert_eq!(result.0, 1, "Root value should be 1");
        assert_eq!(
            result.1, 6,
            "Total element count across all levels should be 6"
        );
    }

    /// T011 (additional): Element count aggregation with depth
    #[test]
    fn para_element_count_by_depth() {
        // Pattern: root(1) with [pattern(2, [point(3), point(4)]), point(5)]
        let p = Pattern::pattern(
            1,
            vec![
                Pattern::pattern(2, vec![Pattern::point(3), Pattern::point(4)]),
                Pattern::point(5),
            ],
        );

        // Count elements at each depth level
        type DepthCounts = Vec<usize>; // counts[depth] = number of elements at that depth
        let result: DepthCounts = p.para(|pat, rs: &[DepthCounts]| {
            let elem_count = pat.elements().len();
            let max_depth = rs.iter().map(|v| v.len()).max().unwrap_or(0);

            let mut counts = vec![0; max_depth + 1];
            counts[0] = elem_count; // Current level

            // Aggregate from elements
            for child_counts in rs {
                for (depth, &count) in child_counts.iter().enumerate() {
                    counts[depth + 1] += count;
                }
            }

            counts
        });

        // Depth 0 (root level): 2 elements [pattern(2), point(5)]
        // Depth 1 (pattern(2) level): 2 elements [point(3), point(4)]
        // Depth 2: 0 elements (all leaves)
        assert_eq!(result[0], 2, "Root has 2 elements");
        assert_eq!(result[1], 2, "Second level has 2 elements");
    }

    // ========================================================================
    // Phase 5: User Story 3 – Nesting Statistics
    // ========================================================================

    /// T012: Atomic pattern nesting statistics
    #[test]
    fn para_atomic_nesting_statistics() {
        let atom = Pattern::point(42);

        // Compute (sum, count, max_depth) for atomic pattern
        type Stats = (i32, usize, usize);
        let stats: Stats = atom.para(|pat, rs: &[Stats]| {
            let value = *pat.value();
            let (child_sum, child_count, child_max_depth) = rs
                .iter()
                .fold((0_i32, 0_usize, 0_usize), |(s, c, d), (s2, c2, d2)| {
                    (s + s2, c + c2, d.max(*d2))
                });

            (
                value + child_sum,
                1 + child_count,
                pat.depth().max(child_max_depth),
            )
        });

        assert_eq!(stats.0, 42, "Sum should be the value itself");
        assert_eq!(stats.1, 1, "Count should be 1 (single node)");
        assert_eq!(stats.2, 0, "Max depth should be 0 (atomic pattern)");
    }

    /// T013: Nested pattern computing (sum, count, max_depth) in single traversal
    #[test]
    fn para_nested_nesting_statistics() {
        // Pattern: root(1) with [pattern(2, [point(3)]), point(4)]
        // Structure:
        //   1
        //   ├─ 2
        //   │  └─ 3
        //   └─ 4
        let p = Pattern::pattern(
            1,
            vec![
                Pattern::pattern(2, vec![Pattern::point(3)]),
                Pattern::point(4),
            ],
        );

        // Compute (sum, count, max_depth) in a single traversal
        type Stats = (i32, usize, usize);
        let stats: Stats = p.para(|pat, rs: &[Stats]| {
            let value = *pat.value();
            let (child_sum, child_count, child_max_depth) = rs
                .iter()
                .fold((0_i32, 0_usize, 0_usize), |(s, c, d), (s2, c2, d2)| {
                    (s + s2, c + c2, d.max(*d2))
                });

            (
                value + child_sum,
                1 + child_count,
                pat.depth().max(child_max_depth),
            )
        });

        assert_eq!(stats.0, 10, "Sum: 1 + 2 + 3 + 4 = 10");
        assert_eq!(stats.1, 4, "Count: 4 nodes total");
        assert_eq!(stats.2, 2, "Max depth: 2 (root -> pattern(2) -> point(3))");
    }

    /// T013 (additional): Complex nested pattern statistics
    #[test]
    fn para_complex_nesting_statistics() {
        // More complex pattern:
        // root(1) with [
        //   pattern(2, [point(3), point(4)]),
        //   pattern(5, [pattern(6, [point(7)])]),
        //   point(8)
        // ]
        let p = Pattern::pattern(
            1,
            vec![
                Pattern::pattern(2, vec![Pattern::point(3), Pattern::point(4)]),
                Pattern::pattern(5, vec![Pattern::pattern(6, vec![Pattern::point(7)])]),
                Pattern::point(8),
            ],
        );

        type Stats = (i32, usize, usize);
        let stats: Stats = p.para(|pat, rs: &[Stats]| {
            let value = *pat.value();
            let (child_sum, child_count, child_max_depth) = rs
                .iter()
                .fold((0_i32, 0_usize, 0_usize), |(s, c, d), (s2, c2, d2)| {
                    (s + s2, c + c2, d.max(*d2))
                });

            (
                value + child_sum,
                1 + child_count,
                pat.depth().max(child_max_depth),
            )
        });

        // Sum: 1+2+3+4+5+6+7+8 = 36
        assert_eq!(stats.0, 36, "Sum of all values");
        // Count: 8 nodes
        assert_eq!(stats.1, 8, "Total node count");
        // Max depth: 3 (root -> pattern(5) -> pattern(6) -> point(7))
        assert_eq!(stats.2, 3, "Maximum nesting depth");
    }

    /// T013 (additional): Verify single traversal efficiency
    #[test]
    fn para_single_traversal_statistics() {
        let p = Pattern::pattern(
            10,
            vec![
                Pattern::pattern(20, vec![Pattern::point(30), Pattern::point(40)]),
                Pattern::point(50),
            ],
        );

        // Use a counter to verify single traversal
        use std::cell::RefCell;
        let visit_count = RefCell::new(0);

        type Stats = (i32, usize, usize);
        let stats: Stats = p.para(|pat, rs: &[Stats]| {
            *visit_count.borrow_mut() += 1;

            let value = *pat.value();
            let (child_sum, child_count, child_max_depth) = rs
                .iter()
                .fold((0_i32, 0_usize, 0_usize), |(s, c, d), (s2, c2, d2)| {
                    (s + s2, c + c2, d.max(*d2))
                });

            (
                value + child_sum,
                1 + child_count,
                pat.depth().max(child_max_depth),
            )
        });

        // Verify statistics
        assert_eq!(stats.0, 150, "Sum: 10+20+30+40+50");
        assert_eq!(stats.1, 5, "Count: 5 nodes");
        assert_eq!(stats.2, 2, "Max depth: 2");

        // Verify single traversal: each node visited exactly once
        assert_eq!(
            *visit_count.borrow(),
            5,
            "Should visit each node exactly once"
        );
    }

    // ========================================================================
    // Phase 6: User Story 4 – Custom Structure-Aware Folding
    // ========================================================================

    /// T014: Para simulates fold – equivalence test
    #[test]
    fn para_simulates_fold() {
        let p = Pattern::pattern(
            10,
            vec![
                Pattern::pattern(20, vec![Pattern::point(30), Pattern::point(40)]),
                Pattern::point(50),
            ],
        );

        // Para version: sum all values
        let para_sum: i32 = p.para(|pat, rs| *pat.value() + rs.iter().sum::<i32>());

        // Fold version: sum all values
        let fold_sum: i32 = p.fold(0, |acc, v| acc + v);

        assert_eq!(para_sum, fold_sum, "Para should produce same sum as fold");
        assert_eq!(para_sum, 150, "Sum: 10+20+30+40+50 = 150");
    }

    /// T014 (additional): Para simulates fold for different operations
    #[test]
    fn para_simulates_fold_product() {
        let p = Pattern::pattern(
            2,
            vec![
                Pattern::pattern(3, vec![Pattern::point(4)]),
                Pattern::point(5),
            ],
        );

        // Para version: product of all values
        let para_product: i32 = p.para(|pat, rs| {
            let element_product: i32 = rs.iter().product();
            if element_product == 0 {
                *pat.value() // No elements, just the value
            } else {
                *pat.value() * element_product
            }
        });

        // Fold version: product of all values
        let fold_product: i32 = p.fold(1, |acc, v| acc * v);

        assert_eq!(
            para_product, fold_product,
            "Para should produce same product as fold"
        );
        assert_eq!(para_product, 120, "Product: 2*3*4*5 = 120");
    }

    /// T015: Para preserves element order (toList property)
    #[test]
    fn para_preserves_order_tolist() {
        let p = Pattern::pattern(
            1,
            vec![
                Pattern::pattern(2, vec![Pattern::point(3), Pattern::point(4)]),
                Pattern::point(5),
            ],
        );

        // Use para to build value list (pre-order: root first, then elements)
        let para_values: Vec<i32> = p.para(|pat, rs: &[Vec<i32>]| {
            let mut result = vec![*pat.value()];
            for child_vec in rs {
                result.extend(child_vec);
            }
            result
        });

        // Expected pre-order: 1, 2, 3, 4, 5
        assert_eq!(
            para_values,
            vec![1, 2, 3, 4, 5],
            "Para should preserve pre-order"
        );

        // Verify it matches values() method
        let values_method: Vec<i32> = p.values().into_iter().copied().collect();
        assert_eq!(
            para_values, values_method,
            "Para toList should match values()"
        );
    }

    /// T015 (additional): Para order preservation with different structures
    #[test]
    fn para_order_preservation_wide() {
        // Wide pattern: many siblings
        let p = Pattern::pattern(
            0,
            vec![
                Pattern::point(1),
                Pattern::point(2),
                Pattern::point(3),
                Pattern::point(4),
            ],
        );

        let para_values: Vec<i32> = p.para(|pat, rs: &[Vec<i32>]| {
            let mut result = vec![*pat.value()];
            for child_vec in rs {
                result.extend(child_vec);
            }
            result
        });

        assert_eq!(
            para_values,
            vec![0, 1, 2, 3, 4],
            "Should preserve left-to-right order"
        );
    }

    /// T016: Custom folding function with structure access
    #[test]
    fn para_custom_structure_aware_folding() {
        let p = Pattern::pattern(
            "root",
            vec![
                Pattern::pattern(
                    "branch",
                    vec![Pattern::point("leaf1"), Pattern::point("leaf2")],
                ),
                Pattern::point("leaf3"),
            ],
        );

        // Custom folding: build a description of the structure
        type Description = String;
        let description: Description = p.para(|pat, rs: &[Description]| {
            let value = *pat.value();
            let elem_count = pat.elements().len();
            let depth = pat.depth();

            if elem_count == 0 {
                // Atomic pattern
                format!("Leaf({})", value)
            } else {
                // Pattern with elements
                let children_desc = rs.join(", ");
                format!(
                    "Node({}, depth={}, elements=[{}])",
                    value, depth, children_desc
                )
            }
        });

        // Verify structure description
        assert!(description.contains("root"), "Should mention root");
        assert!(description.contains("branch"), "Should mention branch");
        assert!(description.contains("leaf1"), "Should mention leaf1");
        assert!(description.contains("depth="), "Should include depth info");
    }

    /// T016 (additional): Structure-aware transformation returning Pattern
    #[test]
    fn para_structure_preserving_transformation() {
        let p = Pattern::pattern(
            1,
            vec![
                Pattern::pattern(2, vec![Pattern::point(3)]),
                Pattern::point(4),
            ],
        );

        // Use para to transform: multiply each value by its depth + 1
        let transformed: Pattern<i32> = p.para(|pat, rs: &[Pattern<i32>]| {
            let value = *pat.value();
            let depth = pat.depth();
            let new_value = value * (depth as i32 + 1);

            Pattern::pattern(new_value, rs.to_vec())
        });

        // Verify structure is preserved
        assert_eq!(transformed.size(), p.size(), "Size should be preserved");
        assert_eq!(transformed.depth(), p.depth(), "Depth should be preserved");
        assert_eq!(
            transformed.elements().len(),
            p.elements().len(),
            "Element count should be preserved"
        );

        // Verify values are transformed correctly
        // Root (depth=2): 1 * 3 = 3
        assert_eq!(*transformed.value(), 3);
    }

    /// T016 (additional): Para with complex custom logic
    #[test]
    fn para_complex_custom_logic() {
        let p = Pattern::pattern(
            10,
            vec![
                Pattern::pattern(20, vec![Pattern::point(30)]),
                Pattern::point(40),
            ],
        );

        // Custom logic: compute weighted sum where each value is weighted by
        // (1 + number of descendants)
        type WeightedSum = (i32, usize); // (weighted_sum, descendant_count)
        let result: WeightedSum = p.para(|pat, rs: &[WeightedSum]| {
            let value = *pat.value();
            let (child_sum, child_descendants): (i32, usize) =
                rs.iter().fold((0, 0), |(s, d), (s2, d2)| (s + s2, d + d2));

            let my_descendants = child_descendants + pat.elements().len();
            let my_weighted_value = value * (1 + my_descendants) as i32;

            (my_weighted_value + child_sum, my_descendants)
        });

        // Verify the computation
        // Leaf 30: 30 * 1 = 30, descendants=0
        // Leaf 40: 40 * 1 = 40, descendants=0
        // Branch 20: 20 * 2 = 40, descendants=1 (point 30)
        // Root 10: 10 * 4 = 40, descendants=3 (branch 20, point 30, point 40)
        // Total: 30 + 40 + 40 + 40 = 150
        assert_eq!(result.0, 150, "Weighted sum should be 150");
        assert_eq!(result.1, 3, "Root should have 3 descendants");
    }
}

// ============================================================================
// Comonad Operations
// ============================================================================