summaryrefslogtreecommitdiffstats
path: root/slib.texi
blob: 77aea2a7e9907a493dd233eaf4a37acdc9da0a36 (plain)
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
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
\input texinfo @c -*-texinfo-*-
@c %**start of header
@setfilename slib.info
@settitle slib
@include version.txi
@setchapternewpage on
@c Choices for setchapternewpage are {on,off,odd}.
@paragraphindent 2
@defcodeindex ft
@syncodeindex ft cp
@syncodeindex tp cp
@c %**end of header

@copying
@noindent
This manual is for SLIB (version @value{SLIBVERSION}, @value{SLIBDATE}),
the portable Scheme library.

@noindent
@c Copyright (C) 1993 Todd R. Eigenschink@*
Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc.

@quotation
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.2 or
any later version published by the Free Software Foundation; with no
Invariant Sections, with the Front-Cover Texts being ``A GNU Manual,''
and with the Back-Cover Texts as in (a) below.  A copy of the
license is included in the section entitled ``GNU Free Documentation
License.''

(a) The FSF's Back-Cover Text is: ``You have freedom to copy and modify
this GNU Manual, like GNU software.  Copies published by the Free
Software Foundation raise funds for GNU development.''
@end quotation
@end copying

@dircategory The Algorithmic Language Scheme
@direntry
* SLIB: (slib).         Scheme Library
@end direntry

@iftex
@finalout
@c DL: lose the egregious vertical whitespace, esp. around examples
@c but paras in @defun-like things don't have parindent
@parskip 4pt plus 1pt
@end iftex

@titlepage
@title SLIB
@subtitle The Portable Scheme Library
@subtitle Version @value{SLIBVERSION}, @value{SLIBDATE}
@author Aubrey Jaffer
@page
@vskip 0pt plus 1filll
@insertcopying
@end titlepage

@contents

@ifnottex
@node Top, The Library System, (dir), (dir)
@top SLIB

@insertcopying

@menu
* The Library System::          How to use and customize.
* Universal SLIB Procedures::   Provided for all implementations.
* Scheme Syntax Extension Packages::  
* Textual Conversion Packages::  
* Mathematical Packages::       
* Database Packages::           
* Other Packages::              
* About SLIB::                  Install, etc.
* Index::                       
@end menu
@end ifnottex

@node The Library System, Universal SLIB Procedures, Top, Top
@chapter The Library System

@noindent
@dfn{SLIB} is a portable library for the programming language
@dfn{Scheme}.  It provides a platform independent framework for using
@dfn{packages} of Scheme procedures and syntax.  As distributed, SLIB
contains useful packages for all Scheme implementations.  Its catalog
can be transparently extended to accomodate packages specific to a site,
implementation, user, or directory.

@menu
* Feature::                     SLIB names.
* Require::                     
* Library Catalogs::            
* Catalog Creation::            
* Catalog Vicinities::          
* Compiling Scheme::            
@end menu


@node Feature, Require, The Library System, The Library System
@section Feature

@noindent
@cindex feature
SLIB denotes @dfn{features} by symbols.  SLIB maintains a list of
features supported by a Scheme @dfn{session}.  The set of features
@cindex session
provided by a session may change during that session.  Some features
are properties of the Scheme implementation being used.  The following
@cindex intrinsic feature
@dfn{intrinsic feature}s detail what sort of numbers are available
from an implementation:

@ftindex inexact
@ftindex rational
@ftindex real
@ftindex complex
@ftindex bignum

@itemize @bullet
@item
'inexact
@item
'rational
@item
'real
@item
'complex
@item
'bignum
@end itemize

@noindent
SLIB initialization (in @file{require.scm}) tests and @dfn{provide}s
any of these numeric features which are appropriate.

@noindent
Other features correspond to the presence of packages of Scheme
procedures or syntax (macros).

@defun provided? feature
Returns @code{#t} if @var{feature} is present in the current Scheme
session; otherwise @code{#f}.  More specifically, @code{provided?}
returns @code{#t} if the symbol @var{feature} is the
@code{software-type}, the @code{scheme-implementation-type}
@footnote{scheme-implementation-type is the name symbol of the running
Scheme implementation (RScheme, |STk|, Bigloo, chez, Elk, gambit,
guile, JScheme, MacScheme, MITScheme, Pocket-Scheme, Scheme48,
Scheme->C, Scheme48, Scsh, T, umb-scheme, or Vscm).  Dependence on
scheme-implementation-type is almost always the wrong way to do
things.}, or if @var{feature} has been provided by a module already
loaded; and @code{#f} otherwise.

In some implementations @code{provided?} tests whether a module has
been @code{require}d by any module or in any thread; other
implementations will have @code{provided?} reflect only the modules
@code{require}d by that particular session or thread.

To work portably in both scenarios, use @code{provided?} only to test
whether intrinsic properties (like those above) are present.

The @var{feature} argument can also be an expression calling
@code{and}, @code{or}, and @code{not} of features.  The boolean result
of the logical question asked by @var{feature} is returned.
@end defun

@noindent
The generalization of @code{provided?} for arbitrary features and catalog
is @code{feature-eval}:

@defun feature-eval expression provided?
Evaluates @code{and}, @code{or}, and @code{not} forms in
@var{expression}, using the values returned by calling @var{provided?}
on the leaf symbols.  @code{feature-eval} returns the boolean result
of the logical combinations.
@end defun

@deffn {Procedure} provide feature
Informs SLIB that @var{feature} is supported in this session.
@end deffn

@example
(provided? 'foo)    @result{} #f
(provide 'foo)
(provided? 'foo)    @result{} #t
@end example

@c @defvar slib:features
@c Is a list of symbols denoting features present in this implementation.
@c @var{slib:features} can grow as modules are @code{require}d.
@c @footnote{The variables @var{*modules*} and @var{slib:features} were
@c originally modeled on variables of the same names in common-lisp.  But
@c the distinction between features native to an implementation versus
@c those provided by loading files was not useful.  The symbols in
@c @var{slib:features} now indicate the presence of a capability regardless
@c of how it was provided.}
@c @end defvar


@node Require, Library Catalogs, Feature, The Library System
@section Require

@noindent
@cindex catalog
SLIB creates and maintains a @dfn{catalog} mapping features to locations
of files introducing procedures and syntax denoted by those features.

@defvar *catalog*
Is an association list of features (symbols) and pathnames which will
supply those features.  The pathname can be either a string or a pair.
If pathname is a pair then the first element should be a macro feature
symbol, @code{source}, @code{compiled}, or one of the other cases
described in @ref{Library Catalogs}.  The cdr of the pathname should
be either a string or a list.
@end defvar

@noindent
At the beginning of each section of this manual, there is a line like
@code{(require '@var{feature})}.
@ftindex feature
The Scheme files comprising SLIB are cataloged so that these feature
names map to the corresponding files.

@noindent
SLIB provides a form, @code{require}, which loads the files providing
the requested feature.

@deffn {Procedure} require feature
@itemize @bullet
@item
If @code{(provided? @var{feature})} is true,
then @code{require} just returns.
@item
Otherwise, if @var{feature} is found in the catalog, then the
corresponding files will be loaded and @code{(provided?
@var{feature})} will henceforth return @code{#t}.  That @var{feature}
is thereafter @code{provided}.
@item
Otherwise (@var{feature} not found in the catalog), an error is
signaled.
@end itemize
@end deffn

@noindent
There is a related form @code{require-if}, used primarily for enabling
compilers to statically include modules which would be dynamically
loaded by interpreters.

@deffn {Procedure} require-if condition feature

Requires @var{feature} if @var{condition} is true.
@end deffn

@noindent
The @code{random} module uses @code{require-if} to flag
@code{object->string} as a (dynamic) required module.

@example
(require 'byte)
(require 'logical)
(require-if 'compiling 'object->string)
@end example

@noindent
The @code{batch} module uses @code{require-if} to flag
@code{posix-time} as a module to load if the implementation supports
large precision exact integers.

@example
(require-if '(and bignum compiling) 'posix-time)
@end example

@noindent
The catalog can also be queried using @code{slib:in-catalog?}.

@defun slib:in-catalog? feature
Returns a @code{CDR} of the catalog entry if one was found for the
symbol @var{feature} in the alist @code{*catalog*} (and transitively
through any symbol aliases encountered).  Otherwise, returns
@code{#f}.  The format of catalog entries is explained in @ref{Library
Catalogs}.
@end defun


@node Library Catalogs, Catalog Creation, Require, The Library System
@section Library Catalogs

@noindent
Catalog files consist of one or more @dfn{association list}s.
@cindex Catalog File
In the circumstance where a feature symbol appears in more than one
list, the latter list's association is retrieved.  Here are the
supported formats for elements of catalog lists:

@table @code
@item (@var{feature} . @i{<symbol>})
Redirects to the feature named @i{<symbol>}.
@item (@var{feature} . "@i{<path>}")
Loads file @i{<path>}.
@item (@var{feature} source "@i{<path>"})
@cindex source
@code{slib:load}s the Scheme source file @i{<path>}.
@item (@var{feature} compiled "@i{<path>"} @dots{})
@cindex compiled
@code{slib:load-compiled}s the files @i{<path>} @dots{}.
@item (@var{feature} aggregate @i{<symbol>} @dots{})
@cindex aggregate
@code{require}s the features @i{<symbol>} @dots{}.
@end table

@noindent
The various macro styles first @code{require} the named macro package,
then just load @i{<path>} or load-and-macro-expand @i{<path>} as
appropriate for the implementation.

@table @code
@item (@var{feature} defmacro "@i{<path>"})
@cindex defmacro
@code{defmacro:load}s the Scheme source file @i{<path>}.
@item (@var{feature} macro-by-example "@i{<path>"})
@cindex macro-by-example
@code{defmacro:load}s the Scheme source file @i{<path>}.
@end table

@table @code
@item (@var{feature} macro "@i{<path>"})
@cindex macro
@code{macro:load}s the Scheme source file @i{<path>}.
@item (@var{feature} macros-that-work "@i{<path>"})
@cindex macros-that-work
@code{macro:load}s the Scheme source file @i{<path>}.
@item (@var{feature} syntax-case "@i{<path>"})
@cindex syntax-case
@code{macro:load}s the Scheme source file @i{<path>}.
@item (@var{feature} syntactic-closures "@i{<path>"})
@cindex syntactic-closures
@code{macro:load}s the Scheme source file @i{<path>}.
@end table

@c the following paragraph added by tb (Thomas Bushnell, BSG)
@noindent
Note that file names indicated as @i{<path>} may have ``.scm'' or
another suffix appended to them, depending on the specific Scheme
system you are using.

@node Catalog Creation, Catalog Vicinities, Library Catalogs, The Library System
@section Catalog Creation

@noindent
At the start of an interactive session no catalog is present, but is
created with the first catalog inquiry (such as @code{(require
'random)}).  Several sources of catalog information are combined to
produce the catalog:

@itemize @bullet
@item
standard SLIB packages.
@item
additional packages of interest to this site.
@item
packages specifically for the variety of Scheme which this
session is running.
@item
packages this user wants to always have available.  This catalog is the
file @file{homecat} in the user's @dfn{HOME} directory.
@cindex HOME
@item
packages germane to working in this (current working) directory.  This
catalog is the file @file{usercat} in the directory to which it applies.
One would typically @code{cd} to this directory before starting the
Scheme session.
@item
packages which are part of an application program.
@end itemize

@noindent
SLIB combines the catalog information which doesn't vary per user into
the file @file{slibcat} in the implementation-vicinity.  Therefore
@file{slibcat} needs change only when new software is installed or
compiled.  Because the actual pathnames of files can differ from
installation to installation, SLIB builds a separate catalog for each
implementation it is used with.

@noindent
The definition of @code{*slib-version*} in SLIB file
@file{require.scm} is checked against the catalog association of
@code{*slib-version*} to ascertain when versions have changed.  It is
a reasonable practice to change the definition of
@code{*slib-version*} whenever the library is changed.  If multiple
implementations of Scheme use SLIB, remember that recompiling one
@file{slibcat} will update only that implementation's catalog.

@noindent
The compilation scripts of Scheme implementations which work with SLIB
can automatically trigger catalog compilation by deleting
@file{slibcat} or by invoking @code{require} of a special feature:

@deffn {Procedure} require @r{'new-catalog}
@cindex new-catalog
This will load @file{mklibcat}, which compiles and writes a new
@file{slibcat}.
@end deffn

@noindent
Another special feature of @code{require} erases SLIB's catalog,
forcing it to be reloaded the next time the catalog is queried.

@deffn {Procedure} require @r{#f}
Removes SLIB's catalog information.  This should be done before saving
an executable image so that, when restored, its catalog will be loaded
afresh.
@end deffn


@node Catalog Vicinities, Compiling Scheme, Catalog Creation, The Library System
@section Catalog Vicinities

@noindent
Each file in the table below is descibed in terms of its
file-system independent @dfn{vicinity} (@pxref{Vicinity}).  The entries
of a catalog in the table override those of catalogs above it in the
table.

@table @asis

@item @code{implementation-vicinity} @file{slibcat}
@cindex slibcat
This file contains the associations for the packages comprising SLIB,
the @file{implcat} and the @file{sitecat}s.  The associations in the
other catalogs override those of the standard catalog.

@item @code{library-vicinity} @file{mklibcat.scm}
@cindex mklibcat.scm
creates @file{slibcat}.

@item @code{library-vicinity} @file{sitecat}
@cindex sitecat
This file contains the associations specific to an SLIB installation.

@item @code{implementation-vicinity} @file{implcat}
@cindex implcat
This file contains the associations specific to an implementation of
Scheme.  Different implementations of Scheme should have different
@code{implementation-vicinity}.

@item @code{implementation-vicinity} @file{mkimpcat.scm}
@cindex mkimpcat.scm
if present, creates @file{implcat}.

@item @code{implementation-vicinity} @file{sitecat}
@cindex sitecat
This file contains the associations specific to a Scheme implementation
installation.

@item @code{home-vicinity} @file{homecat}
@cindex homecat
This file contains the associations specific to an SLIB user.

@item @code{user-vicinity} @file{usercat}
@cindex usercat
This file contains associations affecting only those sessions whose
@dfn{working directory} is @code{user-vicinity}.

@end table

@noindent
Here is an example of a @file{usercat} catalog.  A program in this
directory can invoke the @samp{run} feature with @code{(require 'run)}.

@example
;;; "usercat": SLIB catalog additions for SIMSYNCH.     -*-scheme-*-
(
 (simsynch      . "../synch/simsynch.scm")
 (run           . "../synch/run.scm")
 (schlep        . "schlep.scm")
)
@end example

@noindent
Copying @file{usercat} to many directories is inconvenient.
Application programs which aren't always run in specially prepared
directories can nonetheless register their features during
initialization.

@deffn {Procedure} catalog:read vicinity catalog
Reads file named by string @var{catalog} in @var{vicinity}, resolving
all paths relative to @var{vicinity}, and adds those feature
associations to @var{*catalog*}.

@code{catalog:read} would typically be used by an application program
having dynamically loadable modules.  For instance, to register
factoring and other modules in @var{*catalog*}, JACAL does:

@example
(catalog:read (program-vicinity) "jacalcat")
@end example

@end deffn

@noindent
For an application program there are three appropriate venues for
registering its catalog associations:

@itemize @bullet
@item
in a @file{usercat} file in the directory where the program runs; or
@item
in an @file{implcat} file in the @code{implementation-vicinity}; or
@item
in an application program directory; loaded by calling
@code{catalog:read}.
@end itemize


@node Compiling Scheme,  , Catalog Vicinities, The Library System
@section Compiling Scheme

To use Scheme compilers effectively with SLIB the compiler needs to
know which SLIB modules are to be compiled and which symbols are
exported from those modules.

The procedures in this section automate the extraction of this
information from SLIB modules.  They are guaranteed to work on SLIB
modules; to use them on other sources, those sources should follow
SLIB conventions.

@menu
* Module Conventions::          
* Module Manifests::            
* Module Semantics::            
* Top-level Variable References::  
* Module Analysis::             
@end menu

@node Module Conventions, Module Manifests, Compiling Scheme, Compiling Scheme
@subsection Module Conventions

@itemize @bullet
@item
All the top-level @code{require} commands have one quoted argument and
are positioned before other Scheme definitions and expressions in the
file.
@item
Any conditionally @code{require}d SLIB modules
@footnote{There are some functions with internal @code{require} calls
to delay loading modules until they are needed.  While this reduces
startup latency for interpreters, it can produce headaches for
compilers.}
also appear at the beginning of their files conditioned on the feature
@cindex compiling
@code{compiling} using @code{require-if}
(@pxref{Require, require-if}).

@example
(require 'logical)
(require 'multiarg/and-)
(require-if 'compiling 'sort)
(require-if 'compiling 'ciexyz)
@end example

@item
Schmooz-style comments preceding a definition, identify that
definition as an exported identifier (@pxref{Schmooz}).  For
non-schmooz files, putting @samp{;@@} at the beginning of the line
immediately preceding the definition (@code{define},
@code{define-syntax}, or @code{defmacro}) suffices.

@example
;@@
(define (identity <obj>) <obj>)
@end example

@item
Syntax (macro) definitions are grouped at the end of a module file.

@item
Modules defining macros do not invoke those macros.  SLIB macro
implementations are exempt from this rule.

An example of how to expand macro invocations is:

@example
(require 'macros-that-work)
(require 'yasos)
(require 'pprint-file)
(pprint-filter-file "collect.scm" macwork:expand)
@end example

@end itemize


@node Module Manifests, Module Semantics, Module Conventions, Compiling Scheme
@subsection Module Manifests

@include manifest.txi


@node Module Semantics, Top-level Variable References, Module Manifests, Compiling Scheme
@subsection Module Semantics

For the purpose of compiling Scheme code, each top-level
@code{require} makes the identifiers exported by its feature's module
@code{defined} (or defmacroed or defined-syntaxed) within the file
(being compiled) headed with those requires.

Top-level occurrences of @code{require-if} make defined the exports
from the module named by the second argument @emph{if} the
@var{feature-expression} first argument is true in the target
environment.  The target feature @code{compiling} should be provided
during this phase of compilation.

Non-top-level SLIB occurences of @code{require} and @code{require-if}
of quoted features can be ignored by compilers.  The SLIB modules will
all have top-level constructs for those features.

@cindex aggregate
Note that aggregate catalog entries import more than one module.
Implementations of @code{require} may or may @emph{not} be transitive;
code which uses module exports without requiring the providing module
is in error.

In the SLIB modules @code{modular}, @code{batch}, @code{hash},
@code{common-lisp-time}, @code{commutative-ring}, @code{charplot},
@code{logical}, @code{common-list-functions}, @code{coerce} and
@code{break} there is code conditional on features being
@code{provided?}.  Most are testing for the presence of features which
are intrinsic to implementations (inexacts, bignums, ...).

In all cases these @code{provided?} tests can be evaluated at
compile-time using @code{feature-eval}
(@pxref{Feature, feature-eval}).  The simplest way to compile these
constructs may be to treat @code{provided?} as a macro.


@node Top-level Variable References, Module Analysis, Module Semantics, Compiling Scheme
@subsection Top-level Variable References

@include top-refs.txi



@node Module Analysis,  , Top-level Variable References, Compiling Scheme
@subsection Module Analysis

@include vet.txi



@node Universal SLIB Procedures, Scheme Syntax Extension Packages, The Library System, Top
@chapter Universal SLIB Procedures

@noindent
The procedures described in these sections are supported by all
implementations as part of the @samp{*.init} files or by
@file{require.scm}.

@menu
* Vicinity::                    Pathname Management
* Configuration::               Characteristics of Scheme Implementation
* Input/Output::                Things not provided by the Scheme specs.
* System::                      LOADing, EVALing, ERRORing, and EXITing
* Miscellany::                  
@end menu


@node Vicinity, Configuration, Universal SLIB Procedures, Universal SLIB Procedures
@section Vicinity

@noindent
A vicinity is a descriptor for a place in the file system.  Vicinities
hide from the programmer the concepts of host, volume, directory, and
version.  Vicinities express only the concept of a file environment
where a file name can be resolved to a file in a system independent
manner.  Vicinities can even be used on @dfn{flat} file systems (which
have no directory structure) by having the vicinity express constraints
on the file name.

All of these procedures are file-system dependent.  Use of these
vicinity procedures can make programs file-system @emph{in}dependent.

@noindent
These procedures are provided by all implementations.
On most systems a vicinity is a string.

@defun make-vicinity dirpath
Returns @var{dirpath} as a vicinity for use as first argument to
@code{in-vicinity}.
@end defun

@defun pathname->vicinity path
Returns the vicinity containing @var{path}.
@example
(pathname->vicinity "/usr/local/lib/scm/Link.scm")
                    @result{} "/usr/local/lib/scm/"
@end example
@end defun

@defun program-vicinity
Returns the vicinity of the currently loading Scheme code.  For an
interpreter this would be the directory containing source code.  For a
compiled system (with multiple files) this would be the directory
where the object or executable files are.  If no file is currently
loading, then the result is undefined.  @strong{Warning:}
@code{program-vicinity} can return incorrect values if your program
escapes back into a @code{load} continuation.
@end defun

@defun library-vicinity
Returns the vicinity of the shared Scheme library.
@end defun

@defun implementation-vicinity
Returns the vicinity of the underlying Scheme implementation.  This
vicinity will likely contain startup code and messages and a compiler.
@end defun

@defun user-vicinity
Returns the vicinity of the current directory of the user.  On most
systems this is @file{""} (the empty string).
@end defun

@defun home-vicinity
Returns the vicinity of the user's @dfn{HOME} directory, the directory
@cindex HOME
which typically contains files which customize a computer environment
for a user.  If scheme is running without a user (eg. a daemon) or if
this concept is meaningless for the platform, then @code{home-vicinity}
returns @code{#f}.
@end defun

@c @defun scheme-file-suffix
@c Returns the default filename suffix for scheme source files.  On most
@c systems this is @samp{.scm}.
@c @end defun

@defun vicinity:suffix? chr
Returns the @samp{#t} if @var{chr} is a vicinity suffix character; and
@code{#f} otherwise.  Typical vicinity suffixes are @samp{/},
@samp{:}, and @samp{\},
@end defun

@defun in-vicinity vicinity filename
Returns a filename suitable for use by @code{slib:load},
@code{slib:load-source}, @code{slib:load-compiled},
@code{open-input-file}, @code{open-output-file}, etc.  The returned
filename is @var{filename} in @var{vicinity}.  @code{in-vicinity} should
allow @var{filename} to override @var{vicinity} when @var{filename} is
an absolute pathname and @var{vicinity} is equal to the value of
@code{(user-vicinity)}.  The behavior of @code{in-vicinity} when
@var{filename} is absolute and @var{vicinity} is not equal to the value
of @code{(user-vicinity)} is unspecified.  For most systems
@code{in-vicinity} can be @code{string-append}.
@end defun

@defun sub-vicinity vicinity name
Returns the vicinity of @var{vicinity} restricted to @var{name}.  This
is used for large systems where names of files in subsystems could
conflict.  On systems with directory structure @code{sub-vicinity} will
return a pathname of the subdirectory @var{name} of
@var{vicinity}.
@end defun

@defun with-load-pathname path thunk
@var{path} should be a string naming a file being read or loaded.
@code{with-load-pathname} evaluates @var{thunk} in a dynamic scope
where an internal variable is bound to @var{path}; the internal
variable is used for messages and @code{program-vicinity}.
@code{with-load-pathname} returns the value returned by @var{thunk}.
@end defun



@node Configuration, Input/Output, Vicinity, Universal SLIB Procedures
@section Configuration

@noindent
These constants and procedures describe characteristics of the Scheme
and underlying operating system.  They are provided by all
implementations.

@defvr Constant char-code-limit
An integer 1 larger that the largest value which can be returned by
@code{char->integer}.
@end defvr

@defvr Constant most-positive-fixnum
In implementations which support integers of practically unlimited size,
@var{most-positive-fixnum} is a large exact integer within the range of
exact integers that may result from computing the length of a list,
vector, or string.

In implementations which do not support integers of practically
unlimited size, @var{most-positive-fixnum} is the largest exact integer
that may result from computing the length of a list, vector, or string.
@end defvr

@defvr Constant slib:tab
The tab character.
@end defvr

@defvr Constant slib:form-feed
The form-feed character.
@end defvr

@defun software-type
Returns a symbol denoting the generic operating system type.  For
instance, @code{unix}, @code{vms}, @code{macos}, @code{amiga}, or
@code{ms-dos}.
@end defun

@defun slib:report-version
Displays the versions of SLIB and the underlying Scheme implementation
and the name of the operating system.  An unspecified value is returned.

@example
(slib:report-version) @result{} slib "@value{SLIBVERSION}" on scm "5b1" on unix
@end example
@end defun

@defun slib:report
Displays the information of @code{(slib:report-version)} followed by
almost all the information neccessary for submitting a problem report.
An unspecified value is returned.

@defunx slib:report #t
provides a more verbose listing.

@defunx slib:report filename
Writes the report to file @file{filename}.

@example
(slib:report)
@result{}
slib "@value{SLIBVERSION}" on scm "5b1" on unix
(implementation-vicinity) is "/usr/local/lib/scm/"
(library-vicinity) is "/usr/local/lib/slib/"
(scheme-file-suffix) is ".scm"
loaded slib:features :
        trace alist qp sort
        common-list-functions macro values getopt
        compiled
implementation slib:features :
        bignum complex real rational
        inexact vicinity ed getenv
        tmpnam abort transcript with-file
        ieee-p1178 r4rs rev4-optional-procedures hash
        object-hash delay eval dynamic-wind
        multiarg-apply multiarg/and- logical defmacro
        string-port source current-time record
        rev3-procedures rev2-procedures sun-dl string-case
        array dump char-ready? full-continuation
        system
implementation *catalog* :
        (i/o-extensions compiled "/usr/local/lib/scm/ioext.so")
        ...
@end example
@end defun

@node Input/Output, System, Configuration, Universal SLIB Procedures
@section Input/Output

@noindent
These procedures are provided by all implementations.

@defun file-exists? filename
Returns @code{#t} if the specified file exists.  Otherwise, returns
@code{#f}.  If the underlying implementation does not support this
feature then @code{#f} is always returned.
@end defun

@defun delete-file filename
Deletes the file specified by @var{filename}.  If @var{filename} can not
be deleted, @code{#f} is returned.  Otherwise, @code{#t} is
returned.
@end defun

@defun open-file filename modes
@var{filename} should be a string naming a file.  @code{open-file}
returns a port depending on the symbol @var{modes}:

@table @r
@item r
an input port capable of delivering characters from the file.
@item rb
a @emph{binary} input port capable of delivering characters from the file.
@item w
an output port capable of writing characters to a new file by that name.
@item wb
a @emph{binary} output port capable of writing characters to a new file
by that name.
@end table

If an implementation does not distinguish between binary and non-binary
files, then it must treat @r{rb} as @r{r} and @r{wb} as @r{w}.

If the file cannot be opened, either #f is returned or an error is
signalled.  For output, if a file with the given name already exists,
the effect is unspecified.
@end defun

@defun port? obj
Returns @t{#t} if @var{obj} is an input or output port, otherwise
returns @t{#f}.
@end defun

@deffn {Procedure} close-port port
Closes the file associated with @var{port}, rendering the @var{port}
incapable of delivering or accepting characters.

@code{close-file} has no effect if the file has already been closed.
The value returned is unspecified.
@end deffn

@defun call-with-open-ports proc ports @dots{}
@defunx call-with-open-ports ports @dots{} proc
@var{Proc} should be a procedure that accepts as many arguments as there
are @var{ports} passed to @code{call-with-open-ports}.
@code{call-with-open-ports} calls @var{proc} with @var{ports} @dots{}.
If @var{proc} returns, then the ports are closed automatically and the
value yielded by the @var{proc} is returned.  If @var{proc} does not
return, then the ports will not be closed automatically unless it is
possible to prove that the ports will never again be used for a read or
write operation.
@end defun

@defun tmpnam
Returns a pathname for a file which will likely not be used by any other
process.  Successive calls to @code{(tmpnam)} will return different
pathnames.
@end defun

@defun current-error-port
Returns the current port to which diagnostic and error output is
directed.
@end defun

@deffn {Procedure} force-output
@deffnx {Procedure} force-output port
Forces any pending output on @var{port} to be delivered to the output
device and returns an unspecified value.  The @var{port} argument may be
omitted, in which case it defaults to the value returned by
@code{(current-output-port)}.
@end deffn

@defun output-port-width
@defunx output-port-width port

Returns the width of @var{port}, which defaults to
@code{(current-output-port)} if absent.  If the width cannot be
determined 79 is returned.
@end defun

@defun output-port-height
@defunx output-port-height port

Returns the height of @var{port}, which defaults to
@code{(current-output-port)} if absent.  If the height cannot be
determined 24 is returned.
@end defun


@node System, Miscellany, Input/Output, Universal SLIB Procedures
@section System

@noindent
These procedures are provided by all implementations.

@deffn {Procedure} slib:load-source name
Loads a file of Scheme source code from @var{name} with the default
filename extension used in SLIB.  For instance if the filename extension
used in SLIB is @file{.scm} then @code{(slib:load-source "foo")} will
load from file @file{foo.scm}.
@end deffn

@deffn {Procedure} slib:load-compiled name
On implementations which support separtely loadable compiled modules,
loads a file of compiled code from @var{name} with the implementation's
filename extension for compiled code appended.
@end deffn

@deffn {Procedure} slib:load name
Loads a file of Scheme source or compiled code from @var{name} with the
appropriate suffixes appended.  If both source and compiled code are
present with the appropriate names then the implementation will load
just one.  It is up to the implementation to choose which one will be
loaded.

If an implementation does not support compiled code then
@code{slib:load} will be identical to @code{slib:load-source}.
@end deffn

@deffn {Procedure} slib:eval obj
@code{eval} returns the value of @var{obj} evaluated in the current top
level environment.  @ref{Eval} provides a more general evaluation
facility.
@end deffn

@deffn {Procedure} slib:eval-load filename eval
@var{filename} should be a string.  If filename names an existing file,
the Scheme source code expressions and definitions are read from the
file and @var{eval} called with them sequentially.  The
@code{slib:eval-load} procedure does not affect the values returned by
@code{current-input-port} and @code{current-output-port}.
@end deffn

@deffn {Procedure} slib:warn arg1 arg2 @dots{}
Outputs a warning message containing the arguments.
@end deffn

@deffn {Procedure} slib:error arg1 arg2 @dots{}
Outputs an error message containing the arguments, aborts evaluation of
the current form and responds in a system dependent way to the error.
Typical responses are to abort the program or to enter a read-eval-print
loop.
@end deffn

@deffn {Procedure} slib:exit n
@deffnx {Procedure} slib:exit
Exits from the Scheme session returning status @var{n} to the system.
If @var{n} is omitted or @code{#t}, a success status is returned to the
system (if possible).  If @var{n} is @code{#f} a failure is returned to
the system (if possible).  If @var{n} is an integer, then @var{n} is
returned to the system (if possible).  If the Scheme session cannot exit
an unspecified value is returned from @code{slib:exit}.
@end deffn

@defun browse-url url
Web browsers have become so ubiquitous that programming languagues
should support a uniform interface to them.

If a @samp{netscape} browser is running, @code{browse-url} causes the
browser to display the page specified by string @var{url} and returns
#t.

If the browser is not running, @code{browse-url} starts a browser
displaying the argument @var{url}.  If the browser starts as a
background job, @code{browse-url} returns #t immediately; if the
browser starts as a foreground job, then @code{browse-url} returns #t
when the browser exits; otherwise it returns #f.
@end defun


@node Miscellany,  , System, Universal SLIB Procedures
@section Miscellany

These procedures are provided by all implementations.

@defun identity x
@var{identity} returns its argument.

Example:
@lisp
(identity 3)
   @result{} 3
(identity '(foo bar))
   @result{} (foo bar)
(map identity @var{lst})
   @equiv{} (copy-list @var{lst})
@end lisp
@end defun

@defun expt n k
Returns @var{n} raised to the non-negative integer exponent @var{k}.

Example:
@lisp
(expt 2 5)
   @result{} 32
(expt -3 3)
   @result{} -27
@end lisp
@end defun


@subsection Mutual Exclusion

@noindent
An @dfn{exchanger} is a procedure of one argument regulating mutually
@cindex exchanger
exclusive access to a resource.  When a exchanger is called, its current
content is returned, while being replaced by its argument in an atomic
operation.

@defun make-exchanger obj

Returns a new exchanger with the argument @var{obj} as its initial
content.

@example
(define queue (make-exchanger (list a)))
@end example

A queue implemented as an exchanger holding a list can be protected from
reentrant execution thus:

@example
(define (pop queue)
  (let ((lst #f))
    (dynamic-wind
        (lambda () (set! lst (queue #f)))
        (lambda () (and lst (not (null? lst))
                        (let ((ret (car lst)))
                          (set! lst (cdr lst))
                          ret)))
        (lambda () (and lst (queue lst))))))

(pop queue)         @result{} a

(pop queue)         @result{} #f
@end example
@end defun


@subsection Legacy

@noindent
The following procedures were present in Scheme until R4RS
(@pxref{Notes, , Language changes ,r4rs, Revised(4) Scheme}).
They are provided by all SLIB implementations.

@defvr Constant t
Defined as @code{#t}.
@end defvr

@defvr Constant nil
Defined as @code{#f}.
@end defvr

@defun last-pair l
Returns the last pair in the list @var{l}.  Example:
@lisp
(last-pair (cons 1 2))
   @result{} (1 . 2)
(last-pair '(1 2))
   @result{} (2)
    @equiv{} (cons 2 '())
@end lisp
@end defun


@node Scheme Syntax Extension Packages, Textual Conversion Packages, Universal SLIB Procedures, Top
@chapter Scheme Syntax Extension Packages

@menu
* Defmacro::                    Supported by all implementations

* R4RS Macros::                 'macro
* Macro by Example::            'macro-by-example
* Macros That Work::            'macros-that-work
* Syntactic Closures::          'syntactic-closures
* Syntax-Case Macros::          'syntax-case

Syntax extensions (macros) included with SLIB.

* Define-Structure::            'structure
* Define-Record-Type::          'define-record-type, 'srfi-9
* Fluid-Let::                   'fluid-let
* Binding to multiple values::  'receive, 'srfi-8
* Guarded LET* special form::   'and-let*, 'srfi-2
* Guarded COND Clause::         'guarded-cond-clause, 'srfi-61
* Yasos::                       'yasos, 'oop, 'collect
@end menu


@node Defmacro, R4RS Macros, Scheme Syntax Extension Packages, Scheme Syntax Extension Packages
@section Defmacro

Defmacros are supported by all implementations.
@c See also @code{gentemp}, in @ref{Macros}.

@defun gentemp
Returns a new (interned) symbol each time it is called.  The symbol
names are implementation-dependent
@lisp
(gentemp) @result{} scm:G0
(gentemp) @result{} scm:G1
@end lisp
@end defun

@defun defmacro:eval e
Returns the @code{slib:eval} of expanding all defmacros in scheme
expression @var{e}.
@end defun

@defun defmacro:load filename
@var{filename} should be a string.  If filename names an existing file,
the @code{defmacro:load} procedure reads Scheme source code expressions
and definitions from the file and evaluates them sequentially.  These
source code expressions and definitions may contain defmacro
definitions.  The @code{macro:load} procedure does not affect the values
returned by @code{current-input-port} and
@code{current-output-port}.
@end defun

@defun defmacro? sym
Returns @code{#t} if @var{sym} has been defined by @code{defmacro},
@code{#f} otherwise.
@end defun

@defun macroexpand-1 form
@defunx macroexpand form
If @var{form} is a macro call, @code{macroexpand-1} will expand the
macro call once and return it.  A @var{form} is considered to be a macro
call only if it is a cons whose @code{car} is a symbol for which a
@code{defmacro} has been defined.

@code{macroexpand} is similar to @code{macroexpand-1}, but repeatedly
expands @var{form} until it is no longer a macro call.
@end defun

@defmac defmacro name lambda-list form @dots{}
When encountered by @code{defmacro:eval}, @code{defmacro:macroexpand*},
or @code{defmacro:load} defines a new macro which will henceforth be
expanded when encountered by @code{defmacro:eval},
@code{defmacro:macroexpand*}, or @code{defmacro:load}.
@end defmac

@subsection Defmacroexpand
@code{(require 'defmacroexpand)}
@ftindex defmacroexpand

@defun defmacro:expand* e
Returns the result of expanding all defmacros in scheme expression
@var{e}.
@end defun

@node R4RS Macros, Macro by Example, Defmacro, Scheme Syntax Extension Packages
@section R4RS Macros

@code{(require 'macro)} is the appropriate call if you want R4RS
@ftindex macro
high-level macros but don't care about the low level implementation.  If
an SLIB R4RS macro implementation is already loaded it will be used.
Otherwise, one of the R4RS macros implemetations is loaded.

The SLIB R4RS macro implementations support the following uniform
interface:

@defun macro:expand sexpression
Takes an R4RS expression, macro-expands it, and returns the result of
the macro expansion.
@end defun

@defun macro:eval sexpression
Takes an R4RS expression, macro-expands it, evals the result of the
macro expansion, and returns the result of the evaluation.
@end defun

@deffn {Procedure} macro:load filename
@var{filename} should be a string.  If filename names an existing file,
the @code{macro:load} procedure reads Scheme source code expressions and
definitions from the file and evaluates them sequentially.  These source
code expressions and definitions may contain macro definitions.  The
@code{macro:load} procedure does not affect the values returned by
@code{current-input-port} and @code{current-output-port}.
@end deffn

@node  Macro by Example, Macros That Work, R4RS Macros, Scheme Syntax Extension Packages
@section Macro by Example

@code{(require 'macro-by-example)}
@ftindex macro-by-example

A vanilla implementation of @cite{Macro by Example} (Eugene Kohlbecker,
R4RS) by Dorai Sitaram, (dorai @@ cs.rice.edu) using @code{defmacro}.

@itemize @bullet

@item
generating hygienic global @code{define-syntax} Macro-by-Example macros
@strong{cheaply}.

@item
can define macros which use @code{...}.

@item
needn't worry about a lexical variable in a macro definition
clashing with a variable from the macro use context

@item
don't suffer the overhead of redefining the repl if @code{defmacro}
natively supported (most implementations)

@end itemize
@subsection Caveat
These macros are not referentially transparent (@pxref{Macros, , ,r4rs,
Revised(4) Scheme}).  Lexically scoped macros (i.e., @code{let-syntax}
and @code{letrec-syntax}) are not supported.  In any case, the problem
of referential transparency gains poignancy only when @code{let-syntax}
and @code{letrec-syntax} are used.  So you will not be courting
large-scale disaster unless you're using system-function names as local
variables with unintuitive bindings that the macro can't use.  However,
if you must have the full @cite{r4rs} macro functionality, look to the
more featureful (but also more expensive) versions of syntax-rules
available in slib @ref{Macros That Work}, @ref{Syntactic Closures}, and
@ref{Syntax-Case Macros}.

@defmac define-syntax keyword transformer-spec
The @var{keyword} is an identifier, and the @var{transformer-spec}
should be an instance of @code{syntax-rules}.

The top-level syntactic environment is extended by binding the
@var{keyword} to the specified transformer.

@example
(define-syntax let*
  (syntax-rules ()
    ((let* () body1 body2 ...)
     (let () body1 body2 ...))
    ((let* ((name1 val1) (name2 val2) ...)
       body1 body2 ...)
     (let ((name1 val1))
       (let* (( name2 val2) ...)
         body1 body2 ...)))))
@end example
@end defmac

@defmac syntax-rules literals syntax-rule @dots{}
@var{literals} is a list of identifiers, and each @var{syntax-rule}
should be of the form

@code{(@var{pattern} @var{template})}

where the @var{pattern} and  @var{template} are as in the grammar above.

An instance of @code{syntax-rules} produces a new macro transformer by
specifying a sequence of hygienic rewrite rules.  A use of a macro whose
keyword is associated with a transformer specified by
@code{syntax-rules} is matched against the patterns contained in the
@var{syntax-rule}s, beginning with the leftmost @var{syntax-rule}.
When a match is found, the macro use is trancribed hygienically
according to the template.

Each pattern begins with the keyword for the macro.  This keyword is not
involved in the matching and is not considered a pattern variable or
literal identifier.
@end defmac

@node Macros That Work, Syntactic Closures, Macro by Example, Scheme Syntax Extension Packages
@section Macros That Work

@code{(require 'macros-that-work)}
@ftindex macros-that-work

@cite{Macros That Work} differs from the other R4RS macro
implementations in that it does not expand derived expression types to
primitive expression types.

@defun macro:expand expression
@defunx macwork:expand expression
Takes an R4RS expression, macro-expands it, and returns the result of
the macro expansion.
@end defun

@defun macro:eval expression
@defunx macwork:eval expression
@code{macro:eval} returns the value of @var{expression} in the current
top level environment.  @var{expression} can contain macro definitions.
Side effects of @var{expression} will affect the top level
environment.
@end defun

@deffn {Procedure} macro:load filename
@deffnx {Procedure} macwork:load filename
@var{filename} should be a string.  If filename names an existing file,
the @code{macro:load} procedure reads Scheme source code expressions and
definitions from the file and evaluates them sequentially.  These source
code expressions and definitions may contain macro definitions.  The
@code{macro:load} procedure does not affect the values returned by
@code{current-input-port} and @code{current-output-port}.
@end deffn

References:

The @cite{Revised^4 Report on the Algorithmic Language Scheme} Clinger
and Rees [editors].  To appear in LISP Pointers.  Also available as a
technical report from the University of Oregon, MIT AI Lab, and
Cornell.

@center Macros That Work.  Clinger and Rees.  POPL '91.

The supported syntax differs from the R4RS in that vectors are allowed
as patterns and as templates and are not allowed as pattern or template
data.

@example
transformer spec  @expansion{}  (syntax-rules literals rules)

rules  @expansion{}  ()
         |  (rule . rules)

rule  @expansion{}  (pattern template)

pattern  @expansion{}  pattern_var      ; a symbol not in literals
           |  symbol           ; a symbol in literals
           |  ()
           |  (pattern . pattern)
           |  (ellipsis_pattern)
           |  #(pattern*)                     ; extends R4RS
           |  #(pattern* ellipsis_pattern)    ; extends R4RS
           |  pattern_datum

template  @expansion{}  pattern_var
            |  symbol
            |  ()
            |  (template2 . template2)
            |  #(template*)                   ; extends R4RS
            |  pattern_datum

template2  @expansion{}  template
             |  ellipsis_template

pattern_datum  @expansion{}  string                    ; no vector
                 |  character
                 |  boolean
                 |  number

ellipsis_pattern  @expansion{} pattern ...

ellipsis_template  @expansion{}  template ...

pattern_var  @expansion{}  symbol   ; not in literals

literals  @expansion{}  ()
            |  (symbol . literals)
@end example

@subsection Definitions

@table @asis

@item Scope of an ellipsis
Within a pattern or template, the scope of an ellipsis (@code{...}) is
the pattern or template that appears to its left.

@item Rank of a pattern variable
The rank of a pattern variable is the number of ellipses within whose
scope it appears in the pattern.

@item Rank of a subtemplate
The rank of a subtemplate is the number of ellipses within whose scope
it appears in the template.

@item Template rank of an occurrence of a pattern variable
The template rank of an occurrence of a pattern variable within a
template is the rank of that occurrence, viewed as a subtemplate.

@item Variables bound by a pattern
The variables bound by a pattern are the pattern variables that appear
within it.

@item Referenced variables of a subtemplate
The referenced variables of a subtemplate are the pattern variables that
appear within it.

@item Variables opened by an ellipsis template
The variables opened by an ellipsis template are the referenced pattern
variables whose rank is greater than the rank of the ellipsis template.

@end table

@subsection Restrictions

No pattern variable appears more than once within a pattern.

For every occurrence of a pattern variable within a template, the
template rank of the occurrence must be greater than or equal to the
pattern variable's rank.

Every ellipsis template must open at least one variable.

For every ellipsis template, the variables opened by an ellipsis
template must all be bound to sequences of the same length.

The compiled form of a @var{rule} is

@example
rule  @expansion{}  (pattern template inserted)

pattern  @expansion{}  pattern_var
           |  symbol
           |  ()
           |  (pattern . pattern)
           |  ellipsis_pattern
           |  #(pattern)
           |  pattern_datum

template  @expansion{}  pattern_var
            |  symbol
            |  ()
            |  (template2 . template2)
            |  #(pattern)
            |  pattern_datum

template2  @expansion{}  template
             |  ellipsis_template

pattern_datum  @expansion{}  string
                 |  character
                 |  boolean
                 |  number

pattern_var  @expansion{}  #(V symbol rank)

ellipsis_pattern  @expansion{}  #(E pattern pattern_vars)

ellipsis_template  @expansion{}  #(E template pattern_vars)

inserted  @expansion{}  ()
            |  (symbol . inserted)

pattern_vars  @expansion{}  ()
                |  (pattern_var . pattern_vars)

rank  @expansion{}  exact non-negative integer
@end example

where V and E are unforgeable values.

The pattern variables associated with an ellipsis pattern are the
variables bound by the pattern, and the pattern variables associated
with an ellipsis template are the variables opened by the ellipsis
template.

If the template contains a big chunk that contains no pattern variables
or inserted identifiers, then the big chunk will be copied
unnecessarily.  That shouldn't matter very often.





@node Syntactic Closures, Syntax-Case Macros, Macros That Work, Scheme Syntax Extension Packages
@section Syntactic Closures

@code{(require 'syntactic-closures)}
@ftindex syntactic-closures

@defun macro:expand expression
@defunx synclo:expand expression
Returns scheme code with the macros and derived expression types of
@var{expression} expanded to primitive expression types.
@end defun

@defun macro:eval expression
@defunx synclo:eval expression
@code{macro:eval} returns the value of @var{expression} in the current
top level environment.  @var{expression} can contain macro definitions.
Side effects of @var{expression} will affect the top level
environment.
@end defun

@deffn {Procedure} macro:load filename
@deffnx {Procedure} synclo:load filename
@var{filename} should be a string.  If filename names an existing file,
the @code{macro:load} procedure reads Scheme source code expressions and
definitions from the file and evaluates them sequentially.  These
source code expressions and definitions may contain macro definitions.
The @code{macro:load} procedure does not affect the values returned by
@code{current-input-port} and @code{current-output-port}.
@end deffn

@subsection Syntactic Closure Macro Facility

@center A Syntactic Closures Macro Facility
@center by Chris Hanson
@center 9 November 1991

This document describes @dfn{syntactic closures}, a low-level macro
facility for the Scheme programming language.  The facility is an
alternative to the low-level macro facility described in the
@cite{Revised^4 Report on Scheme.} This document is an addendum to that
report.

The syntactic closures facility extends the BNF rule for
@var{transformer spec} to allow a new keyword that introduces a
low-level macro transformer:

@example
@var{transformer spec} := (transformer @var{expression})
@end example

Additionally, the following procedures are added:
@lisp
make-syntactic-closure
capture-syntactic-environment
identifier?
identifier=?
@end lisp

The description of the facility is divided into three parts.  The first
part defines basic terminology.  The second part describes how macro
transformers are defined.  The third part describes the use of
@dfn{identifiers}, which extend the syntactic closure mechanism to be
compatible with @code{syntax-rules}.

@subsubsection Terminology

This section defines the concepts and data types used by the syntactic
closures facility.

@itemize @bullet

@item @dfn{Forms} are the syntactic entities out of which programs are
recursively constructed.  A form is any expression, any definition, any
syntactic keyword, or any syntactic closure.  The variable name that
appears in a @code{set!} special form is also a form.  Examples of
forms:

@lisp
17
#t
car
(+ x 4)
(lambda (x) x)
(define pi 3.14159)
if
define
@end lisp

@item An @dfn{alias} is an alternate name for a given symbol.  It can
appear anywhere in a form that the symbol could be used, and when quoted
it is replaced by the symbol; however, it does not satisfy the predicate
@code{symbol?}.  Macro transformers rarely distinguish symbols from
aliases, referring to both as identifiers.

@item A @dfn{syntactic} environment maps identifiers to their
meanings.  More precisely, it determines whether an identifier is a
syntactic keyword or a variable.  If it is a keyword, the meaning is an
interpretation for the form in which that keyword appears.  If it is a
variable, the meaning identifies which binding of that variable is
referenced.  In short, syntactic environments contain all of the
contextual information necessary for interpreting the meaning of a
particular form.

@item A @dfn{syntactic closure} consists of a form, a syntactic
environment, and a list of identifiers.  All identifiers in the form
take their meaning from the syntactic environment, except those in the
given list.  The identifiers in the list are to have their meanings
determined later.  A syntactic closure may be used in any context in
which its form could have been used.  Since a syntactic closure is also
a form, it may not be used in contexts where a form would be illegal.
For example, a form may not appear as a clause in the cond special form.
A syntactic closure appearing in a quoted structure is replaced by its
form.

@end itemize

@subsubsection Transformer Definition

This section describes the @code{transformer} special form and the
procedures @code{make-syntactic-closure} and
@code{capture-syntactic-environment}.

@deffn Syntax transformer expression

Syntax: It is an error if this syntax occurs except as a
@var{transformer spec}.

Semantics: The @var{expression} is evaluated in the standard transformer
environment to yield a macro transformer as described below.  This macro
transformer is bound to a macro keyword by the special form in which the
@code{transformer} expression appears (for example,
@code{let-syntax}).

A @dfn{macro transformer} is a procedure that takes two arguments, a
form and a syntactic environment, and returns a new form.  The first
argument, the @dfn{input form}, is the form in which the macro keyword
occurred.  The second argument, the @dfn{usage environment}, is the
syntactic environment in which the input form occurred.  The result of
the transformer, the @dfn{output form}, is automatically closed in the
@dfn{transformer environment}, which is the syntactic environment in
which the @code{transformer} expression occurred.

For example, here is a definition of a push macro using
@code{syntax-rules}:

@lisp
(define-syntax  push
  (syntax-rules ()
    ((push item list)
     (set! list (cons item list)))))
@end lisp

Here is an equivalent definition using @code{transformer}:
@lisp
(define-syntax push
  (transformer
   (lambda (exp env)
     (let ((item
            (make-syntactic-closure env '() (cadr exp)))
           (list
            (make-syntactic-closure env '() (caddr exp))))
       `(set! ,list (cons ,item ,list))))))
@end lisp

In this example, the identifiers @code{set!} and @code{cons} are closed
in the transformer environment, and thus will not be affected by the
meanings of those identifiers in the usage environment
@code{env}.

Some macros may be non-hygienic by design.  For example, the following
defines a loop macro that implicitly binds @code{exit} to an escape
procedure.  The binding of @code{exit} is intended to capture free
references to @code{exit} in the body of the loop, so @code{exit} must
be left free when the body is closed:

@lisp
(define-syntax loop
  (transformer
   (lambda (exp env)
     (let ((body (cdr exp)))
       `(call-with-current-continuation
         (lambda (exit)
           (let f ()
             ,@@(map (lambda  (exp)
                       (make-syntactic-closure env '(exit)
                                               exp))
                     body)
             (f))))))))
@end lisp

To assign meanings to the identifiers in a form, use
@code{make-syntactic-closure} to close the form in a syntactic
environment.
@end deffn

@defun make-syntactic-closure environment free-names form

@var{environment} must be a syntactic environment, @var{free-names} must
be a list of identifiers, and @var{form} must be a form.
@code{make-syntactic-closure} constructs and returns a syntactic closure
of @var{form} in @var{environment}, which can be used anywhere that
@var{form} could have been used.  All the identifiers used in
@var{form}, except those explicitly excepted by @var{free-names}, obtain
their meanings from @var{environment}.

Here is an example where @var{free-names} is something other than the
empty list.  It is instructive to compare the use of @var{free-names} in
this example with its use in the @code{loop} example above: the examples
are similar except for the source of the identifier being left
free.
@lisp
(define-syntax let1
  (transformer
   (lambda (exp env)
     (let ((id (cadr exp))
           (init (caddr exp))
           (exp (cadddr exp)))
       `((lambda (,id)
           ,(make-syntactic-closure env (list id) exp))
         ,(make-syntactic-closure env '() init))))))
@end lisp

@code{let1} is a simplified version of @code{let} that only binds a
single identifier, and whose body consists of a single expression.  When
the body expression is syntactically closed in its original syntactic
environment, the identifier that is to be bound by @code{let1} must be
left free, so that it can be properly captured by the @code{lambda} in
the output form.

To obtain a syntactic environment other than the usage environment, use
@code{capture-syntactic-environment}.
@end defun

@defun capture-syntactic-environment procedure

@code{capture-syntactic-environment} returns a form that will, when
transformed, call @var{procedure} on the current syntactic environment.
@var{procedure} should compute and return a new form to be transformed,
in that same syntactic environment, in place of the form.

An example will make this clear.  Suppose we wanted to define a simple
@code{loop-until} keyword equivalent to

@lisp
(define-syntax loop-until
  (syntax-rules ()
    ((loop-until id init test return step)
     (letrec ((loop
               (lambda (id)
                 (if test return (loop step)))))
       (loop init)))))
@end lisp

The following attempt at defining @code{loop-until} has a subtle bug:
@lisp
(define-syntax loop-until
  (transformer
   (lambda (exp env)
     (let ((id (cadr exp))
           (init (caddr exp))
           (test (cadddr exp))
           (return (cadddr (cdr exp)))
           (step (cadddr (cddr exp)))
           (close
            (lambda (exp free)
              (make-syntactic-closure env free exp))))
       `(letrec ((loop
                  (lambda (,id)
                    (if ,(close test (list id))
                        ,(close return (list id))
                        (loop ,(close step (list id)))))))
          (loop ,(close init '())))))))
@end lisp

This definition appears to take all of the proper precautions to prevent
unintended captures.  It carefully closes the subexpressions in their
original syntactic environment and it leaves the @code{id} identifier
free in the @code{test}, @code{return}, and @code{step} expressions, so
that it will be captured by the binding introduced by the @code{lambda}
expression.  Unfortunately it uses the identifiers @code{if} and
@code{loop} within that @code{lambda} expression, so if the user of
@code{loop-until} just happens to use, say, @code{if} for the
identifier, it will be inadvertently captured.

The syntactic environment that @code{if} and @code{loop} want to be
exposed to is the one just outside the @code{lambda} expression: before
the user's identifier is added to the syntactic environment, but after
the identifier loop has been added.
@code{capture-syntactic-environment} captures exactly that environment
as follows:

@lisp
(define-syntax loop-until
  (transformer
   (lambda (exp env)
     (let ((id (cadr exp))
           (init (caddr exp))
           (test (cadddr exp))
           (return (cadddr (cdr exp)))
           (step (cadddr (cddr exp)))
           (close
            (lambda (exp free)
              (make-syntactic-closure env free exp))))
       `(letrec ((loop
                  ,(capture-syntactic-environment
                    (lambda (env)
                      `(lambda (,id)
                         (,(make-syntactic-closure env '() `if)
                          ,(close test (list id))
                          ,(close return (list id))
                          (,(make-syntactic-closure env '()
                                                    `loop)
                           ,(close step (list id)))))))))
          (loop ,(close init '())))))))
@end lisp

In this case, having captured the desired syntactic environment, it is
convenient to construct syntactic closures of the identifiers @code{if}
and the @code{loop} and use them in the body of the
@code{lambda}.

A common use of @code{capture-syntactic-environment} is to get the
transformer environment of a macro transformer:

@lisp
(transformer
 (lambda (exp env)
   (capture-syntactic-environment
    (lambda (transformer-env)
      ...))))
@end lisp
@end defun

@subsubsection Identifiers

This section describes the procedures that create and manipulate
identifiers.  Previous syntactic closure proposals did not have an
identifier data type -- they just used symbols.  The identifier data
type extends the syntactic closures facility to be compatible with the
high-level @code{syntax-rules} facility.

As discussed earlier, an identifier is either a symbol or an
@dfn{alias}.  An alias is implemented as a syntactic closure whose
@dfn{form} is an identifier:

@lisp
(make-syntactic-closure env '() 'a)
   @result{} an @dfn{alias}
@end lisp

Aliases are implemented as syntactic closures because they behave just
like syntactic closures most of the time.  The difference is that an
alias may be bound to a new value (for example by @code{lambda} or
@code{let-syntax}); other syntactic closures may not be used this way.
If an alias is bound, then within the scope of that binding it is looked
up in the syntactic environment just like any other identifier.

Aliases are used in the implementation of the high-level facility
@code{syntax-rules}.  A macro transformer created by @code{syntax-rules}
uses a template to generate its output form, substituting subforms of
the input form into the template.  In a syntactic closures
implementation, all of the symbols in the template are replaced by
aliases closed in the transformer environment, while the output form
itself is closed in the usage environment.  This guarantees that the
macro transformation is hygienic, without requiring the transformer to
know the syntactic roles of the substituted input subforms.

@defun identifier?  object
Returns @code{#t} if @var{object} is an identifier, otherwise returns
@code{#f}.  Examples:

@lisp
(identifier? 'a)
   @result{} #t
(identifier? (make-syntactic-closure env '() 'a))
   @result{} #t
(identifier? "a")
   @result{} #f
(identifier? #\a)
   @result{} #f
(identifier? 97)
   @result{} #f
(identifier? #f)
   @result{} #f
(identifier? '(a))
   @result{} #f
(identifier? '#(a))
   @result{} #f
@end lisp

The predicate @code{eq?} is used to determine if two identifers are
``the same''.  Thus @code{eq?} can be used to compare identifiers
exactly as it would be used to compare symbols.  Often, though, it is
useful to know whether two identifiers ``mean the same thing''.  For
example, the @code{cond} macro uses the symbol @code{else} to identify
the final clause in the conditional.  A macro transformer for
@code{cond} cannot just look for the symbol @code{else}, because the
@code{cond} form might be the output of another macro transformer that
replaced the symbol @code{else} with an alias.  Instead the transformer
must look for an identifier that ``means the same thing'' in the usage
environment as the symbol @code{else} means in the transformer
environment.
@end defun

@defun identifier=? environment1 identifier1 environment2 identifier2
@var{environment1} and @var{environment2} must be syntactic
environments, and @var{identifier1} and @var{identifier2} must be
identifiers.  @code{identifier=?} returns @code{#t} if the meaning of
@var{identifier1} in @var{environment1} is the same as that of
@var{identifier2} in @var{environment2}, otherwise it returns @code{#f}.
Examples:

@lisp
(let-syntax
    ((foo
      (transformer
       (lambda (form env)
         (capture-syntactic-environment
          (lambda (transformer-env)
            (identifier=? transformer-env 'x env 'x)))))))
  (list (foo)
        (let ((x 3))
          (foo))))
   @result{} (#t #f)
@end lisp

@lisp
(let-syntax ((bar foo))
  (let-syntax
      ((foo
        (transformer
         (lambda (form env)
           (capture-syntactic-environment
            (lambda (transformer-env)
              (identifier=? transformer-env 'foo
                            env (cadr form))))))))
    (list (foo foo)
          (foobar))))
   @result{} (#f #t)
@end lisp
@end defun

@subsubsection Acknowledgements

The syntactic closures facility was invented by Alan Bawden and Jonathan
Rees.  The use of aliases to implement @code{syntax-rules} was invented
by Alan Bawden (who prefers to call them @dfn{synthetic names}).  Much
of this proposal is derived from an earlier proposal by Alan
Bawden.





@node Syntax-Case Macros, Define-Structure, Syntactic Closures, Scheme Syntax Extension Packages
@section Syntax-Case Macros

@code{(require 'syntax-case)}
@ftindex syntax-case

@defun macro:expand expression
@defunx syncase:expand expression
Returns scheme code with the macros and derived expression types of
@var{expression} expanded to primitive expression types.
@end defun

@defun macro:eval expression
@defunx syncase:eval expression
@code{macro:eval} returns the value of @var{expression} in the current
top level environment.  @var{expression} can contain macro definitions.
Side effects of @var{expression} will affect the top level
environment.
@end defun

@deffn {Procedure} macro:load filename
@deffnx {Procedure} syncase:load filename
@var{filename} should be a string.  If filename names an existing file,
the @code{macro:load} procedure reads Scheme source code expressions and
definitions from the file and evaluates them sequentially.  These
source code expressions and definitions may contain macro definitions.
The @code{macro:load} procedure does not affect the values returned by
@code{current-input-port} and @code{current-output-port}.
@end deffn

This is version 2.1 of @code{syntax-case}, the low-level macro facility
proposed and implemented by Robert Hieb and R. Kent Dybvig.

This version is further adapted by Harald Hanche-Olsen
<hanche @@ imf.unit.no> to make it compatible with, and easily usable
with, SLIB.  Mainly, these adaptations consisted of:

@itemize @bullet
@item
Removing white space from @file{expand.pp} to save space in the
distribution.  This file is not meant for human readers anyway@dots{}

@item
Removed a couple of Chez scheme dependencies.

@item
Renamed global variables used to minimize the possibility of name
conflicts.

@item
Adding an SLIB-specific initialization file.

@item
Removing a couple extra files, most notably the documentation (but see
below).
@end itemize

If you wish, you can see exactly what changes were done by reading the
shell script in the file @file{syncase.sh}.

The two PostScript files were omitted in order to not burden the SLIB
distribution with them.  If you do intend to use @code{syntax-case},
however, you should get these files and print them out on a PostScript
printer.  They are available with the original @code{syntax-case}
distribution by anonymous FTP in
@file{cs.indiana.edu:/pub/scheme/syntax-case}.

In order to use syntax-case from an interactive top level, execute:
@lisp
(require 'syntax-case)
@ftindex syntax-case
(require 'repl)
@ftindex repl
(repl:top-level macro:eval)
@end lisp
See the section Repl (@pxref{Repl}) for more information.

To check operation of syntax-case get
@file{cs.indiana.edu:/pub/scheme/syntax-case}, and type
@lisp
(require 'syntax-case)
@ftindex syntax-case
@findex syncase:sanity-check
(syncase:sanity-check)
@end lisp

Beware that @code{syntax-case} takes a long time to load -- about 20s on
a SPARCstation SLC (with SCM) and about 90s on a Macintosh SE/30 (with
Gambit).

@subsection Notes

All R4RS syntactic forms are defined, including @code{delay}.  Along
with @code{delay} are simple definitions for @code{make-promise} (into
which @code{delay} expressions expand) and @code{force}.

@code{syntax-rules} and @code{with-syntax} (described in @cite{TR356})
are defined.

@code{syntax-case} is actually defined as a macro that expands into
calls to the procedure @code{syntax-dispatch} and the core form
@code{syntax-lambda}; do not redefine these names.

Several other top-level bindings not documented in TR356 are created:
@itemize @bullet
@item the ``hooks'' in @file{hooks.ss}
@item the @code{build-} procedures in @file{output.ss}
@item @code{expand-syntax} (the expander)
@end itemize

The syntax of define has been extended to allow @code{(define @var{id})},
which assigns @var{id} to some unspecified value.

We have attempted to maintain R4RS compatibility where possible.  The
incompatibilities should be confined to @file{hooks.ss}.  Please let us
know if there is some incompatibility that is not flagged as such.

Send bug reports, comments, suggestions, and questions to Kent Dybvig
(dyb @@ iuvax.cs.indiana.edu).



@node Define-Structure, Define-Record-Type, Syntax-Case Macros, Scheme Syntax Extension Packages
@section Define-Structure

@code{(require 'structure)}

@noindent
Included with the @code{syntax-case} files was @file{structure.scm}
which defines a macro @code{define-structure}.  Here is its
documentation from Gambit 4.0:

@deffn {special form} define-structure @var{name} @var{field}@dots{}

Record data types similar to Pascal records and C @code{struct}
types can be defined using the @code{define-structure} special form.
The identifier @var{name} specifies the name of the new data type.  The
structure name is followed by @var{k} identifiers naming each field of
the record.  The @code{define-structure} expands into a set of definitions
of the following procedures:

@itemize @bullet{}

@item
`@t{make-}@var{name}' -- A @var{k} argument procedure which constructs
a new record from the value of its @var{k} fields.

@item
`@var{name}@t{?}' -- A procedure which tests if its single argument
is of the given record type.

@item
`@var{name}@t{-}@var{field}' -- For each field, a procedure taking
as its single argument a value of the given record type and returning
the content of the corresponding field of the record.

@item
`@var{name}@t{-}@var{field}@t{-set!}' -- For each field, a two
argument procedure taking as its first argument a value of the given
record type.  The second argument gets assigned to the corresponding
field of the record and the void object is returned.

@end itemize

Gambit record data types have a printed representation that includes
the name of the type and the name and value of each field.

For example:

@smallexample
> @b{(define-structure point x y color)}
> @b{(define p (make-point 3 5 'red))}
> @b{p}
#<point #3 x: 3 y: 5 color: red>
> @b{(point-x p)}
3
> @b{(point-color p)}
red
> @b{(point-color-set! p 'black)}
> @b{p}
#<point #3 x: 3 y: 5 color: black>
@end smallexample

@end deffn

@node Define-Record-Type, Fluid-Let, Define-Structure, Scheme Syntax Extension Packages
@section Define-Record-Type

@code{(require 'define-record-type)} or @code{(require 'srfi-9)}
@ftindex srfi-9
@ftindex define-record-type

@url{http://srfi.schemers.org/srfi-9/srfi-9.html}

@defspec define-record-type <type-name> (<constructor-name> <field-tag> ...) <predicate-name> <field-spec> ...

Where
@lisp
<field-spec> @equiv{} (<field-tag> <accessor-name>)
             @equiv{} (<field-tag> <accessor-name> <modifier-name>)

@end lisp

@code{define-record-type} is a syntax wrapper for the SLIB
@code{record} module.
@end defspec


@node Fluid-Let, Binding to multiple values, Define-Record-Type, Scheme Syntax Extension Packages
@section Fluid-Let

@code{(require 'fluid-let)}
@ftindex fluid-let

@deffn Syntax fluid-let @code{(@var{bindings} @dots{})} @var{forms}@dots{}
@end deffn
@lisp
(fluid-let ((@var{variable} @var{init}) @dots{})
   @var{expression} @var{expression} @dots{})
@end lisp

The @var{init}s are evaluated in the current environment (in some
unspecified order), the current values of the @var{variable}s are saved,
the results are assigned to the @var{variable}s, the @var{expression}s
are evaluated sequentially in the current environment, the
@var{variable}s are restored to their original values, and the value of
the last @var{expression} is returned.

The syntax of this special form is similar to that of @code{let}, but
@code{fluid-let} temporarily rebinds existing @var{variable}s.  Unlike
@code{let}, @code{fluid-let} creates no new bindings; instead it
@emph{assigns} the values of each @var{init} to the binding (determined
by the rules of lexical scoping) of its corresponding
@var{variable}.


@node Binding to multiple values, Guarded LET* special form, Fluid-Let, Scheme Syntax Extension Packages
@section Binding to multiple values

@code{(require 'receive)} or @code{(require 'srfi-8)}
@ftindex srfi-8
@ftindex receive

@defspec receive formals expression body @dots{}

@url{http://srfi.schemers.org/srfi-8/srfi-8.html}
@end defspec



@node Guarded LET* special form, Guarded COND Clause, Binding to multiple values, Scheme Syntax Extension Packages
@section Guarded LET* special form

@code{(require 'and-let*)} or @code{(require 'srfi-2)}
@ftindex srfi-2
@ftindex and-let*

@defmac and-let* claws body @dots{}

@url{http://srfi.schemers.org/srfi-2/srfi-2.html}
@end defmac


@node Guarded COND Clause, Yasos, Guarded LET* special form, Scheme Syntax Extension Packages
@section Guarded COND Clause

@code{(require 'guarded-cond-clause)} or @code{(require 'srfi-61)}
@ftindex srfi-61
@ftindex guarded-cond-clause

@url{http://srfi.schemers.org/srfi-61/srfi-61.html}

@deffn {library syntax} cond  <clause1> <clause2> @dots{}

@emph{Syntax:}
Each @r{<clause>} should be of the form

@format
@t{(@r{<test>} @r{<expression1>} @dots{})
}
@end format

where @r{<test>} is any expression.  Alternatively, a @r{<clause>} may be
of the form

@format
@t{(@r{<test>} => @r{<expression>})
}
@end format

The @r{<clause>} production in the formal syntax of Scheme as
written by R5RS in section 7.1.3 is extended with a new option:
@cindex @w{=>}

@format
@t{@r{<clause>} => (@r{<generator>} @r{<guard>} => @r{<receiver>})
}
@end format

where @r{<generator>}, @r{<guard>}, & @r{<receiver>} are all
@r{<expression>}s.

@quotation
Clauses of this form have the following semantics: @r{<generator>} is
evaluated.  It may return arbitrarily many values.  @r{<Guard>} is
applied to an argument list containing the values in order that
@r{<generator>} returned.  If @r{<guard>} returns a true value for
that argument list, @r{<receiver>} is applied with an equivalent
argument list.  If @r{<guard>} returns a false value, however, the
clause is abandoned and the next one is tried.
@end quotation

The last @r{<clause>} may be
an ``else clause,'' which has the form

@format
@t{(else @r{<expression1>} @r{<expression2>} @dots{})@r{.}
}
@end format
@end deffn

@noindent
This @code{port->char-list} procedure accepts an input port and
returns a list of all the characters it produces until the end.

@example
(define (port->char-list port)
  (cond ((read-char port) char?
         => (lambda (c) (cons c (port->char-list port))))
        (else '())))

(call-with-input-string "foo" port->char-list)  ==>  (#\f #\o #\o)
@end example



@node Yasos,  , Guarded COND Clause, Scheme Syntax Extension Packages
@section Yasos

@c Much of the documentation in this section was written by Dave Love
@c (d.love@dl.ac.uk) -- don't blame Ken Dickey for its faults.
@c but we can blame him for not writing it!

@code{(require 'oop)} or @code{(require 'yasos)}
@ftindex oop
@ftindex yasos

`Yet Another Scheme Object System' is a simple object system for Scheme
based on the paper by Norman Adams and Jonathan Rees: @cite{Object
Oriented Programming in Scheme}, Proceedings of the 1988 ACM Conference
on LISP and Functional Programming, July 1988 [ACM #552880].

Another reference is:

Ken Dickey.
@ifset html
<A HREF="ftp://ftp.cs.indiana.edu/pub/scheme-repository/doc/pubs/swob.txt">
@end ifset
Scheming with Objects
@ifset html
</A>
@end ifset
@cite{AI Expert} Volume 7, Number 10 (October 1992), pp. 24-33.

@menu
* Yasos terms::                 Definitions and disclaimer.
* Yasos interface::             The Yasos macros and procedures.
* Setters::                     Dylan-like setters in Yasos.
* Yasos examples::              Usage of Yasos and setters.
@end menu

@node Yasos terms, Yasos interface, Yasos, Yasos
@subsection Terms

@table @asis
@item @dfn{Object}
Any Scheme data object.

@item @dfn{Instance}
An instance of the OO system; an @dfn{object}.

@item @dfn{Operation}
A @var{method}.
@end table

@table @emph
@item Notes:
The object system supports multiple inheritance.  An instance can
inherit from 0 or more ancestors.  In the case of multiple inherited
operations with the same identity, the operation used is that from the
first ancestor which contains it (in the ancestor @code{let}).  An
operation may be applied to any Scheme data object---not just instances.
As code which creates instances is just code, there are no @dfn{classes}
and no meta-@var{anything}.  Method dispatch is by a procedure call a la
CLOS rather than by @code{send} syntax a la Smalltalk.

@item Disclaimer:
There are a number of optimizations which can be made.  This
implementation is expository (although performance should be quite
reasonable).  See the L&FP paper for some suggestions.
@end table





@node Yasos interface, Setters, Yasos terms, Yasos
@subsection Interface

@deffn Syntax define-operation @code{(}opname self arg @dots{}@code{)} @var{default-body}
Defines a default behavior for data objects which don't handle the
operation @var{opname}.  The default behavior (for an empty
@var{default-body}) is to generate an error.
@end deffn

@deffn Syntax define-predicate opname?
Defines a predicate @var{opname?}, usually used for determining the
@dfn{type} of an object, such that @code{(@var{opname?} @var{object})}
returns @code{#t} if @var{object} has an operation @var{opname?} and
@code{#f} otherwise.
@end deffn

@deffn Syntax object @code{((@var{name} @var{self} @var{arg} @dots{}) @var{body})} @dots{}
Returns an object (an instance of the object system) with operations.
Invoking @code{(@var{name} @var{object} @var{arg} @dots{}} executes the
@var{body} of the @var{object} with @var{self} bound to @var{object} and
with argument(s) @var{arg}@dots{}.
@end deffn

@deffn Syntax object-with-ancestors @code{((}ancestor1 init1@code{)} @dots{}@code{)} operation @dots{}
A @code{let}-like form of @code{object} for multiple inheritance.  It
returns an object inheriting the behaviour of @var{ancestor1} etc.  An
operation will be invoked in an ancestor if the object itself does not
provide such a method.  In the case of multiple inherited operations
with the same identity, the operation used is the one found in the first
ancestor in the ancestor list.
@end deffn

@deffn Syntax operate-as component operation self arg @dots{}
Used in an operation definition (of @var{self}) to invoke the
@var{operation} in an ancestor @var{component} but maintain the object's
identity.  Also known as ``send-to-super''.
@end deffn

@deffn {Procedure} print obj port
A default @code{print} operation is provided which is just @code{(format
@var{port} @var{obj})} (@pxref{Format}) for non-instances and prints
@var{obj} preceded by @samp{#<INSTANCE>} for instances.
@end deffn

@defun size obj
The default method returns the number of elements in @var{obj} if it is
a vector, string or list, @code{2} for a pair, @code{1} for a character
and by default id an error otherwise.  Objects such as collections
(@pxref{Collections}) may override the default in an obvious way.
@end defun





@node Setters, Yasos examples, Yasos interface, Yasos
@subsection Setters

@dfn{Setters} implement @dfn{generalized locations} for objects
associated with some sort of mutable state.  A @dfn{getter} operation
retrieves a value from a generalized location and the corresponding
setter operation stores a value into the location.  Only the getter is
named -- the setter is specified by a procedure call as below.  (Dylan
uses special syntax.)  Typically, but not necessarily, getters are
access operations to extract values from Yasos objects (@pxref{Yasos}).
Several setters are predefined, corresponding to getters @code{car},
@code{cdr}, @code{string-ref} and @code{vector-ref} e.g., @code{(setter
car)} is equivalent to @code{set-car!}.

This implementation of setters is similar to that in Dylan(TM)
(@cite{Dylan: An object-oriented dynamic language}, Apple Computer
Eastern Research and Technology).  Common LISP provides similar
facilities through @code{setf}.

@defun setter getter
Returns the setter for the procedure @var{getter}.  E.g., since
@code{string-ref} is the getter corresponding to a setter which is
actually @code{string-set!}:
@example
(define foo "foo")
((setter string-ref) foo 0 #\F) ; set element 0 of foo
foo @result{} "Foo"
@end example
@end defun

@deffn Syntax set place new-value
If @var{place} is a variable name, @code{set} is equivalent to
@code{set!}.  Otherwise, @var{place} must have the form of a procedure
call, where the procedure name refers to a getter and the call indicates
an accessible generalized location, i.e., the call would return a value.
The return value of @code{set} is usually unspecified unless used with a
setter whose definition guarantees to return a useful value.
@example
(set (string-ref foo 2) #\O)  ; generalized location with getter
foo @result{} "FoO"
(set foo "foo")               ; like set!
foo @result{} "foo"
@end example
@end deffn

@deffn {Procedure} add-setter getter setter
Add procedures @var{getter} and @var{setter} to the (inaccessible) list
of valid setter/getter pairs.  @var{setter} implements the store
operation corresponding to the @var{getter} access operation for the
relevant state.  The return value is unspecified.
@end deffn

@deffn {Procedure} remove-setter-for getter
Removes the setter corresponding to the specified @var{getter} from the
list of valid setters.  The return value is unspecified.
@end deffn

@deffn Syntax define-access-operation getter-name
Shorthand for a Yasos @code{define-operation} defining an operation
@var{getter-name} that objects may support to return the value of some
mutable state.  The default operation is to signal an error.  The return
value is unspecified.
@end deffn





@node Yasos examples,  , Setters, Yasos
@subsection Examples

@lisp
;;; These definitions for PRINT and SIZE are
;;; already supplied by
(require 'yasos)

(define-operation (print obj port)
  (format port
          (if (instance? obj) "#<instance>" "~s")
          obj))

(define-operation (size obj)
  (cond
   ((vector? obj) (vector-length obj))
   ((list?   obj) (length obj))
   ((pair?   obj) 2)
   ((string? obj) (string-length obj))
   ((char?   obj) 1)
   (else
    (slib:error "Operation not supported: size" obj))))

(define-predicate cell?)
(define-operation (fetch obj))
(define-operation (store! obj newValue))

(define (make-cell value)
  (object
   ((cell? self) #t)
   ((fetch self) value)
   ((store! self newValue)
    (set! value newValue)
    newValue)
   ((size self) 1)
   ((print self port)
    (format port "#<Cell: ~s>" (fetch self)))))

(define-operation (discard obj value)
  (format #t "Discarding ~s~%" value))

(define (make-filtered-cell value filter)
  (object-with-ancestors
   ((cell (make-cell value)))
   ((store! self newValue)
   (if (filter newValue)
       (store! cell newValue)
       (discard self newValue)))))

(define-predicate array?)
(define-operation (array-ref array index))
(define-operation (array-set! array index value))

(define (make-array num-slots)
  (let ((anArray (make-vector num-slots)))
    (object
     ((array? self) #t)
     ((size self) num-slots)
     ((array-ref self index)
      (vector-ref  anArray index))
     ((array-set! self index newValue)
      (vector-set! anArray index newValue))
     ((print self port)
      (format port "#<Array ~s>" (size self))))))

(define-operation (position obj))
(define-operation (discarded-value obj))

(define (make-cell-with-history value filter size)
  (let ((pos 0) (most-recent-discard #f))
    (object-with-ancestors
     ((cell (make-filtered-call value filter))
      (sequence (make-array size)))
     ((array? self) #f)
     ((position self) pos)
     ((store! self newValue)
      (operate-as cell store! self newValue)
      (array-set! self pos newValue)
      (set! pos (+ pos 1)))
     ((discard self value)
      (set! most-recent-discard value))
     ((discarded-value self) most-recent-discard)
     ((print self port)
      (format port "#<Cell-with-history ~s>"
              (fetch self))))))

(define-access-operation fetch)
(add-setter fetch store!)
(define foo (make-cell 1))
(print foo #f)
@result{} "#<Cell: 1>"
(set (fetch foo) 2)
@result{}
(print foo #f)
@result{} "#<Cell: 2>"
(fetch foo)
@result{} 2
@end lisp



@node Textual Conversion Packages, Mathematical Packages, Scheme Syntax Extension Packages, Top
@chapter Textual Conversion Packages

@menu
* Precedence Parsing::          
* Format::                      Common-Lisp Format
* Standard Formatted I/O::      Posix printf and scanf
* Programs and Arguments::      
* HTML::                        Generating
* HTML Tables::                 Databases meet HTML
* HTTP and CGI::                Serve WWW sites
* Parsing HTML::                'html-for-each
* URI::                         Uniform Resource Identifier
* Printing Scheme::             Nicely
* Time and Date::               
* NCBI-DNA::                    DNA and protein sequences
* Schmooz::                     Documentation markup for Scheme programs
@end menu


@node Precedence Parsing, Format, Textual Conversion Packages, Textual Conversion Packages
@section Precedence Parsing

@code{(require 'precedence-parse)} or @code{(require 'parse)}
@ftindex parse
@ftindex precedence

@noindent
This package implements:

@itemize @bullet
@item
a Pratt style precedence parser;
@item
a @dfn{tokenizer} which congeals tokens according to assigned classes of
constituent characters;
@item
procedures giving direct control of parser rulesets;
@item
procedures for higher level specification of rulesets.
@end itemize

@menu
* Precedence Parsing Overview::  
* Rule Types::                  
* Ruleset Definition and Use::  
* Token definition::            
* Nud and Led Definition::      
* Grammar Rule Definition::     
@end menu

@node Precedence Parsing Overview, Rule Types, Precedence Parsing, Precedence Parsing
@subsection Precedence Parsing Overview

@noindent
This package offers improvements over previous parsers.

@itemize @bullet
@item
Common computer language constructs are concisely specified.
@item
Grammars can be changed dynamically.  Operators can be assigned
different meanings within a lexical context.
@item
Rulesets don't need compilation.  Grammars can be changed incrementally.
@item
Operator precedence is specified by integers.
@item
All possibilities of bad input are handled @footnote{How do I know this?
I parsed 250kbyte of random input (an e-mail file) with a non-trivial
grammar utilizing all constructs.} and return as much structure as was
parsed when the error occured; The symbol @code{?} is substituted for
missing input.
@end itemize

@noindent
@cindex binding power
The notion of @dfn{binding power} may be unfamiliar to those
accustomed to BNF grammars.

@noindent
When two consecutive objects are parsed, the first might be the prefix
to the second, or the second might be a suffix of the first.
Comparing the left and right binding powers of the two objects decides
which way to interpret them.

@noindent
Objects at each level of syntactic grouping have binding powers.

@noindent
@cindex syntax tree
A syntax tree is not built unless the rules explicitly do so.  The
call graph of grammar rules effectively instantiate the sytnax tree.

@noindent
The JACAL symbolic math system
(@url{http://swiss.csail.mit.edu/~jaffer/JACAL}) uses
@t{precedence-parse}.  Its grammar definitions in the file
@file{jacal/English.scm} can serve as examples of use.


@node Rule Types, Ruleset Definition and Use, Precedence Parsing Overview, Precedence Parsing
@subsection Rule Types

@noindent
Here are the higher-level syntax types and an example of each.
Precedence considerations are omitted for clarity.  See @ref{Grammar
Rule Definition} for full details.
@deftp Grammar nofix bye exit
@example
bye
@end example
calls the function @code{exit} with no arguments.
@end deftp
@deftp Grammar prefix - negate
@example
- 42
@end example
Calls the function @code{negate} with the argument @code{42}.
@end deftp
@deftp Grammar infix - difference
@example
x - y
@end example
Calls the function @code{difference} with arguments @code{x} and @code{y}.
@end deftp
@deftp Grammar nary + sum
@example
x + y + z
@end example
Calls the function @code{sum} with arguments @code{x}, @code{y}, and
@code{y}.
@end deftp
@deftp Grammar postfix ! factorial
@example
5 !
@end example
Calls the function @code{factorial} with the argument @code{5}.
@end deftp
@deftp Grammar prestfix set set!
@example
set foo bar
@end example
Calls the function @code{set!} with the arguments @code{foo} and
@code{bar}.
@end deftp
@deftp Grammar commentfix /* */
@example
/* almost any text here */
@end example
Ignores the comment delimited by @code{/*} and @code{*/}.
@end deftp
@deftp Grammar matchfix @{ list @}
@example
@{0, 1, 2@}
@end example
Calls the function @code{list} with the arguments @code{0}, @code{1},
and @code{2}.
@end deftp
@deftp Grammar inmatchfix ( funcall )
@example
f(x, y)
@end example
Calls the function @code{funcall} with the arguments @code{f}, @code{x},
and @code{y}.
@end deftp
@deftp Grammar delim ;
@example
set foo bar;
@end example
delimits the extent of the restfix operator @code{set}.
@end deftp


@node Ruleset Definition and Use, Token definition, Rule Types, Precedence Parsing
@subsection Ruleset Definition and Use

@defvar *syn-defs*
A grammar is built by one or more calls to @code{prec:define-grammar}.
The rules are appended to @var{*syn-defs*}.  The value of
@var{*syn-defs*} is the grammar suitable for passing as an argument to
@code{prec:parse}.
@end defvar

@defvr Constant *syn-ignore-whitespace*
Is a nearly empty grammar with whitespace characters set to group 0,
which means they will not be made into tokens.  Most rulesets will want
to start with @code{*syn-ignore-whitespace*}
@end defvr

@noindent
In order to start defining a grammar, either

@example
(set! *syn-defs* '())
@end example
@noindent
or

@example
(set! *syn-defs* *syn-ignore-whitespace*)
@end example

@defun prec:define-grammar rule1 @dots{}
Appends @var{rule1} @dots{} to @var{*syn-defs*}.
@code{prec:define-grammar} is used to define both the character classes
and rules for tokens.
@end defun

@noindent
Once your grammar is defined, save the value of @code{*syn-defs*} in a
variable (for use when calling @code{prec:parse}).

@example
(define my-ruleset *syn-defs*)
@end example

@defun prec:parse ruleset delim
@defunx prec:parse ruleset delim port
The @var{ruleset} argument must be a list of rules as constructed by
@code{prec:define-grammar} and extracted from @var{*syn-defs*}.

The token @var{delim} may be a character, symbol, or string.  A
character @var{delim} argument will match only a character token;
i.e. a character for which no token-group is assigned.  A symbol or
string will match only a token string; i.e. a token resulting from a
token group.

@code{prec:parse} reads a @var{ruleset} grammar expression delimited
by @var{delim} from the given input @var{port}.  @code{prec:parse}
returns the next object parsable from the given input @var{port},
updating @var{port} to point to the first character past the end of the
external representation of the object.

If an end of file is encountered in the input before any characters are
found that can begin an object, then an end of file object is returned.
If a delimiter (such as @var{delim}) is found before any characters are
found that can begin an object, then @code{#f} is returned.

The @var{port} argument may be omitted, in which case it defaults to the
value returned by @code{current-input-port}.  It is an error to parse
from a closed port.
@findex current-input-port
@end defun

@node Token definition, Nud and Led Definition, Ruleset Definition and Use, Precedence Parsing
@subsection Token definition

@defun tok:char-group group chars chars-proc
The argument @var{chars} may be a single character, a list of
characters, or a string.  Each character in @var{chars} is treated as
though @code{tok:char-group} was called with that character alone.

The argument @var{chars-proc} must be a procedure of one argument, a
list of characters.  After @code{tokenize} has finished
accumulating the characters for a token, it calls @var{chars-proc} with
the list of characters.  The value returned is the token which
@code{tokenize} returns.

The argument @var{group} may be an exact integer or a procedure of one
character argument.  The following discussion concerns the treatment
which the tokenizing routine, @code{tokenize}, will accord to characters
on the basis of their groups.

When @var{group} is a non-zero integer, characters whose group number is
equal to or exactly one less than @var{group} will continue to
accumulate.  Any other character causes the accumulation to stop (until
a new token is to be read).

The @var{group} of zero is special.  These characters are ignored when
parsed pending a token, and stop the accumulation of token characters
when the accumulation has already begun.  Whitespace characters are
usually put in group 0.

If @var{group} is a procedure, then, when triggerd by the occurence of
an initial (no accumulation) @var{chars} character, this procedure will
be repeatedly called with each successive character from the input
stream until the @var{group} procedure returns a non-false value.
@end defun

@noindent
The following convenient constants are provided for use with
@code{tok:char-group}.

@defvr Constant tok:decimal-digits
Is the string @code{"0123456789"}.
@end defvr
@defvr Constant tok:upper-case
Is the string consisting of all upper-case letters
("ABCDEFGHIJKLMNOPQRSTUVWXYZ").
@end defvr
@defvr Constant tok:lower-case
Is the string consisting of all lower-case letters
("abcdefghijklmnopqrstuvwxyz").
@end defvr
@defvr Constant tok:whitespaces
Is the string consisting of all characters between 0 and 255 for which
@code{char-whitespace?} returns true.
@end defvr

@noindent
For the purpose of reporting problems in error messages, this package
keeps track of the @dfn{current column}.  When the column does not
simply track input characters, @code{tok:bump-column} can be used to
adjust the current-column.

@defun tok:bump-column pos port
Adds @var{pos} to the current-column for input-port @var{port}.
@end defun


@node Nud and Led Definition, Grammar Rule Definition, Token definition, Precedence Parsing
@subsection Nud and Led Definition

This section describes advanced features.  You can skip this section on
first reading.

@noindent
The @dfn{Null Denotation} (or @dfn{nud})
@cindex Null Denotation, nud
of a token is the procedure and arguments applying for that token when
@dfn{Left}, an unclaimed parsed expression is not extant.

@noindent
The @dfn{Left Denotation} (or @dfn{led})
@cindex Left Denotation, led
of a token is the procedure, arguments, and lbp applying for that token
when there is a @dfn{Left}, an unclaimed parsed expression.

@noindent
In his paper,

@quotation
Pratt, V. R.
Top Down Operator Precendence.
@cite{SIGACT/SIGPLAN Symposium on Principles of Programming Languages},
Boston, 1973, pages 41-51
@end quotation

the @dfn{left binding power} (or @dfn{lbp}) was an independent property
of tokens.  I think this was done in order to allow tokens with NUDs but
not LEDs to also be used as delimiters, which was a problem for
statically defined syntaxes.  It turns out that @emph{dynamically
binding} NUDs and LEDs allows them independence.

@noindent
For the rule-defining procedures that follow, the variable @var{tk} may
be a character, string, or symbol, or a list composed of characters,
strings, and symbols.  Each element of @var{tk} is treated as though the
procedure were called for each element.

@noindent
Character @var{tk} arguments will match only character tokens;
i.e. characters for which no token-group is assigned.  Symbols and
strings will both match token strings; i.e. tokens resulting from token
groups.

@defun prec:make-nud tk sop arg1 @dots{}
Returns a rule specifying that @var{sop} be called when @var{tk} is
parsed.  If @var{sop} is a procedure, it is called with @var{tk} and
@var{arg1} @dots{} as its arguments; the resulting value is incorporated
into the expression being built.  Otherwise, @code{(list @var{sop}
@var{arg1} @dots{})} is incorporated.
@end defun

@noindent
If no NUD has been defined for a token; then if that token is a string,
it is converted to a symbol and returned; if not a string, the token is
returned.

@defun prec:make-led tk sop arg1 @dots{}
Returns a rule specifying that @var{sop} be called when @var{tk} is
parsed and @var{left} has an unclaimed parsed expression.  If @var{sop}
is a procedure, it is called with @var{left}, @var{tk}, and @var{arg1}
@dots{} as its arguments; the resulting value is incorporated into the
expression being built.  Otherwise, @var{left} is incorporated.
@end defun

@noindent
If no LED has been defined for a token, and @var{left} is set, the
parser issues a warning.

@node Grammar Rule Definition,  , Nud and Led Definition, Precedence Parsing
@subsection Grammar Rule Definition

@noindent
Here are procedures for defining rules for the syntax types introduced
in @ref{Precedence Parsing Overview}.

@noindent
For the rule-defining procedures that follow, the variable @var{tk} may
be a character, string, or symbol, or a list composed of characters,
strings, and symbols.  Each element of @var{tk} is treated as though the
procedure were called for each element.

@noindent
For procedures prec:delim, @dots{}, prec:prestfix, if the @var{sop}
argument is @code{#f}, then the token which triggered this rule is
converted to a symbol and returned.  A false @var{sop} argument to the
procedures prec:commentfix, prec:matchfix, or prec:inmatchfix has a
different meaning.

@noindent
Character @var{tk} arguments will match only character tokens;
i.e. characters for which no token-group is assigned.  Symbols and
strings will both match token strings; i.e. tokens resulting from token
groups.

@defun prec:delim tk
Returns a rule specifying that @var{tk} should not be returned from
parsing; i.e. @var{tk}'s function is purely syntactic.  The end-of-file
is always treated as a delimiter.
@end defun

@defun prec:nofix tk sop
Returns a rule specifying the following actions take place when @var{tk}
is parsed:
@itemize @bullet
@item
If @var{sop} is a procedure, it is called with no arguments; the
resulting value is incorporated into the expression being built.
Otherwise, the list of @var{sop} is incorporated.
@end itemize
@end defun

@defun prec:prefix tk sop bp rule1 @dots{}
Returns a rule specifying the following actions take place when @var{tk}
is parsed:
@itemize @bullet
@item
The rules @var{rule1} @dots{} augment and, in case of conflict, override
rules currently in effect.
@item
@code{prec:parse1} is called with binding-power @var{bp}.
@item
If @var{sop} is a procedure, it is called with the expression returned
from @code{prec:parse1}; the resulting value is incorporated into the
expression being built.  Otherwise, the list of @var{sop} and the
expression returned from @code{prec:parse1} is incorporated.
@item
The ruleset in effect before @var{tk} was parsed is restored;
@var{rule1} @dots{} are forgotten.
@end itemize
@end defun

@defun prec:infix tk sop lbp bp rule1 @dots{}
Returns a rule declaring the left-binding-precedence of the token
@var{tk} is @var{lbp} and specifying the following actions take place
when @var{tk} is parsed:
@itemize @bullet
@item
The rules @var{rule1} @dots{} augment and, in case of conflict, override
rules currently in effect.
@item
One expression is parsed with binding-power @var{lbp}.  If instead a
delimiter is encountered, a warning is issued.
@item
If @var{sop} is a procedure, it is applied to the list of @var{left} and
the parsed expression; the resulting value is incorporated into the
expression being built.  Otherwise, the list of @var{sop}, the
@var{left} expression, and the parsed expression is incorporated.
@item
The ruleset in effect before @var{tk} was parsed is restored;
@var{rule1} @dots{} are forgotten.
@end itemize
@end defun

@defun prec:nary tk sop bp
Returns a rule declaring the left-binding-precedence of the token
@var{tk} is @var{bp} and specifying the following actions take place
when @var{tk} is parsed:
@itemize @bullet
@item
Expressions are parsed with binding-power @var{bp} as far as they are
interleaved with the token @var{tk}.
@item
If @var{sop} is a procedure, it is applied to the list of @var{left} and
the parsed expressions; the resulting value is incorporated into the
expression being built.  Otherwise, the list of @var{sop}, the
@var{left} expression, and the parsed expressions is incorporated.
@end itemize
@end defun

@defun prec:postfix tk sop lbp
Returns a rule declaring the left-binding-precedence of the token
@var{tk} is @var{lbp} and specifying the following actions take place
when @var{tk} is parsed:
@itemize @bullet
@item
If @var{sop} is a procedure, it is called with the @var{left} expression;
the resulting value is incorporated into the expression being built.
Otherwise, the list of @var{sop} and the @var{left} expression is
incorporated.
@end itemize
@end defun

@defun prec:prestfix tk sop bp rule1 @dots{}
Returns a rule specifying the following actions take place when @var{tk}
is parsed:
@itemize @bullet
@item
The rules @var{rule1} @dots{} augment and, in case of conflict, override
rules currently in effect.
@item
Expressions are parsed with binding-power @var{bp} until a delimiter is
reached.
@item
If @var{sop} is a procedure, it is applied to the list of parsed
expressions; the resulting value is incorporated into the expression
being built.  Otherwise, the list of @var{sop} and the parsed
expressions is incorporated.
@item
The ruleset in effect before @var{tk} was parsed is restored;
@var{rule1} @dots{} are forgotten.
@end itemize
@end defun

@defun prec:commentfix tk stp match rule1 @dots{}
Returns rules specifying the following actions take place when @var{tk}
is parsed:
@itemize @bullet
@item
The rules @var{rule1} @dots{} augment and, in case of conflict, override
rules currently in effect.
@item
Characters are read until and end-of-file or a sequence of characters
is read which matches the @emph{string} @var{match}.
@item
If @var{stp} is a procedure, it is called with the string of all that
was read between the @var{tk} and @var{match} (exclusive).
@item
The ruleset in effect before @var{tk} was parsed is restored;
@var{rule1} @dots{} are forgotten.
@end itemize

Parsing of commentfix syntax differs from the others in several ways.
It reads directly from input without tokenizing; It calls @var{stp} but
does not return its value; nay any value.  I added the @var{stp}
argument so that comment text could be echoed.
@end defun

@defun prec:matchfix tk sop sep match rule1 @dots{}
Returns a rule specifying the following actions take place when @var{tk}
is parsed:
@itemize @bullet
@item
The rules @var{rule1} @dots{} augment and, in case of conflict, override
rules currently in effect.
@item
A rule declaring the token @var{match} a delimiter takes effect.
@item
Expressions are parsed with binding-power @code{0} until the token
@var{match} is reached.  If the token @var{sep} does not appear between
each pair of expressions parsed, a warning is issued.
@item
If @var{sop} is a procedure, it is applied to the list of parsed
expressions; the resulting value is incorporated into the expression
being built.  Otherwise, the list of @var{sop} and the parsed
expressions is incorporated.
@item
The ruleset in effect before @var{tk} was parsed is restored;
@var{rule1} @dots{} are forgotten.
@end itemize
@end defun

@defun prec:inmatchfix tk sop sep match lbp rule1 @dots{}
Returns a rule declaring the left-binding-precedence of the token
@var{tk} is @var{lbp} and specifying the following actions take place
when @var{tk} is parsed:
@itemize @bullet
@item
The rules @var{rule1} @dots{} augment and, in case of conflict, override
rules currently in effect.
@item
A rule declaring the token @var{match} a delimiter takes effect.
@item
Expressions are parsed with binding-power @code{0} until the token
@var{match} is reached.  If the token @var{sep} does not appear between
each pair of expressions parsed, a warning is issued.
@item
If @var{sop} is a procedure, it is applied to the list of @var{left} and
the parsed expressions; the resulting value is incorporated into the
expression being built.  Otherwise, the list of @var{sop}, the
@var{left} expression, and the parsed expressions is incorporated.
@item
The ruleset in effect before @var{tk} was parsed is restored;
@var{rule1} @dots{} are forgotten.
@end itemize
@end defun


@node Format, Standard Formatted I/O, Precedence Parsing, Textual Conversion Packages
@section Format (version 3.1)

@ifset html
<A NAME="format"></A>
@end ifset
@code{(require 'format)}
@ftindex format

@c The @file{format.scm} package was removed because it was not
@c reentrant.  @url{http://swiss.csail.mit.edu/~jaffer/SLIB.FAQ} explains
@c more about FORMAT's woes.

@include format.texi



@node Standard Formatted I/O, Programs and Arguments, Format, Textual Conversion Packages
@section Standard Formatted I/O

@menu
* Standard Formatted Output::   'printf
* Standard Formatted Input::    'scanf
@end menu

@subsection stdio

@code{(require 'stdio)}
@ftindex stdio

@code{require}s @code{printf} and @code{scanf} and additionally defines
the symbols:

@defvar stdin
Defined to be @code{(current-input-port)}.
@end defvar
@defvar stdout
Defined to be @code{(current-output-port)}.
@end defvar
@defvar stderr
Defined to be @code{(current-error-port)}.
@end defvar


@node Standard Formatted Output, Standard Formatted Input, Standard Formatted I/O, Standard Formatted I/O
@subsection Standard Formatted Output

@ifset html
<A NAME="printf"></A>
@end ifset
@code{(require 'printf)}
@ftindex printf

@deffn {Procedure} printf format arg1 @dots{}
@deffnx {Procedure} fprintf port format arg1 @dots{}
@deffnx {Procedure} sprintf str format arg1 @dots{}
@deffnx {Procedure} sprintf #f format arg1 @dots{}
@deffnx {Procedure} sprintf k format arg1 @dots{}

Each function converts, formats, and outputs its @var{arg1} @dots{}
arguments according to the control string @var{format} argument and
returns the number of characters output.

@code{printf} sends its output to the port @code{(current-output-port)}.
@code{fprintf} sends its output to the port @var{port}.  @code{sprintf}
@code{string-set!}s locations of the non-constant string argument
@var{str} to the output characters.

Two extensions of @code{sprintf} return new strings.  If the first
argument is @code{#f}, then the returned string's length is as many
characters as specified by the @var{format} and data; if the first
argument is a non-negative integer @var{k}, then the length of the
returned string is also bounded by @var{k}.

The string @var{format} contains plain characters which are copied to
the output stream, and conversion specifications, each of which results
in fetching zero or more of the arguments @var{arg1} @dots{}.  The
results are undefined if there are an insufficient number of arguments
for the format.  If @var{format} is exhausted while some of the
@var{arg1} @dots{} arguments remain unused, the excess @var{arg1}
@dots{} arguments are ignored.

The conversion specifications in a format string have the form:

@example
% @r{[} @var{flags} @r{]} @r{[} @var{width} @r{]} @r{[} . @var{precision} @r{]} @r{[} @var{type} @r{]} @var{conversion}
@end example

An output conversion specifications consist of an initial @samp{%}
character followed in sequence by:

@itemize @bullet
@item
Zero or more @dfn{flag characters} that modify the normal behavior of
the conversion specification.

@table @asis
@item @samp{-}
Left-justify the result in the field.  Normally the result is
right-justified.

@item @samp{+}
For the signed @samp{%d} and @samp{%i} conversions and all inexact
conversions, prefix a plus sign if the value is positive.

@item @samp{ }
For the signed @samp{%d} and @samp{%i} conversions, if the result
doesn't start with a plus or minus sign, prefix it with a space
character instead.  Since the @samp{+} flag ensures that the result
includes a sign, this flag is ignored if both are specified.

@item @samp{#}
For inexact conversions, @samp{#} specifies that the result should
always include a decimal point, even if no digits follow it.  For the
@samp{%g} and @samp{%G} conversions, this also forces trailing zeros
after the decimal point to be printed where they would otherwise be
elided.

For the @samp{%o} conversion, force the leading digit to be @samp{0}, as
if by increasing the precision.  For @samp{%x} or @samp{%X}, prefix a
leading @samp{0x} or @samp{0X} (respectively) to the result.  This
doesn't do anything useful for the @samp{%d}, @samp{%i}, or @samp{%u}
conversions.  Using this flag produces output which can be parsed by the
@code{scanf} functions with the @samp{%i} conversion (@pxref{Standard
Formatted Input}).


@item @samp{0}
Pad the field with zeros instead of spaces.  The zeros are placed after
any indication of sign or base.  This flag is ignored if the @samp{-}
flag is also specified, or if a precision is specified for an exact
converson.
@end table

@item
An optional decimal integer specifying the @dfn{minimum field width}.
If the normal conversion produces fewer characters than this, the field
is padded (with spaces or zeros per the @samp{0} flag) to the specified
width.  This is a @emph{minimum} width; if the normal conversion
produces more characters than this, the field is @emph{not} truncated.
@cindex minimum field width (@code{printf})

Alternatively, if the field width is @samp{*}, the next argument in the
argument list (before the actual value to be printed) is used as the
field width.  The width value must be an integer.  If the value is
negative it is as though the @samp{-} flag is set (see above) and the
absolute value is used as the field width.

@item
An optional @dfn{precision} to specify the number of digits to be
written for numeric conversions and the maximum field width for string
conversions.  The precision is specified by a period (@samp{.}) followed
optionally by a decimal integer (which defaults to zero if omitted).
@cindex precision (@code{printf})

Alternatively, if the precision is @samp{.*}, the next argument in the
argument list (before the actual value to be printed) is used as the
precision.  The value must be an integer, and is ignored if negative.
If you specify @samp{*} for both the field width and precision, the
field width argument precedes the precision argument.  The @samp{.*}
precision is an enhancement.  C library versions may not accept this
syntax.

For the @samp{%f}, @samp{%e}, and @samp{%E} conversions, the precision
specifies how many digits follow the decimal-point character.  The
default precision is @code{6}.  If the precision is explicitly @code{0},
the decimal point character is suppressed.

For the @samp{%g} and @samp{%G} conversions, the precision specifies how
many significant digits to print.  Significant digits are the first
digit before the decimal point, and all the digits after it.  If the
precision is @code{0} or not specified for @samp{%g} or @samp{%G}, it is
treated like a value of @code{1}.  If the value being printed cannot be
expressed accurately in the specified number of digits, the value is
rounded to the nearest number that fits.

For exact conversions, if a precision is supplied it specifies the
minimum number of digits to appear; leading zeros are produced if
necessary.  If a precision is not supplied, the number is printed with
as many digits as necessary.  Converting an exact @samp{0} with an
explicit precision of zero produces no characters.

@item
An optional one of @samp{l}, @samp{h} or @samp{L}, which is ignored for
numeric conversions.  It is an error to specify these modifiers for
non-numeric conversions.

@item
A character that specifies the conversion to be applied.
@end itemize

@subsubsection Exact Conversions

@table @asis
@item @samp{b}, @samp{B}
Print an integer as an unsigned binary number.

@emph{Note:} @samp{%b} and @samp{%B} are SLIB extensions.


@item @samp{d}, @samp{i}
Print an integer as a signed decimal number.  @samp{%d} and @samp{%i}
are synonymous for output, but are different when used with @code{scanf}
for input (@pxref{Standard Formatted Input}).

@item @samp{o}
Print an integer as an unsigned octal number.

@item @samp{u}
Print an integer as an unsigned decimal number.

@item @samp{x}, @samp{X}
Print an integer as an unsigned hexadecimal number.  @samp{%x} prints
using the digits @samp{0123456789abcdef}.  @samp{%X} prints using the
digits @samp{0123456789ABCDEF}.
@end table

@subsubsection Inexact Conversions

@table @asis
@item @samp{f}
Print a floating-point number in fixed-point notation.

@item @samp{e}, @samp{E}
Print a floating-point number in exponential notation.  @samp{%e} prints
@samp{e} between mantissa and exponont.  @samp{%E} prints @samp{E}
between mantissa and exponont.

@item @samp{g}, @samp{G}
Print a floating-point number in either fixed or exponential notation,
whichever is more appropriate for its magnitude.  Unless an @samp{#}
flag has been supplied, trailing zeros after a decimal point will be
stripped off.  @samp{%g} prints @samp{e} between mantissa and exponont.
@samp{%G} prints @samp{E} between mantissa and exponent.

@item @samp{k}, @samp{K}
Print a number like @samp{%g}, except that an SI prefix is output
after the number, which is scaled accordingly.  @samp{%K} outputs a
dot between number and prefix, @samp{%k} does not.

@end table

@subsubsection Other Conversions
@table @asis
@item @samp{c}
Print a single character.  The @samp{-} flag is the only one which can
be specified.  It is an error to specify a precision.

@item @samp{s}
Print a string.  The @samp{-} flag is the only one which can be
specified.  A precision specifies the maximum number of characters to
output; otherwise all characters in the string are output.

@item @samp{a}, @samp{A}
Print a scheme expression.  The @samp{-} flag left-justifies the output.
The @samp{#} flag specifies that strings and characters should be quoted
as by @code{write} (which can be read using @code{read}); otherwise,
output is as @code{display} prints.  A precision specifies the maximum
number of characters to output; otherwise as many characters as needed
are output.

@emph{Note:} @samp{%a} and @samp{%A} are SLIB extensions.

@c @item @samp{p}
@c Print the value of a pointer.

@c @item @samp{n}
@c Get the number of characters printed so far.  See @ref{Other Output Conversions}.
@c Note that this conversion specification never produces any output.

@c @item @samp{m}
@c Print the string corresponding to the value of @code{errno}.
@c (This is a GNU extension.)
@c @xref{Other Output Conversions}.

@item @samp{%}
Print a literal @samp{%} character.  No argument is consumed.  It is an
error to specify flags, field width, precision, or type modifiers with
@samp{%%}.
@end table
@end deffn


@node Standard Formatted Input,  , Standard Formatted Output, Standard Formatted I/O
@subsection Standard Formatted Input

@code{(require 'scanf)}
@ftindex scanf

@deffn Function scanf-read-list format
@deffnx Function scanf-read-list format port
@deffnx Function scanf-read-list format string
@end deffn

@defmac scanf format arg1 @dots{}
@defmacx fscanf port format arg1 @dots{}
@defmacx sscanf str format arg1 @dots{}

Each function reads characters, interpreting them according to the
control string @var{format} argument.

@code{scanf-read-list} returns a list of the items specified as far as
the input matches @var{format}.  @code{scanf}, @code{fscanf}, and
@code{sscanf} return the number of items successfully matched and
stored.  @code{scanf}, @code{fscanf}, and @code{sscanf} also set the
location corresponding to @var{arg1} @dots{} using the methods:

@table @asis
@item symbol
@code{set!}
@item car expression
@code{set-car!}
@item cdr expression
@code{set-cdr!}
@item vector-ref expression
@code{vector-set!}
@item substring expression
@code{substring-move-left!}
@end table

The argument to a @code{substring} expression in @var{arg1} @dots{} must
be a non-constant string.  Characters will be stored starting at the
position specified by the second argument to @code{substring}.  The
number of characters stored will be limited by either the position
specified by the third argument to @code{substring} or the length of the
matched string, whichever is less.

The control string, @var{format}, contains conversion specifications and
other characters used to direct interpretation of input sequences.  The
control string contains:

@itemize @bullet
@item White-space characters (blanks, tabs, newlines, or formfeeds)
that cause input to be read (and discarded) up to the next
non-white-space character.

@item An ordinary character (not @samp{%}) that must match the next
character of the input stream.

@item Conversion specifications, consisting of the character @samp{%}, an
optional assignment suppressing character @samp{*}, an optional
numerical maximum-field width, an optional @samp{l}, @samp{h} or
@samp{L} which is ignored, and a conversion code.

@c @item The conversion specification can alternatively be prefixed by
@c the character sequence @samp{%n$} instead of the character @samp{%},
@c where @var{n} is a decimal integer in the range.  The @samp{%n$}
@c construction indicates that the value of the next input field should be
@c placed in the @var{n}th place in the return list, rather than to the next
@c unused one.  The two forms of introducing a conversion specification,
@c @samp{%} and @samp{%n$}, must not be mixed within a single format string
@c with the following exception: Skip fields (see below) can be designated
@c as @samp{%*} or @samp{%n$*}.  In the latter case, @var{n} is ignored.

@end itemize

Unless the specification contains the @samp{n} conversion character
(described below), a conversion specification directs the conversion of
the next input field.  The result of a conversion specification is
returned in the position of the corresponding argument points, unless
@samp{*} indicates assignment suppression.  Assignment suppression
provides a way to describe an input field to be skipped.  An input field
is defined as a string of characters; it extends to the next
inappropriate character or until the field width, if specified, is
exhausted.

@quotation
@emph{Note:} This specification of format strings differs from the
@cite{ANSI C} and @cite{POSIX} specifications.  In SLIB, white space
before an input field is not skipped unless white space appears before
the conversion specification in the format string.  In order to write
format strings which work identically with @cite{ANSI C} and SLIB,
prepend whitespace to all conversion specifications except @samp{[} and
@samp{c}.
@end quotation

The conversion code indicates the interpretation of the input field; For
a suppressed field, no value is returned.  The following conversion
codes are legal:

@table @asis

@item @samp{%}
A single % is expected in the input at this point; no value is returned.

@item @samp{d}, @samp{D}
A decimal integer is expected.

@item @samp{u}, @samp{U}
An unsigned decimal integer is expected.

@item @samp{o}, @samp{O}
An octal integer is expected.

@item @samp{x}, @samp{X}
A hexadecimal integer is expected.

@item @samp{i}
An integer is expected.  Returns the value of the next input item,
interpreted according to C conventions; a leading @samp{0} implies
octal, a leading @samp{0x} implies hexadecimal; otherwise, decimal is
assumed.

@item @samp{n}
Returns the total number of bytes (including white space) read by
@code{scanf}.  No input is consumed by @code{%n}.

@item @samp{f}, @samp{F}, @samp{e}, @samp{E}, @samp{g}, @samp{G}
A floating-point number is expected.  The input format for
floating-point numbers is an optionally signed string of digits,
possibly containing a radix character @samp{.}, followed by an optional
exponent field consisting of an @samp{E} or an @samp{e}, followed by an
optional @samp{+}, @samp{-}, or space, followed by an integer.

@item @samp{c}, @samp{C}
@var{Width} characters are expected.  The normal skip-over-white-space
is suppressed in this case; to read the next non-space character, use
@samp{%1s}.  If a field width is given, a string is returned; up to the
indicated number of characters is read.

@item @samp{s}, @samp{S}
A character string is expected The input field is terminated by a
white-space character.  @code{scanf} cannot read a null string.

@item @samp{[}
Indicates string data and the normal skip-over-leading-white-space is
suppressed.  The left bracket is followed by a set of characters, called
the scanset, and a right bracket; the input field is the maximal
sequence of input characters consisting entirely of characters in the
scanset.  @samp{^}, when it appears as the first character in the
scanset, serves as a complement operator and redefines the scanset as
the set of all characters not contained in the remainder of the scanset
string.  Construction of the scanset follows certain conventions.  A
range of characters may be represented by the construct first-last,
enabling @samp{[0123456789]} to be expressed @samp{[0-9]}.  Using this
convention, first must be lexically less than or equal to last;
otherwise, the dash stands for itself.  The dash also stands for itself
when it is the first or the last character in the scanset.  To include
the right square bracket as an element of the scanset, it must appear as
the first character (possibly preceded by a @samp{^}) of the scanset, in
which case it will not be interpreted syntactically as the closing
bracket.  At least one character must match for this conversion to
succeed.
@end table

The @code{scanf} functions terminate their conversions at end-of-file,
at the end of the control string, or when an input character conflicts
with the control string.  In the latter case, the offending character is
left unread in the input stream.
@end defmac


@node Programs and Arguments, HTML, Standard Formatted I/O, Textual Conversion Packages
@section Program and Arguments

@menu
* Getopt::                      Command Line option parsing
* Command Line::                A command line reader for Scheme shells
* Parameter lists::             'parameters
* Getopt Parameter lists::      'getopt-parameters
* Filenames::                   'glob or 'filename
* Batch::                       'batch
@end menu

@node Getopt, Command Line, Programs and Arguments, Programs and Arguments
@subsection Getopt

@code{(require 'getopt)}
@ftindex getopt

This routine implements Posix command line argument parsing.  Notice
that returning values through global variables means that @code{getopt}
is @emph{not} reentrant.

Obedience to Posix format for the @code{getopt} calls sows confusion.
Passing @var{argc} and @var{argv} as arguments while referencing
@var{optind} as a global variable leads to strange behavior,
especially when the calls to @code{getopt} are buried in other
procedures.

Even in C, @var{argc} can be derived from @var{argv}; what purpose
does it serve beyond providing an opportunity for
@var{argv}/@var{argc} mismatch?  Just such a mismatch existed for
years in a SLIB @code{getopt--} example.

I have removed the @var{argc} and @var{argv} arguments to getopt
procedures; and replaced them with a global variable:

@defvar *argv*
Define @var{*argv*} with a list of arguments before calling getopt
procedures.  If you don't want the first (0th) element to be ignored,
set @var{*optind*} to 0 (after requiring getopt).
@end defvar

@defvar *optind*
Is the index of the current element of the command line.  It is
initially one.  In order to parse a new command line or reparse an old
one, @var{*optind*} must be reset.
@end defvar

@defvar *optarg*
Is set by getopt to the (string) option-argument of the current option.
@end defvar

@defun getopt optstring
Returns the next option letter in @var{*argv*} (starting from
@code{(vector-ref argv *optind*)}) that matches a letter in
@var{optstring}.  @var{*argv*} is a vector or list of strings, the 0th
of which getopt usually ignores.  @var{optstring} is a string of
recognized option characters; if a character is followed by a colon,
the option takes an argument which may be immediately following it in
the string or in the next element of @var{*argv*}.

@var{*optind*} is the index of the next element of the @var{*argv*} vector
to be processed.  It is initialized to 1 by @file{getopt.scm}, and
@code{getopt} updates it when it finishes with each element of
@var{*argv*}.

@code{getopt} returns the next option character from @var{*argv*} that
matches a character in @var{optstring}, if there is one that matches.
If the option takes an argument, @code{getopt} sets the variable
@var{*optarg*} to the option-argument as follows:

@itemize @bullet
@item
If the option was the last character in the string pointed to by an
element of @var{*argv*}, then @var{*optarg*} contains the next element
of @var{*argv*}, and @var{*optind*} is incremented by 2.  If the
resulting value of @var{*optind*} is greater than or equal to
@code{(length @var{*argv*})}, this indicates a missing option
argument, and @code{getopt} returns an error indication.

@item
Otherwise, @var{*optarg*} is set to the string following the option
character in that element of @var{*argv*}, and @var{*optind*} is
incremented by 1.
@end itemize

If, when @code{getopt} is called, the string @code{(vector-ref argv
*optind*)} either does not begin with the character @code{#\-} or is
just @code{"-"}, @code{getopt} returns @code{#f} without changing
@var{*optind*}.  If @code{(vector-ref argv *optind*)} is the string
@code{"--"}, @code{getopt} returns @code{#f} after incrementing
@var{*optind*}.

If @code{getopt} encounters an option character that is not contained in
@var{optstring}, it returns the question-mark @code{#\?} character.  If
it detects a missing option argument, it returns the colon character
@code{#\:} if the first character of @var{optstring} was a colon, or a
question-mark character otherwise.  In either case, @code{getopt} sets
the variable @var{getopt:opt} to the option character that caused the
error.

The special option @code{"--"} can be used to delimit the end of the
options; @code{#f} is returned, and @code{"--"} is skipped.

RETURN VALUE

@code{getopt} returns the next option character specified on the command
line.  A colon @code{#\:} is returned if @code{getopt} detects a missing
argument and the first character of @var{optstring} was a colon
@code{#\:}.

A question-mark @code{#\?} is returned if @code{getopt} encounters an
option character not in @var{optstring} or detects a missing argument
and the first character of @var{optstring} was not a colon @code{#\:}.

Otherwise, @code{getopt} returns @code{#f} when all command line options
have been parsed.

Example:
@lisp
#! /usr/local/bin/scm
;;;This code is SCM specific.
(define argv (program-arguments))
(require 'getopt)
@ftindex getopt

(define opts ":a:b:cd")
(let loop ((opt (getopt (length argv) argv opts)))
  (case opt
    ((#\a) (print "option a: " *optarg*))
    ((#\b) (print "option b: " *optarg*))
    ((#\c) (print "option c"))
    ((#\d) (print "option d"))
    ((#\?) (print "error" getopt:opt))
    ((#\:) (print "missing arg" getopt:opt))
    ((#f) (if (< *optind* (length argv))
              (print "argv[" *optind* "]="
                     (list-ref argv *optind*)))
          (set! *optind* (+ *optind* 1))))
  (if (< *optind* (length argv))
      (loop (getopt (length argv) argv opts))))

(slib:exit)
@end lisp
@end defun

@subsection Getopt---

@defun @code{getopt--} optstring
The procedure @code{getopt--} is an extended version of @code{getopt}
which parses @dfn{long option names} of the form
@samp{--hold-the-onions} and @samp{--verbosity-level=extreme}.
@w{@code{Getopt--}} behaves as @code{getopt} except for non-empty
options beginning with @samp{--}.

Options beginning with @samp{--} are returned as strings rather than
characters.  If a value is assigned (using @samp{=}) to a long option,
@code{*optarg*} is set to the value.  The @samp{=} and value are
not returned as part of the option string.

No information is passed to @code{getopt--} concerning which long
options should be accepted or whether such options can take arguments.
If a long option did not have an argument, @code{*optarg*} will be set
to @code{#f}.  The caller is responsible for detecting and reporting
errors.

@example
(define opts ":-:b:")
(define *argv* '("foo" "-b9" "--f1" "--2=" "--g3=35234.342" "--"))
(define *optind* 1)
(define *optarg* #f)
(require 'qp)
@ftindex qp
(do ((i 5 (+ -1 i)))
    ((zero? i))
  (let ((opt (getopt-- opts)))
    (print *optind* opt *optarg*)))
@print{}
2 #\b "9"
3 "f1" #f
4 "2" ""
5 "g3" "35234.342"
5 #f "35234.342"
@end example
@end defun

@node Command Line, Parameter lists, Getopt, Programs and Arguments
@subsection Command Line

@include comparse.txi


@node Parameter lists, Getopt Parameter lists, Command Line, Programs and Arguments
@subsection Parameter lists

@code{(require 'parameters)}
@ftindex parameters

@noindent
Arguments to procedures in scheme are distinguished from each other by
their position in the procedure call.  This can be confusing when a
procedure takes many arguments, many of which are not often used.

@noindent
A @dfn{parameter-list} is a way of passing named information to a
procedure.  Procedures are also defined to set unused parameters to
default values, check parameters, and combine parameter lists.

@noindent
A @var{parameter} has the form @code{(@r{parameter-name} @r{value1}
@dots{})}.  This format allows for more than one value per
parameter-name.

@noindent
A @var{parameter-list} is a list of @var{parameter}s, each with a
different @var{parameter-name}.

@deffn Function make-parameter-list parameter-names
Returns an empty parameter-list with slots for @var{parameter-names}.
@end deffn

@deffn Function parameter-list-ref parameter-list parameter-name
@var{parameter-name} must name a valid slot of @var{parameter-list}.
@code{parameter-list-ref} returns the value of parameter
@var{parameter-name} of @var{parameter-list}.
@end deffn

@deffn Function remove-parameter parameter-name parameter-list
Removes the parameter @var{parameter-name} from @var{parameter-list}.
@code{remove-parameter} does not alter the argument
@var{parameter-list}.

If there are more than one @var{parameter-name} parameters, an error is
signaled.
@end deffn

@deffn {Procedure} adjoin-parameters! parameter-list parameter1 @dots{}
Returns @var{parameter-list} with @var{parameter1} @dots{} merged in.
@end deffn

@deffn {Procedure} parameter-list-expand expanders parameter-list
@var{expanders} is a list of procedures whose order matches the order of
the @var{parameter-name}s in the call to @code{make-parameter-list}
which created @var{parameter-list}.  For each non-false element of
@var{expanders} that procedure is mapped over the corresponding
parameter value and the returned parameter lists are merged into
@var{parameter-list}.

This process is repeated until @var{parameter-list} stops growing.  The
value returned from @code{parameter-list-expand} is unspecified.
@end deffn

@deffn Function fill-empty-parameters defaulters parameter-list
@var{defaulters} is a list of procedures whose order matches the order
of the @var{parameter-name}s in the call to @code{make-parameter-list}
which created @var{parameter-list}.  @code{fill-empty-parameters}
returns a new parameter-list with each empty parameter replaced with the
list returned by calling the corresponding @var{defaulter} with
@var{parameter-list} as its argument.
@end deffn

@deffn Function check-parameters checks parameter-list
@var{checks} is a list of procedures whose order matches the order of
the @var{parameter-name}s in the call to @code{make-parameter-list}
which created @var{parameter-list}.

@code{check-parameters} returns @var{parameter-list} if each @var{check}
of the corresponding @var{parameter-list} returns non-false.  If some
@var{check} returns @code{#f} a warning is signaled.
@end deffn

@noindent
In the following procedures @var{arities} is a list of symbols.  The
elements of @code{arities} can be:

@table @code
@item single
Requires a single parameter.
@item optional
A single parameter or no parameter is acceptable.
@item boolean
A single boolean parameter or zero parameters is acceptable.
@item nary
Any number of parameters are acceptable.
@item nary1
One or more of parameters are acceptable.
@end table

@deffn Function parameter-list->arglist positions arities parameter-list
Returns @var{parameter-list} converted to an argument list.  Parameters
of @var{arity} type @code{single} and @code{boolean} are converted to
the single value associated with them.  The other @var{arity} types are
converted to lists of the value(s).

@var{positions} is a list of positive integers whose order matches the
order of the @var{parameter-name}s in the call to
@code{make-parameter-list} which created @var{parameter-list}.  The
integers specify in which argument position the corresponding parameter
should appear.
@end deffn


@node Getopt Parameter lists, Filenames, Parameter lists, Programs and Arguments
@subsection Getopt Parameter lists

@include getparam.txi


@node Filenames, Batch, Getopt Parameter lists, Programs and Arguments
@subsection Filenames

@include glob.txi


@node Batch,  , Filenames, Programs and Arguments
@subsection Batch

@code{(require 'batch)}
@ftindex batch

@noindent
The batch procedures provide a way to write and execute portable scripts
for a variety of operating systems.  Each @code{batch:} procedure takes
as its first argument a parameter-list (@pxref{Parameter lists}).  This
parameter-list argument @var{parms} contains named associations.  Batch
currently uses 2 of these:

@table @code
@item batch-port
The port on which to write lines of the batch file.
@item batch-dialect
The syntax of batch file to generate.  Currently supported are:
@itemize @bullet
@item
unix
@item
dos
@item
vms
@item
amigaos
@item
system
@item
*unknown*
@end itemize
@end table

@noindent
@file{batch.scm} uses 2 enhanced relational tables
(@pxref{Using Databases}) to store information linking the names of
@code{operating-system}s to @code{batch-dialect}es.

@defun batch:initialize! database
Defines @code{operating-system} and @code{batch-dialect} tables and adds
the domain @code{operating-system} to the enhanced relational database
@var{database}.
@end defun

@defvar *operating-system*
Is batch's best guess as to which operating-system it is running under.
@code{*operating-system*} is set to @code{(software-type)}
(@pxref{Configuration}) unless @code{(software-type)} is @code{unix},
in which case finer distinctions are made.
@end defvar

@defun batch:call-with-output-script parms file proc
@var{proc} should be a procedure of one argument.  If @var{file} is an
output-port, @code{batch:call-with-output-script} writes an appropriate
header to @var{file} and then calls @var{proc} with @var{file} as the
only argument.  If @var{file} is a string,
@code{batch:call-with-output-script} opens a output-file of name
@var{file}, writes an appropriate header to @var{file}, and then calls
@var{proc} with the newly opened port as the only argument.  Otherwise,
@code{batch:call-with-output-script} acts as if it was called with the
result of @code{(current-output-port)} as its third argument.
@end defun

@noindent
The rest of the @code{batch:} procedures write (or execute if
@code{batch-dialect} is @code{system}) commands to the batch port which
has been added to @var{parms} or @code{(copy-tree @var{parms})} by the
code:

@example
(adjoin-parameters! @var{parms} (list 'batch-port @var{port}))
@end example

@defun batch:command parms string1 string2 @dots{}
Calls @code{batch:try-command} (below) with arguments, but signals an
error if @code{batch:try-command} returns @code{#f}.
@end defun

@noindent
These functions return a non-false value if the command was successfully
translated into the batch dialect and @code{#f} if not.  In the case of
the @code{system} dialect, the value is non-false if the operation
suceeded.

@defun batch:try-command parms string1 string2 @dots{}
Writes a command to the @code{batch-port} in @var{parms} which executes
the program named @var{string1} with arguments @var{string2} @dots{}.
@end defun

@defun batch:try-chopped-command parms arg1 arg2 @dots{} list
breaks the last argument @var{list} into chunks small enough so that the
command:

@example
@var{arg1} @var{arg2} @dots{} @var{chunk}
@end example

fits withing the platform's maximum command-line length.

@code{batch:try-chopped-command} calls @code{batch:try-command} with the
command and returns non-false only if the commands all fit and
@code{batch:try-command} of each command line returned non-false.
@end defun

@defun batch:run-script parms string1 string2 @dots{}
Writes a command to the @code{batch-port} in @var{parms} which executes
the batch script named @var{string1} with arguments @var{string2}
@dots{}.

@emph{Note:} @code{batch:run-script} and @code{batch:try-command} are not the
same for some operating systems (VMS).
@end defun

@defun batch:comment parms line1 @dots{}
Writes comment lines @var{line1} @dots{} to the @code{batch-port} in
@var{parms}.
@end defun

@defun batch:lines->file parms file line1 @dots{}
Writes commands to the @code{batch-port} in @var{parms} which create a
file named @var{file} with contents @var{line1} @dots{}.
@end defun

@defun batch:delete-file parms file
Writes a command to the @code{batch-port} in @var{parms} which deletes
the file named @var{file}.
@end defun

@defun batch:rename-file parms old-name new-name
Writes a command to the @code{batch-port} in @var{parms} which renames
the file @var{old-name} to @var{new-name}.
@end defun

@noindent
In addition, batch provides some small utilities very useful for writing
scripts:

@defun truncate-up-to path char
@defunx truncate-up-to path string
@defunx truncate-up-to path charlist
@var{path} can be a string or a list of strings.  Returns @var{path}
sans any prefixes ending with a character of the second argument.  This
can be used to derive a filename moved locally from elsewhere.

@example
(truncate-up-to "/usr/local/lib/slib/batch.scm" "/")
@result{} "batch.scm"
@end example
@end defun

@defun string-join joiner string1 @dots{}
Returns a new string consisting of all the strings @var{string1} @dots{}
in order appended together with the string @var{joiner} between each
adjacent pair.
@end defun

@defun must-be-first list1 list2
Returns a new list consisting of the elements of @var{list2} ordered so
that if some elements of @var{list1} are @code{equal?} to elements of
@var{list2}, then those elements will appear first and in the order of
@var{list1}.
@end defun

@defun must-be-last list1 list2
Returns a new list consisting of the elements of @var{list1} ordered so
that if some elements of @var{list2} are @code{equal?} to elements of
@var{list1}, then those elements will appear last and in the order of
@var{list2}.
@end defun

@defun os->batch-dialect osname
Returns its best guess for the @code{batch-dialect} to be used for the
operating-system named @var{osname}.  @code{os->batch-dialect} uses the
tables added to @var{database} by @code{batch:initialize!}.
@end defun

@noindent
Here is an example of the use of most of batch's procedures:

@example
(require 'databases)
@ftindex databases
(require 'parameters)
@ftindex parameters
(require 'batch)
@ftindex batch
(require 'glob)
@ftindex glob

(define batch (create-database #f 'alist-table))
(batch:initialize! batch)

(define my-parameters
  (list (list 'batch-dialect (os->batch-dialect *operating-system*))
        (list 'operating-system *operating-system*)
        (list 'batch-port (current-output-port)))) ;gets filled in later

(batch:call-with-output-script
 my-parameters
 "my-batch"
 (lambda (batch-port)
   (adjoin-parameters! my-parameters (list 'batch-port batch-port))
   (and
    (batch:comment my-parameters
                   "================ Write file with C program.")
    (batch:rename-file my-parameters "hello.c" "hello.c~")
    (batch:lines->file my-parameters "hello.c"
                       "#include <stdio.h>"
                       "int main(int argc, char **argv)"
                       "@{"
                       "  printf(\"hello world\\n\");"
                       "  return 0;"
                       "@}" )
    (batch:command my-parameters "cc" "-c" "hello.c")
    (batch:command my-parameters "cc" "-o" "hello"
                  (replace-suffix "hello.c" ".c" ".o"))
    (batch:command my-parameters "hello")
    (batch:delete-file my-parameters "hello")
    (batch:delete-file my-parameters "hello.c")
    (batch:delete-file my-parameters "hello.o")
    (batch:delete-file my-parameters "my-batch")
    )))
@end example

@noindent
Produces the file @file{my-batch}:

@example
#! /bin/sh
# "my-batch" script created by SLIB/batch Sun Oct 31 18:24:10 1999
# ================ Write file with C program.
mv -f hello.c hello.c~
rm -f hello.c
echo '#include <stdio.h>'>>hello.c
echo 'int main(int argc, char **argv)'>>hello.c
echo '@{'>>hello.c
echo '  printf("hello world\n");'>>hello.c
echo '  return 0;'>>hello.c
echo '@}'>>hello.c
cc -c hello.c
cc -o hello hello.o
hello
rm -f hello
rm -f hello.c
rm -f hello.o
rm -f my-batch
@end example

@noindent
When run, @file{my-batch} prints:

@example
bash$ my-batch
mv: hello.c: No such file or directory
hello world
@end example


@node HTML, HTML Tables, Programs and Arguments, Textual Conversion Packages
@section HTML

@include htmlform.txi


@node HTML Tables, HTTP and CGI, HTML, Textual Conversion Packages
@section HTML Tables

@include db2html.txi


@node HTTP and CGI, Parsing HTML, HTML Tables, Textual Conversion Packages
@section HTTP and CGI

@include http-cgi.txi


@node Parsing HTML, URI, HTTP and CGI, Textual Conversion Packages
@section Parsing HTML

@include html4each.txi


@node URI, Printing Scheme, Parsing HTML, Textual Conversion Packages
@section URI

@include uri.txi



@node Printing Scheme, Time and Date, URI, Textual Conversion Packages
@section Printing Scheme

@menu
* Generic-Write::               'generic-write
* Object-To-String::            'object->string
* Pretty-Print::                'pretty-print, 'pprint-file
@end menu


@node Generic-Write, Object-To-String, Printing Scheme, Printing Scheme
@subsection Generic-Write

@code{(require 'generic-write)}
@ftindex generic-write

@code{generic-write} is a procedure that transforms a Scheme data value
(or Scheme program expression) into its textual representation and
prints it.  The interface to the procedure is sufficiently general to
easily implement other useful formatting procedures such as pretty
printing, output to a string and truncated output.

@deffn {Procedure} generic-write obj display? width output
@table @var
@item obj
Scheme data value to transform.
@item display?
Boolean, controls whether characters and strings are quoted.
@item width
Extended boolean, selects format:
@table @asis
@item #f
single line format
@item integer > 0
pretty-print (value = max nb of chars per line)
@end table
@item output
Procedure of 1 argument of string type, called repeatedly with
successive substrings of the textual representation.  This procedure can
return @code{#f} to stop the transformation.
@end table

The value returned by @code{generic-write} is undefined.

Examples:
@lisp
(write obj) @equiv{} (generic-write obj #f #f @var{display-string})
(display obj) @equiv{} (generic-write obj #t #f @var{display-string})
@end lisp
@noindent
where
@lisp
@var{display-string} @equiv{}
(lambda (s) (for-each write-char (string->list s)) #t)
@end lisp
@end deffn



@node Object-To-String, Pretty-Print, Generic-Write, Printing Scheme
@subsection Object-To-String

@code{(require 'object->string)}
@ftindex object->string

@include obj2str.txi


@node Pretty-Print,  , Object-To-String, Printing Scheme
@subsection Pretty-Print

@code{(require 'pretty-print)}
@ftindex pretty-print

@deffn {Procedure} pretty-print obj
@deffnx {Procedure} pretty-print obj port

@code{pretty-print}s @var{obj} on @var{port}.  If @var{port} is not
specified, @code{current-output-port} is used.

Example:
@example
@group
(pretty-print '((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)))
   @print{} ((1 2 3 4 5)
   @print{}  (6 7 8 9 10)
   @print{}  (11 12 13 14 15)
   @print{}  (16 17 18 19 20)
   @print{}  (21 22 23 24 25))
@end group
@end example
@end deffn

@deffn {Procedure} pretty-print->string obj
@deffnx {Procedure} pretty-print->string obj width

Returns the string of @var{obj} @code{pretty-print}ed in @var{width}
columns.  If @var{width} is not specified, @code{(output-port-width)} is
used.

Example:
@example
@group
(pretty-print->string '((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)))
@result{}
"((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))
"
@end group
@group
(pretty-print->string '((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))
                      16)
@result{}
"((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))
"
@end group
@end example
@end deffn


@code{(require 'pprint-file)}
@ftindex pprint-file

@deffn {Procedure} pprint-file infile
@deffnx {Procedure} pprint-file infile outfile
Pretty-prints all the code in @var{infile}.  If @var{outfile} is
specified, the output goes to @var{outfile}, otherwise it goes to
@code{(current-output-port)}.
@end deffn

@defun pprint-filter-file infile proc outfile
@defunx pprint-filter-file infile proc
@var{infile} is a port or a string naming an existing file.  Scheme
source code expressions and definitions are read from the port (or file)
and @var{proc} is applied to them sequentially.

@var{outfile} is a port or a string.  If no @var{outfile} is specified
then @code{current-output-port} is assumed.  These expanded expressions
are then @code{pretty-print}ed to this port.

Whitepsace and comments (introduced by @code{;}) which are not part of
scheme expressions are reproduced in the output.  This procedure does
not affect the values returned by @code{current-input-port} and
@code{current-output-port}.
@end defun

@code{pprint-filter-file} can be used to pre-compile macro-expansion and
thus can reduce loading time.  The following will write into
@file{exp-code.scm} the result of expanding all defmacros in
@file{code.scm}.
@lisp
(require 'pprint-file)
@ftindex pprint-file
(require 'defmacroexpand)
@ftindex defmacroexpand
(defmacro:load "my-macros.scm")
(pprint-filter-file "code.scm" defmacro:expand* "exp-code.scm")
@end lisp

@node Time and Date, NCBI-DNA, Printing Scheme, Textual Conversion Packages
@section Time and Date

@menu
* Time Zone::                   
* Posix Time::                  'posix-time
* Common-Lisp Time::            'common-lisp-time
* Time Infrastructure::         
@end menu

@noindent
If @code{(provided? 'current-time)}:

@noindent
The procedures @code{current-time}, @code{difftime}, and
@code{offset-time} deal with a @dfn{calendar time} datatype
@cindex time
@cindex calendar time
which may or may not be disjoint from other Scheme datatypes.

@defun current-time
Returns the time since 00:00:00 GMT, January 1, 1970, measured in
seconds.  Note that the reference time is different from the reference
time for @code{get-universal-time} in @ref{Common-Lisp Time}.
@end defun

@defun difftime caltime1 caltime0
Returns the difference (number of seconds) between twe calendar times:
@var{caltime1} - @var{caltime0}.  @var{caltime0} may also be a number.
@end defun

@defun offset-time caltime offset
Returns the calendar time of @var{caltime} offset by @var{offset} number
of seconds @code{(+ caltime offset)}.
@end defun


@node Time Zone, Posix Time, Time and Date, Time and Date
@subsection Time Zone

(require 'time-zone)

@deftp {Data Format} TZ-string

POSIX standards specify several formats for encoding time-zone rules.

@table @t
@item :@i{<pathname>}
If the first character of @i{<pathname>} is @samp{/}, then
@i{<pathname>} specifies the absolute pathname of a tzfile(5) format
time-zone file.  Otherwise, @i{<pathname>} is interpreted as a pathname
within @var{tzfile:vicinity} (/usr/lib/zoneinfo/) naming a tzfile(5)
format time-zone file.
@item @i{<std>}@i{<offset>}
The string @i{<std>} consists of 3 or more alphabetic characters.
@i{<offset>} specifies the time difference from GMT.  The @i{<offset>}
is positive if the local time zone is west of the Prime Meridian and
negative if it is east.  @i{<offset>} can be the number of hours or
hours and minutes (and optionally seconds) separated by @samp{:}.  For
example, @code{-4:30}.
@item @i{<std>}@i{<offset>}@i{<dst>}
@i{<dst>} is the at least 3 alphabetic characters naming the local
daylight-savings-time.
@item @i{<std>}@i{<offset>}@i{<dst>}@i{<doffset>}
@i{<doffset>} specifies the offset from the Prime Meridian when
daylight-savings-time is in effect.
@end table

The non-tzfile formats can optionally be followed by transition times
specifying the day and time when a zone changes from standard to
daylight-savings and back again.

@table @t
@item ,@i{<date>}/@i{<time>},@i{<date>}/@i{<time>}
The @i{<time>}s are specified like the @i{<offset>}s above, except that
leading @samp{+} and @samp{-} are not allowed.

Each @i{<date>} has one of the formats:

@table @t
@item J@i{<day>}
specifies the Julian day with @i{<day>} between 1 and 365.  February 29
is never counted and cannot be referenced.
@item @i{<day>}
This specifies the Julian day with n between 0 and 365.  February 29 is
counted in leap years and can be specified.
@item M@i{<month>}.@i{<week>}.@i{<day>}
This specifies day @i{<day>} (0 <= @i{<day>} <= 6) of week @i{<week>} (1
<= @i{<week>} <= 5) of month @i{<month>} (1 <= @i{<month>} <= 12).  Week
1 is the first week in which day d occurs and week 5 is the last week in
which day @i{<day>} occurs.  Day 0 is a Sunday.
@end table
@end table

@end deftp

@deftp {Data Type} time-zone
is a datatype encoding how many hours from Greenwich Mean Time the local
time is, and the @dfn{Daylight Savings Time} rules for changing it.
@end deftp

@defun time-zone TZ-string
Creates and returns a time-zone object specified by the string
@var{TZ-string}.  If @code{time-zone} cannot interpret @var{TZ-string},
@code{#f} is returned.
@end defun

@defun tz:params caltime tz
@var{tz} is a time-zone object.  @code{tz:params} returns a list of
three items:
@enumerate 0
@item
An integer.  0 if standard time is in effect for timezone @var{tz} at
@var{caltime}; 1 if daylight savings time is in effect for timezone
@var{tz} at @var{caltime}.
@item
The number of seconds west of the Prime Meridian timezone @var{tz} is at
@var{caltime}.
@item
The name for timezone @var{tz} at @var{caltime}.
@end enumerate

@code{tz:params} is unaffected by the default timezone; inquiries can be
made of any timezone at any calendar time.

@end defun

@defun tz:std-offset tz
@var{tz} is a time-zone object.  @code{tz:std-offset} returns the
number of seconds west of the Prime Meridian timezone @var{tz} is.

@end defun

@noindent
The rest of these procedures and variables are provided for POSIX
compatability.  Because of shared state they are not thread-safe.

@defun tzset
Returns the default time-zone.

@defunx tzset tz
Sets (and returns) the default time-zone to @var{tz}.

@defunx tzset TZ-string
Sets (and returns) the default time-zone to that specified by
@var{TZ-string}.

@code{tzset} also sets the variables @var{*timezone*}, @var{daylight?},
and @var{tzname}.  This function is automatically called by the time
conversion procedures which depend on the time zone (@pxref{Time and
Date}).
@end defun

@defvar *timezone*
Contains the difference, in seconds, between Greenwich Mean Time and
local standard time (for example, in the U.S.  Eastern time zone (EST),
timezone is 5*60*60).  @code{*timezone*} is initialized by @code{tzset}.
@end defvar

@defvar daylight?
is @code{#t} if the default timezone has rules for @dfn{Daylight Savings
Time}.  @emph{Note:} @var{daylight?} does not tell you when Daylight
Savings Time is in effect, just that the default zone sometimes has
Daylight Savings Time.
@end defvar

@defvar tzname
is a vector of strings.  Index 0 has the abbreviation for the standard
timezone; If @var{daylight?}, then index 1 has the abbreviation for the
Daylight Savings timezone.
@end defvar


@node Posix Time, Common-Lisp Time, Time Zone, Time and Date
@subsection Posix Time

@example
(require 'posix-time)
@ftindex posix-time
@end example

@deftp {Data Type} {Calendar-Time}
@cindex calendar time
@cindex caltime
is a datatype encapsulating time.
@end deftp

@deftp {Data Type} {Coordinated Universal Time}
@cindex Coordinated Universal Time
@cindex UTC
(abbreviated @dfn{UTC}) is a vector of integers representing time:

@enumerate 0
@item
 seconds (0 - 61)
@item
 minutes (0 - 59)
@item
 hours since midnight (0 - 23)
@item
 day of month (1 - 31)
@item
 month (0 - 11).  Note difference from @code{decode-universal-time}.
@item
 the number of years since 1900.  Note difference from
@code{decode-universal-time}.
@item
 day of week (0 - 6)
@item
 day of year (0 - 365)
@item
 1 for daylight savings, 0 for regular time
@end enumerate
@end deftp

@defun gmtime caltime
Converts the calendar time @var{caltime} to UTC and returns it.

@defunx localtime caltime tz
Returns @var{caltime} converted to UTC relative to timezone @var{tz}.

@defunx localtime caltime
converts the calendar time @var{caltime} to a vector of integers
expressed relative to the user's time zone.  @code{localtime} sets the
variable @var{*timezone*} with the difference between Coordinated
Universal Time (UTC) and local standard time in seconds
(@pxref{Time Zone,tzset}).

@end defun

@defun gmktime univtime
Converts a vector of integers in GMT Coordinated Universal Time (UTC)
format to a calendar time.

@defunx mktime univtime
Converts a vector of integers in local Coordinated Universal Time (UTC)
format to a calendar time.

@defunx mktime univtime tz
Converts a vector of integers in Coordinated Universal Time (UTC) format
(relative to time-zone @var{tz})
to calendar time.
@end defun

@defun asctime univtime
Converts the vector of integers @var{caltime} in Coordinated
Universal Time (UTC) format into a string of the form
@code{"Wed Jun 30 21:49:08 1993"}.
@end defun

@defun gtime caltime
@defunx ctime caltime
@defunx ctime caltime tz
Equivalent to @code{(asctime (gmtime @var{caltime}))},
@code{(asctime (localtime @var{caltime}))}, and
@code{(asctime (localtime @var{caltime} @var{tz}))}, respectively.
@end defun


@node Common-Lisp Time, Time Infrastructure, Posix Time, Time and Date
@subsection Common-Lisp Time

@defun get-decoded-time
Equivalent to @code{(decode-universal-time (get-universal-time))}.
@end defun

@defun get-universal-time
Returns the current time as @dfn{Universal Time}, number of seconds
since 00:00:00 Jan 1, 1900 GMT.  Note that the reference time is
different from @code{current-time}.
@end defun

@defun decode-universal-time univtime
Converts @var{univtime} to @dfn{Decoded Time} format.
Nine values are returned:
@enumerate 0
@item
 seconds (0 - 61)
@item
 minutes (0 - 59)
@item
 hours since midnight
@item
 day of month
@item
 month (1 - 12).  Note difference from @code{gmtime} and @code{localtime}.
@item
 year (A.D.).  Note difference from @code{gmtime} and @code{localtime}.
@item
 day of week (0 - 6)
@item
 #t for daylight savings, #f otherwise
@item
 hours west of GMT (-24 - +24)
@end enumerate

Notice that the values returned by @code{decode-universal-time} do not
match the arguments to @code{encode-universal-time}.
@end defun

@defun encode-universal-time second minute hour date month year
@defunx encode-universal-time second minute hour date month year time-zone
Converts the arguments in Decoded Time format to Universal Time format.
If @var{time-zone} is not specified, the returned time is adjusted for
daylight saving time.  Otherwise, no adjustment is performed.

Notice that the values returned by @code{decode-universal-time} do not
match the arguments to @code{encode-universal-time}.
@end defun

@node Time Infrastructure,  , Common-Lisp Time, Time and Date
@subsection Time Infrastructure

@code{(require 'time-core)}

@defun time:gmtime tm
@defunx time:invert decoder target
@defunx time:split t tm_isdst tm_gmtoff tm_zone
@end defun

@code{(require 'tzfile)}

@defun tzfile:read path
@end defun


@node NCBI-DNA, Schmooz, Time and Date, Textual Conversion Packages
@section NCBI-DNA

@include ncbi-dna.txi


@node Schmooz,  , NCBI-DNA, Textual Conversion Packages
@section Schmooz

@include schmooz.texi



@node Mathematical Packages, Database Packages, Textual Conversion Packages, Top
@chapter Mathematical Packages

@menu
* Bit-Twiddling::               'logical
* Modular Arithmetic::          'modular
* Irrational Integer Functions::  
* Irrational Real Functions::   
* Prime Numbers::               'factor
* Random Numbers::              'random
* Discrete Fourier Transform::  'dft
* Cyclic Checksum::             'crc
* Graphing::                    
* Solid Modeling::              VRML97
* Color::                       
* Root Finding::                'root
* Minimizing::                  'minimize
* The Limit::                   'limit
* Commutative Rings::           'commutative-ring
* Matrix Algebra::              'determinant
@end menu


@node Bit-Twiddling, Modular Arithmetic, Mathematical Packages, Mathematical Packages
@section Bit-Twiddling

@code{(require 'logical)} or @code{(require 'srfi-60)}
@ftindex logical
@ftindex srfi-60

@noindent
The bit-twiddling functions are made available through the use of the
@code{logical} package.  @code{logical} is loaded by inserting
@ftindex logical
@code{(require 'logical)} before the code that uses these functions.
These functions behave as though operating on integers in
two's-complement representation.

@subsection Bitwise Operations

@defun logand n1 @dots{}
@defunx bitwise-and n1 @dots{}
Returns the integer which is the bit-wise AND of the integer
arguments.

Example:
@lisp
(number->string (logand #b1100 #b1010) 2)
   @result{} "1000"
@end lisp
@end defun

@defun logior n1 @dots{}
@defunx bitwise-ior n1 @dots{}
Returns the integer which is the bit-wise OR of the integer arguments.

Example:
@lisp
(number->string (logior #b1100 #b1010) 2)
   @result{} "1110"
@end lisp
@end defun

@defun logxor n1 @dots{}
@defunx bitwise-xor n1 @dots{}
Returns the integer which is the bit-wise XOR of the integer
arguments.

Example:
@lisp
(number->string (logxor #b1100 #b1010) 2)
   @result{} "110"
@end lisp
@end defun

@defun lognot n
@defunx bitwise-not n
Returns the integer which is the one's-complement of the integer
argument.

Example:
@lisp
(number->string (lognot #b10000000) 2)
   @result{} "-10000001"
(number->string (lognot #b0) 2)
   @result{} "-1"
@end lisp
@end defun

@defun bitwise-if mask n0 n1
@defunx bitwise-merge mask n0 n1
Returns an integer composed of some bits from integer @var{n0} and some
from integer @var{n1}.  A bit of the result is taken from @var{n0} if the
corresponding bit of integer @var{mask} is 1 and from @var{n1} if that bit
of @var{mask} is 0.
@end defun

@defun logtest j k
@defunx any-bits-set? j k
@example
(logtest j k) @equiv{} (not (zero? (logand j k)))

(logtest #b0100 #b1011) @result{} #f
(logtest #b0100 #b0111) @result{} #t
@end example
@end defun


@subsection Integer Properties

@defun logcount n
@defunx bit-count n
Returns the number of bits in integer @var{n}.  If integer is positive,
the 1-bits in its binary representation are counted.  If negative, the
0-bits in its two's-complement binary representation are counted.  If 0,
0 is returned.

Example:
@lisp
(logcount #b10101010)
   @result{} 4
(logcount 0)
   @result{} 0
(logcount -2)
   @result{} 1
@end lisp
@end defun

@defun integer-length n
Returns the number of bits neccessary to represent @var{n}.

Example:
@lisp
(integer-length #b10101010)
   @result{} 8
(integer-length 0)
   @result{} 0
(integer-length #b1111)
   @result{} 4
@end lisp
@end defun

@defun log2-binary-factors n
@defunx first-set-bit n
Returns the number of factors of two of integer @var{n}.  This value
is also the bit-index of the least-significant @samp{1} bit in
@var{n}.

@lisp
(require 'printf)
(do ((idx 0 (+ 1 idx)))
      ((> idx 16))
    (printf "%s(%3d) ==> %-5d %s(%2d) ==> %-5d\n"
            'log2-binary-factors
            (- idx) (log2-binary-factors (- idx))
            'log2-binary-factors
            idx (log2-binary-factors idx)))
@print{}
log2-binary-factors(  0) ==> -1    log2-binary-factors( 0) ==> -1   
log2-binary-factors( -1) ==> 0     log2-binary-factors( 1) ==> 0    
log2-binary-factors( -2) ==> 1     log2-binary-factors( 2) ==> 1    
log2-binary-factors( -3) ==> 0     log2-binary-factors( 3) ==> 0    
log2-binary-factors( -4) ==> 2     log2-binary-factors( 4) ==> 2    
log2-binary-factors( -5) ==> 0     log2-binary-factors( 5) ==> 0    
log2-binary-factors( -6) ==> 1     log2-binary-factors( 6) ==> 1    
log2-binary-factors( -7) ==> 0     log2-binary-factors( 7) ==> 0    
log2-binary-factors( -8) ==> 3     log2-binary-factors( 8) ==> 3    
log2-binary-factors( -9) ==> 0     log2-binary-factors( 9) ==> 0    
log2-binary-factors(-10) ==> 1     log2-binary-factors(10) ==> 1    
log2-binary-factors(-11) ==> 0     log2-binary-factors(11) ==> 0    
log2-binary-factors(-12) ==> 2     log2-binary-factors(12) ==> 2    
log2-binary-factors(-13) ==> 0     log2-binary-factors(13) ==> 0    
log2-binary-factors(-14) ==> 1     log2-binary-factors(14) ==> 1    
log2-binary-factors(-15) ==> 0     log2-binary-factors(15) ==> 0    
log2-binary-factors(-16) ==> 4     log2-binary-factors(16) ==> 4    
@end lisp
@end defun

@subsection Bit Within Word

@defun logbit? index n
@defunx bit-set? index n
@example
(logbit? index n) @equiv{} (logtest (expt 2 index) n)

(logbit? 0 #b1101) @result{} #t
(logbit? 1 #b1101) @result{} #f
(logbit? 2 #b1101) @result{} #t
(logbit? 3 #b1101) @result{} #t
(logbit? 4 #b1101) @result{} #f
@end example
@end defun

@defun copy-bit index from bit
Returns an integer the same as @var{from} except in the @var{index}th bit,
which is 1 if @var{bit} is @code{#t} and 0 if @var{bit} is @code{#f}.

Example:
@example
(number->string (copy-bit 0 0 #t) 2)       @result{} "1"
(number->string (copy-bit 2 0 #t) 2)       @result{} "100"
(number->string (copy-bit 2 #b1111 #f) 2)  @result{} "1011"
@end example
@end defun


@subsection Field of Bits

@defun bit-field n start end
Returns the integer composed of the @var{start} (inclusive) through
@var{end} (exclusive) bits of @var{n}.  The @var{start}th bit becomes
the 0-th bit in the result.

Example:
@lisp
(number->string (bit-field #b1101101010 0 4) 2)
   @result{} "1010"
(number->string (bit-field #b1101101010 4 9) 2)
   @result{} "10110"
@end lisp
@end defun

@defun copy-bit-field to from start end
Returns an integer the same as @var{to} except possibly in the
@var{start} (inclusive) through @var{end} (exclusive) bits, which are
the same as those of @var{from}.  The 0-th bit of @var{from} becomes the
@var{start}th bit of the result.

Example:
@example
(number->string (copy-bit-field #b1101101010 0 0 4) 2)
        @result{} "1101100000"
(number->string (copy-bit-field #b1101101010 -1 0 4) 2)
        @result{} "1101101111"
(number->string (copy-bit-field #b110100100010000 -1 5 9) 2)
        @result{} "110100111110000"
@end example
@end defun

@defun ash n count
@defunx arithmetic-shift n count
Returns an integer equivalent to
@code{(inexact->exact (floor (* @var{n} (expt 2 @var{count}))))}.

Example:
@lisp
(number->string (ash #b1 3) 2)
   @result{} "1000"
(number->string (ash #b1010 -1) 2)
   @result{} "101"
@end lisp
@end defun


@defun rotate-bit-field n count start end
Returns @var{n} with the bit-field from @var{start} to @var{end}
cyclically permuted by @var{count} bits towards high-order.

Example:
@lisp
(number->string (rotate-bit-field #b0100 3 0 4) 2)
    @result{} "10"
(number->string (rotate-bit-field #b0100 -1 0 4) 2)
    @result{} "10"
(number->string (rotate-bit-field #b110100100010000 -1 5 9) 2)
    @result{} "110100010010000"
(number->string (rotate-bit-field #b110100100010000 1 5 9) 2)
    @result{} "110100000110000"
@end lisp
@end defun

@defun reverse-bit-field n start end
Returns @var{n} with the order of bits @var{start} to @var{end}
reversed.

@example
(number->string (reverse-bit-field #xa7 0 8) 16)
  @result{} "e5"
@end example
@end defun


@subsection Bits as Booleans

@defun integer->list k len
@defunx integer->list k
@code{integer->list} returns a list of @var{len} booleans corresponding
to each bit of the given integer.  #t is coded for each 1; #f for 0.
The @var{len} argument defaults to @code{(integer-length @var{k})}.

@defunx list->integer list
@code{list->integer} returns an integer formed from the booleans in the
list @var{list}, which must be a list of booleans.  A 1 bit is coded for
each #t; a 0 bit for #f.

@code{integer->list} and @code{list->integer} are inverses so far as
@code{equal?} is concerned.
@end defun

@defun booleans->integer bool1 @dots{}
Returns the integer coded by the @var{bool1} @dots{} arguments.
@end defun




@node Modular Arithmetic, Irrational Integer Functions, Bit-Twiddling, Mathematical Packages
@section Modular Arithmetic

@include modular.txi


@node Irrational Integer Functions, Irrational Real Functions, Modular Arithmetic, Mathematical Packages
@section Irrational Integer Functions

@include math-integer.txi


@node Irrational Real Functions, Prime Numbers, Irrational Integer Functions, Mathematical Packages
@section Irrational Real Functions

@code{(require 'math-real)}
@ftindex math-real

Although this package defines real and complex functions, it is safe
to load into an integer-only implementation; those functions will be
defined to #f.

@defun real-exp  @var{x}
@defunx  real-ln  @var{x}
@defunx  real-log  @var{y} @var{x}
@defunx  real-sin  @var{x}
@defunx  real-cos  @var{x}
@defunx  real-tan  @var{x}
@defunx  real-asin  @var{x}
@defunx  real-acos  @var{x}
@defunx  real-atan  @var{x}
@defunx  atan  @var{y} @var{x}

These procedures are part of every implementation that supports
general real numbers; they compute the usual transcendental functions.
@samp{real-ln} computes the natural logarithm of @var{x};
@samp{real-log} computes the logarithm of @var{x} base @var{y}, which
is @code{(/ (real-ln x) (real-ln y))}.  If arguments @var{x} and
@var{y} are not both real; or if the correct result would not be real,
then these procedures signal an error.

@end defun


@defun real-sqrt  @var{x}

For non-negative real @var{x} the result will be its positive square
root; otherwise an error will be signaled.

@end defun


@defun real-expt  x1 x2

Returns @var{x1} raised to the power @var{x2} if that result is a real
number; otherwise signals an error.

@code{(real-expt 0.0 @var{x2})}

@itemize @bullet
@item
returns 1.0 for @var{x2} equal to 0.0;
@item
returns 0.0 for positive real @var{x2};
@item
signals an error otherwise.
@end itemize

@end defun


@defun quo x1 x2
@defunx rem x1 x2
@defunx mod x1 x2

@var{x2} should be non-zero.

@example
    (quo @var{x1} @var{x2})                     ==> @var{n_q}
    (rem @var{x1} @var{x2})                     ==> @var{x_r}
    (mod @var{x1} @var{x2})                     ==> @var{x_m}
@end example

where @var{n_q} is @var{x1}/@var{x2} rounded towards zero,
0 < |@var{x_r}| < |@var{x2}|, 0 < |@var{x_m}| < |@var{x2}|, @var{x_r}
and @var{x_m} differ from @var{x1} by a multiple of @var{x2},
@var{x_r} has the same sign as @var{x1}, and @var{x_m} has the same
sign as @var{x2}.

From this we can conclude that for @var{x2} not equal to 0,

@example
     (= @var{x1} (+ (* @var{x2} (quo @var{x1} @var{x2}))
           (rem @var{x1} @var{x2})))
                                       ==>  #t
@end example

provided all numbers involved in that computation are exact.

@example
    (quo 2/3 1/5)                         ==>  3
    (mod 2/3 1/5)                         ==>  1/15

    (quo .666 1/5)                        ==>  3.0
    (mod .666 1/5)                        ==>  65.99999999999995e-3
@end example
@end defun


@defun ln @var{z}

These procedures are part of every implementation that supports
general real numbers.
@samp{Ln} computes the natural logarithm of @var{z}

In general, the mathematical function ln is multiply defined.  The
value of ln @var{z} is defined to be the one whose imaginary part lies
in the range from -pi (exclusive) to pi (inclusive).

@end defun


@defun abs  x

For real argument @var{x}, @samp{Abs} returns the absolute value of
@var{x}' otherwise it signals an error.

@format
@t{(abs -7)                               ==>  7
}
@end format

@end defun

@defun make-rectangular  x1 x2
@defunx make-polar  x3 x4

These procedures are part of every implementation that supports
general complex numbers.  Suppose @var{x1}, @var{x2}, @var{x3}, and
@var{x4} are real numbers and @var{z} is a complex number such that
 

@center  @var{z} = @var{x1} + @var{x2}@w{i} = @var{x3} . e^@w{i} @var{x4}

Then

@format
@t{(make-rectangular @var{x1} @var{x2})               ==> @var{z}
(make-polar @var{x3} @var{x4})                     ==> @var{z}
}
@end format

where -pi < x_angle <= pi with x_angle = @var{x4} + 2pi n
for some integer n.

If an argument is not real, then these procedures signal an error.

@end defun



@node Prime Numbers, Random Numbers, Irrational Real Functions, Mathematical Packages
@section Prime Numbers

@code{(require 'factor)}
@ftindex factor
@ftindex primes

@include factor.txi


@node Random Numbers, Discrete Fourier Transform, Prime Numbers, Mathematical Packages
@section Random Numbers

@cindex RNG
@cindex PRNG
A pseudo-random number generator is only as good as the tests it passes.
George Marsaglia of Florida State University developed a battery of
tests named @dfn{DIEHARD} (@url{http://stat.fsu.edu/~geo/diehard.html}).
@file{diehard.c} has a bug which the patch
@url{http://swiss.csail.mit.edu/ftpdir/users/jaffer/diehard.c.pat} corrects.

SLIB's PRNG generates 8 bits at a time.  With the degenerate seed
@samp{0}, the numbers generated pass DIEHARD; but when bits are
combined from sequential bytes, tests fail.  With the seed
@samp{http://swissnet.ai.mit.edu/~jaffer/SLIB.html}, all of those
tests pass.

@menu
* Exact Random Numbers::        'random
* Inexact Random Numbers::      'random-inexact
@end menu

@node Exact Random Numbers, Inexact Random Numbers, Random Numbers, Random Numbers
@subsection Exact Random Numbers

@include random.txi


@node Inexact Random Numbers,  , Exact Random Numbers, Random Numbers
@subsection Inexact Random Numbers

@include randinex.txi


@node Discrete Fourier Transform, Cyclic Checksum, Random Numbers, Mathematical Packages
@section Discrete Fourier Transform

@include dft.txi


@node Cyclic Checksum, Graphing, Discrete Fourier Transform, Mathematical Packages
@section Cyclic Checksum

@code{(require 'crc)}
@ftindex crc
@noindent
Cyclic Redundancy Checks using Galois field GF(2) polynomial
arithmetic are used for error detection in many data transmission
and storage applications.

@noindent
The generator polynomials for various CRC protocols are availble
from many sources.  But the polynomial is just one of many
parameters which must match in order for a CRC implementation to
interoperate with existing systems:

@itemize @bullet

@item
the byte-order and bit-order of the data stream;

@item
whether the CRC or its inverse is being calculated;

@item
the initial CRC value; and

@item
whether and where the CRC value is appended (inverted
or non-inverted) to the data stream.

@end itemize

@noindent
The performance of a particular CRC polynomial over packets of given
sizes varies widely.  In terms of the probability of undetected
errors, some uses of extant CRC polynomials are suboptimal by several
orders of magnitude.

@noindent
If you are considering CRC for a new application, consult the
following article to find the optimum CRC polynomial for your range of
data lengths:

@itemize @bullet
@item
Philip Koopman and Tridib Chakravarty,@*
``Cyclic Redundancy Code (CRC) Polynomial Selection For Embedded Networks'',@*
The International Conference on Dependable Systems and Networks, DSN-2004.@*
@end itemize

@exdent
@url{http://www.ece.cmu.edu/~koopman/roses/dsn04/koopman04_crc_poly_embedded.pdf}

@noindent
There is even some controversy over the polynomials themselves.

@defvr Constant crc-32-polynomial
For CRC-32, http://www2.sis.pitt.edu/~jkabara/tele-2100/lect08.html
gives x^32+x^26+x^23+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x^1+1.

But
http://www.cs.ncl.ac.uk/people/harry.whitfield/home.formal/CRCs.html,
http://duchon.umuc.edu/Web_Pages/duchon/99_f_cm435/ShiftRegister.htm,
http://spinroot.com/spin/Doc/Book91_PDF/ch3.pdf,
http://www.erg.abdn.ac.uk/users/gorry/course/dl-pages/crc.html,
http://www.rad.com/networks/1994/err_con/crc_most.htm, and
http://www.gpfn.sk.ca/~rhg/csc8550s02/crc.html,
http://www.nobugconsulting.ro/crc.php give
x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1.

SLIB @code{crc-32-polynomial} uses the latter definition.
@end defvr

@defvr Constant crc-ccitt-polynomial

http://www.math.grin.edu/~rebelsky/Courses/CS364/2000S/Outlines/outline.12.html,
http://duchon.umuc.edu/Web_Pages/duchon/99_f_cm435/ShiftRegister.htm,
http://www.cs.ncl.ac.uk/people/harry.whitfield/home.formal/CRCs.html,
http://www2.sis.pitt.edu/~jkabara/tele-2100/lect08.html, and
http://www.gpfn.sk.ca/~rhg/csc8550s02/crc.html give
CRC-CCITT: x^16+x^12+x^5+1.
@end defvr

@defvr Constant crc-16-polynomial

http://www.math.grin.edu/~rebelsky/Courses/CS364/2000S/Outlines/outline.12.html,
http://duchon.umuc.edu/Web_Pages/duchon/99_f_cm435/ShiftRegister.htm,
http://www.cs.ncl.ac.uk/people/harry.whitfield/home.formal/CRCs.html,
http://www.gpfn.sk.ca/~rhg/csc8550s02/crc.html, and
http://www.usb.org/developers/data/crcdes.pdf give
CRC-16: x^16+x^15+x^2+1.
@end defvr

@defvr Constant crc-12-polynomial

http://www.math.grin.edu/~rebelsky/Courses/CS364/2000S/Outlines/outline.12.html,
http://www.cs.ncl.ac.uk/people/harry.whitfield/home.formal/CRCs.html,
http://www.it.iitb.ac.in/it605/lectures/link/node4.html, and
http://spinroot.com/spin/Doc/Book91_PDF/ch3.pdf give
CRC-12: x^12+x^11+x^3+x^2+1.

But
http://www.ffldusoe.edu/Faculty/Denenberg/Topics/Networks/Error_Detection_Correction/crc.html,
http://duchon.umuc.edu/Web_Pages/duchon/99_f_cm435/ShiftRegister.htm,
http://www.eng.uwi.tt/depts/elec/staff/kimal/errorcc.html,
http://www.ee.uwa.edu.au/~roberto/teach/itc314/java/CRC/,
http://www.gpfn.sk.ca/~rhg/csc8550s02/crc.html, and
http://www.efg2.com/Lab/Mathematics/CRC.htm give
CRC-12: x^12+x^11+x^3+x^2+x+1.

These differ in bit 1 and calculations using them return different
values.  With citations near evenly split, it is hard to know which is
correct.  Thanks to Philip Koopman for breaking the tie in favor of
the latter (#xC07).
@end defvr

@defvr Constant crc-10-polynomial

http://www.math.grin.edu/~rebelsky/Courses/CS364/2000S/Outlines/outline.12.html gives
CRC-10: x^10+x^9+x^5+x^4+1;
but
http://cell-relay.indiana.edu/cell-relay/publications/software/CRC/crc10.html,
http://www.it.iitb.ac.in/it605/lectures/link/node4.html,
http://www.gpfn.sk.ca/~rhg/csc8550s02/crc.html,
http://www.techfest.com/networking/atm/atm.htm,
http://www.protocols.com/pbook/atmcell2.htm, and
http://www.nobugconsulting.ro/crc.php give
CRC-10: x^10+x^9+x^5+x^4+x+1.
@end defvr

@defvr Constant crc-08-polynomial

http://www.math.grin.edu/~rebelsky/Courses/CS364/2000S/Outlines/outline.12.html,
http://www.cs.ncl.ac.uk/people/harry.whitfield/home.formal/CRCs.html,
http://www.it.iitb.ac.in/it605/lectures/link/node4.html, and
http://www.nobugconsulting.ro/crc.php give
CRC-8: x^8+x^2+x^1+1
@end defvr

@defvr Constant atm-hec-polynomial

http://cell-relay.indiana.edu/cell-relay/publications/software/CRC/32bitCRC.tutorial.html and
http://www.gpfn.sk.ca/~rhg/csc8550s02/crc.html give
ATM HEC: x^8+x^2+x+1.
@end defvr

@defvr Constant dowcrc-polynomial

http://www.cs.ncl.ac.uk/people/harry.whitfield/home.formal/CRCs.html gives
DOWCRC: x^8+x^5+x^4+1.
@end defvr

@defvr Constant usb-token-polynomial

http://www.usb.org/developers/data/crcdes.pdf and
http://www.nobugconsulting.ro/crc.php give
USB-token: x^5+x^2+1.
@end defvr

@noindent
Each of these polynomial constants is a string of @samp{1}s and
@samp{0}s, the exponent of each power of @var{x} in descending order.

@defun crc:make-table poly

@var{poly} must be string of @samp{1}s and @samp{0}s beginning with
@samp{1} and having length greater than 8.  @code{crc:make-table}
returns a vector of 256 integers, such that:

@example
(set! @var{crc}
      (logxor (ash (logand (+ -1 (ash 1 (- @var{deg} 8))) @var{crc}) 8)
              (vector-ref @var{crc-table}
                          (logxor (ash @var{crc} (- 8 @var{deg})) @var{byte}))))
@end example

will compute the @var{crc} with the 8 additional bits in @var{byte};
where @var{crc} is the previous accumulated CRC value, @var{deg} is
the degree of @var{poly}, and @var{crc-table} is the vector returned
by @code{crc:make-table}.

If the implementation does not support @var{deg}-bit integers, then
@code{crc:make-table} returns #f.

@end defun


@defun cksum file

Computes the P1003.2/D11.2 (POSIX.2) 32-bit checksum of @var{file}.

@example
(require 'crc)
@ftindex crc
(cksum (in-vicinity (library-vicinity) "ratize.scm"))
@result{} 157103930
@end example

@defunx cksum port
Computes the checksum of the bytes read from @var{port} until the
end-of-file.

@end defun

@noindent
@cindex cksum-string
@code{cksum-string}, which returns the P1003.2/D11.2 (POSIX.2) 32-bit
checksum of the bytes in @var{str}, can be defined as follows:

@example
(require 'string-port)
(define (cksum-string str) (call-with-input-string str cksum))
@end example

@defun crc16 file

Computes the USB data-packet (16-bit) CRC of @var{file}.

@defunx crc16 port
Computes the USB data-packet (16-bit) CRC of the bytes read from
@var{port} until the end-of-file.

@code{crc16} calculates the same values as the crc16.pl program given
in http://www.usb.org/developers/data/crcdes.pdf.

@end defun

@defun crc5 file

Computes the USB token (5-bit) CRC of @var{file}.

@defunx crc5 port
Computes the USB token (5-bit) CRC of the bytes read from
@var{port} until the end-of-file.

@code{crc5} calculates the same values as the crc5.pl program given
in http://www.usb.org/developers/data/crcdes.pdf.

@end defun

@node Graphing, Solid Modeling, Cyclic Checksum, Mathematical Packages
@section Graphing

@menu
* Character Plotting::          
* PostScript Graphing::         
@end menu

@node Character Plotting, PostScript Graphing, Graphing, Graphing
@subsection Character Plotting

@code{(require 'charplot)}
@ftindex charplot

@defvar charplot:dimensions
A list of the maximum height (number of lines) and maximum width (number
of columns) for the graph, its scales, and labels.

The default value for @var{charplot:dimensions} is the
@code{output-port-height} and @code{output-port-width} of
@code{current-output-port}.
@end defvar

@deffn {Procedure} plot coords x-label y-label
@var{coords} is a list or vector of coordinates, lists of x and y
coordinates.  @var{x-label} and @var{y-label} are strings with which to
label the x and y axes.

Example:
@example
(require 'charplot)
@ftindex charplot
(set! charplot:dimensions '(20 55))

(define (make-points n)
  (if (zero? n)
      '()
      (cons (list (/ n 6) (sin (/ n 6))) (make-points (1- n)))))

(plot (make-points 40) "x" "Sin(x)")
@print{}
@group
  Sin(x)   _________________________________________
         1|-       ****                             |
          |      **    **                           |
      0.75|-    *        *                          |
          |    *          *                         |
       0.5|-  *            *                        |
          |  *                                     *|
      0.25|-                *                     * |
          | *                *                      |
         0|-------------------*------------------*--|
          |                                     *   |
     -0.25|-                   *               *    |
          |                     *             *     |
      -0.5|-                     *                  |
          |                       *          *      |
     -0.75|-                       *        *       |
          |                         **    **        |
        -1|-                          ****          |
          |:_____._____:_____._____:_____._____:____|
     x                 2           4           6
@end group
@end example
@end deffn

@deffn {Procedure} plot func x1 x2
@deffnx {Procedure} plot func x1 x2 npts
Plots the function of one argument @var{func} over the range @var{x1} to
@var{x2}.  If the optional integer argument @var{npts} is supplied, it
specifies the number of points to evaluate @var{func} at.

@example
(plot sin 0 (* 2 pi))
@print{}
@group
           _________________________________________
         1|-:       ****                            |
          | :     **    **                          |
      0.75|-:    *        *                         |
          | :   *          *                        |
       0.5|-:  **          **                       |
          | : *             *                       |
      0.25|-:**              **                     |
          | :*                *                     |
         0|-*------------------*--------------------|
          | :                  *                 *  |
     -0.25|-:                   **              **  |
          | :                    *             *    |
      -0.5|-:                     *           **    |
          | :                      *          *     |
     -0.75|-:                       *       **      |
          | :                        **    **       |
        -1|-:                          ****         |
          |_:_____._____:_____._____:_____._____:___|
            0           2           4           6
@end group
@end example
@end deffn

@deffn {Procedure} histograph data label
Creates and displays a histogram of the numerical values contained in
vector or list @var{data}

@example
(require 'random-inexact)
(histograph (do ((idx 99 (+ -1 idx))
                 (lst '() (cons (* .02 (random:normal)) lst)))
                ((negative? idx) lst))
            "normal")
@print{}
@group
           _________________________________________
         8|-                :    I                  |
          |                 :    I                  |
         7|-           I  I :    I                  |
          |            I  I :    I                  |
         6|-          III I :I   I                  |
          |           III I :I   I                  |
         5|-          IIIIIIIIII I                  |
          |           IIIIIIIIII I                  |
         4|-          IIIIIIIIIIII                  |
          |           IIIIIIIIIIII                  |
         3|-I    I I  IIIIIIIIIIII  II     I        |
          | I    I I  IIIIIIIIIIII  II     I        |
         2|-I    I I IIIIIIIIIIIIIIIII     I        |
          | I    I I IIIIIIIIIIIIIIIII     I        |
         1|-II I I IIIIIIIIIIIIIIIIIIIII   I I I    |
          | II I I IIIIIIIIIIIIIIIIIIIII   I I I    |
         0|-IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII----|
          |__.____:____.____:____.____:____.____:___|
  normal        -0.025      0       0.025      0.05
@end group
@end example
@end deffn


@node PostScript Graphing,  , Character Plotting, Graphing
@subsection PostScript Graphing

@include grapheps.txi


@node Solid Modeling, Color, Graphing, Mathematical Packages
@section Solid Modeling

@include solid.txi


@node Color, Root Finding, Solid Modeling, Mathematical Packages
@section Color

@ifset html
<A NAME="Color"></A>
@end ifset

@uref{http://swiss.csail.mit.edu/~jaffer/Color}

@noindent
The goals of this package are to provide methods to specify, compute,
and transform colors in a core set of additive color spaces.  The color
spaces supported should be sufficient for working with the color data
encountered in practice and the literature.

@menu
* Color Data-Type::             'color
* Color Spaces::                XYZ, L*a*b*, L*u*v*, L*C*h, RGB709, sRGB
* Spectra::                     Color Temperatures and CIEXYZ(1931)
* Color Difference Metrics::    Society of Dyers and Colorists
* Color Conversions::           Low-level
* Color Names::                 in relational databases
* Daylight::                    Sunlight and sky colors
@end menu

@node Color Data-Type, Color Spaces, Color, Color
@subsection Color Data-Type

@ifset html
<A NAME="Color_Data-Type"></A>
@end ifset
@code{(require 'color)}

@defun color? obj
Returns #t if @var{obj} is a color.

@defunx color? obj typ
Returns #t if @var{obj} is a color of color-space @var{typ}.  The symbol
@var{typ} must be one of:

@itemize @bullet
@item
CIEXYZ
@item
RGB709
@item
L*a*b*
@item
L*u*v*
@item
sRGB
@item
e-sRGB
@item
L*C*h
@end itemize
@end defun

@defun make-color space arg @dots{}
Returns a color of type @var{space}.

@itemize @bullet
@item
For @var{space} arguments @code{CIEXYZ}, @code{RGB709}, and
@code{sRGB}, the sole @var{arg} is a list of three numbers.
@item
For @var{space} arguments @code{L*a*b*}, @code{L*u*v*}, and
@code{L*C*h}, @var{arg} is a list of three numbers optionally followed
by a whitepoint.
@item
For @code{xRGB}, @var{arg} is an integer.
@item
For @code{e-sRGB}, the arguments are as for @code{e-sRGB->color}.
@end itemize
@end defun

@defun color-space color
Returns the symbol for the color-space in which @var{color} is embedded.
@end defun

@defun color-precision color
For colors in digital color-spaces, @code{color-precision} returns the
number of bits used for each of the R, G, and B channels of the
encoding.  Otherwise, @code{color-precision} returns #f
@end defun

@defun color-white-point color
Returns the white-point of @var{color} in all color-spaces except CIEXYZ.
@end defun

@defun convert-color color space white-point
@defunx convert-color color space
@defunx convert-color color e-sRGB precision
Converts @var{color} into @var{space} at optional @var{white-point}.
@end defun

@subsubsection External Representation

@noindent
Each color encoding has an external, case-insensitive representation.
To ensure portability, the white-point for all color strings is D65.
@footnote{Readers may recognize these color string formats from Xlib.
X11's color management system was doomed by its fiction that CRT
monitors' (and X11 default) color-spaces were linear RGBi.  Unable to
shed this legacy, the only practical way to view pictures on X is to
ignore its color management system and use an sRGB monitor.  In this
implementation the device-independent RGB709 and sRGB spaces replace the
device-dependent RGBi and RGB spaces of Xlib.}

@multitable @columnfractions .33 .66
@item Color Space
@tab External Representation
@item CIEXYZ
@tab CIEXYZ:@i{<X>}/@i{<Y>}/@i{<Z>}
@item RGB709
@tab RGBi:@i{<R>}/@i{<G>}/@i{<B>}
@item L*a*b*
@tab CIELAB:@i{<L>}/@i{<a>}/@i{<b>}
@item L*u*v*
@tab CIELuv:@i{<L>}/@i{<u>}/@i{<v>}
@item L*C*h
@tab CIELCh:@i{<L>}/@i{<C>}/@i{<h>}
@end multitable

@noindent
The @var{X}, @var{Y}, @var{Z}, @var{L}, @var{a}, @var{b}, @var{u},
@var{v}, @var{C}, @var{h}, @var{R}, @var{G}, and @var{B} fields are
(Scheme) real numbers within the appropriate ranges.

@multitable @columnfractions .33 .66
@item Color Space
@tab External Representation
@item sRGB
@tab sRGB:@i{<R>}/@i{<G>}/@i{<B>}
@item e-sRGB10
@tab e-sRGB10:@i{<R>}/@i{<G>}/@i{<B>}
@item e-sRGB12
@tab e-sRGB12:@i{<R>}/@i{<G>}/@i{<B>}
@item e-sRGB16
@tab e-sRGB16:@i{<R>}/@i{<G>}/@i{<B>}
@end multitable

@noindent
The @var{R}, @var{G}, and @var{B}, fields are non-negative exact decimal
integers within the appropriate ranges.

@noindent
Several additional syntaxes are supported by @code{string->color}:

@multitable @columnfractions .33 .66
@item Color Space
@tab External Representation
@item sRGB
@tab sRGB:@i{<RRGGBB>}
@item sRGB
@tab #@i{<RRGGBB>}
@item sRGB
@tab 0x@i{<RRGGBB>}
@item sRGB
@tab #x@i{<RRGGBB>}
@end multitable

Where @var{RRGGBB} is a non-negative six-digit hexadecimal number.

@defun color->string color
Returns a string representation of @var{color}.
@end defun

@defun string->color string
Returns the color represented by @var{string}.  If @var{string} is not a
syntactically valid notation for a color, then @code{string->color}
returns #f.
@end defun

@subsubsection White

@noindent
We experience color relative to the illumination around us.
CIEXYZ coordinates, although subject to uniform scaling, are
objective.  Thus other color spaces are specified relative to a
@cindex white point
@dfn{white point} in CIEXYZ coordinates.
@cindex white point

@noindent
The white point for digital color spaces is set to D65.  For the other
spaces a @var{white-point} argument can be specified.  The default if
none is specified is the white-point with which the color was created
or last converted; and D65 if none has been specified.

@defvr Constant D65
Is the color of 6500.K (blackbody) illumination.  D65 is close
to the average color of daylight.
@end defvr

@defvr Constant D50
Is the color of 5000.K (blackbody) illumination.  D50 is the color of
indoor lighting by incandescent bulbs, whose filaments have
temperatures around 5000.K.
@end defvr


@node Color Spaces, Spectra, Color Data-Type, Color
@subsection Color Spaces

@ifset html
<A NAME="Color_Spaces"></A>
@end ifset
@include color.txi



@node Spectra, Color Difference Metrics, Color Spaces, Color
@subsection Spectra

@ifset html
<A NAME="Spectra"></A>
@end ifset
@noindent
The following functions compute colors from spectra, scale color
luminance, and extract chromaticity.  XYZ is used in the names of
procedures for unnormalized colors; the coordinates of CIEXYZ colors are
constrained as described in @ref{Color Spaces}.

@code{(require 'color-space)}

@noindent
A spectrum may be represented as:

@itemize @bullet
@item
A procedure of one argument accepting real numbers from 380e-9 to
780e-9, the wavelength in meters; or
@item
A vector of real numbers representing intensity samples evenly spaced
over some range of wavelengths overlapping the range 380e-9 to 780e-9.
@end itemize

@noindent
CIEXYZ values are calculated as dot-product with the X, Y (Luminance),
and Z @dfn{Spectral Tristimulus Values}.  The files @file{cie1931.xyz}
and @file{cie1964.xyz} in the distribution contain these CIE-defined
values.
@cindex Spectral Tristimulus Values

@deftp {Feature} cie1964
@ftindex cie1964
Loads the Spectral Tristimulus Values defining @cite{CIE 1964
Supplementary Standard Colorimetric Observer}.
@deftpx {Feature} cie1931
@ftindex cie1931
Loads the Spectral Tristimulus Values defining @cite{CIE 1931
Supplementary Standard Colorimetric Observer}.
@deftpx {Feature} ciexyz
@ftindex ciexyz
Requires Spectral Tristimulus Values, defaulting to cie1931.
@end deftp

@noindent
@code{(require 'cie1964)} or @code{(require 'cie1931)} will
@findex load-ciexyz
@code{load-ciexyz} specific values used by the following spectrum
conversion procedures.  The spectrum conversion procedures
@code{(require 'ciexyz)} to assure that a set is loaded.

@defun read-cie-illuminant path
@var{path} must be a string naming a file consisting of 107 numbers
for 5.nm intervals from 300.nm to 830.nm.  @code{read-cie-illuminant}
reads (using Scheme @code{read}) these numbers and returns a length
107 vector filled with them.
@end defun

@example
(define CIE:SI-D65
  (read-CIE-illuminant (in-vicinity (library-vicinity) "ciesid65.dat")))
(spectrum->XYZ CIE:SI-D65 300e-9 830e-9)
@result{} (25.108569422374994 26.418013465625001 28.764075683374993)
@end example


@defun read-normalized-illuminant path
@var{path} must be a string naming a file consisting of 107 numbers
for 5.nm intervals from 300.nm to 830.nm.
@code{read-normalized-illuminant} reads (using Scheme @code{read})
these numbers and returns a length 107 vector filled with them,
normalized so that @code{spectrum->XYZ} of the illuminant returns its
whitepoint.
@end defun

CIE Standard Illuminants A and D65 are included with SLIB:

@example
(define CIE:SI-A
  (read-normalized-illuminant (in-vicinity (library-vicinity) "ciesia.dat")))
(define CIE:SI-D65
  (read-normalized-illuminant (in-vicinity (library-vicinity) "ciesid65.dat")))
(spectrum->XYZ CIE:SI-A 300e-9 830e-9)
@result{} (1.098499460820401 999.9999999999998e-3 355.8173930654951e-3)
(CIEXYZ->sRGB (spectrum->XYZ CIE:SI-A 300e-9 830e-9))
@result{} (255 234 133)
(spectrum->XYZ CIE:SI-D65 300e-9 830e-9)
@result{} (950.4336673552745e-3 1.0000000000000002 1.0888053986649182)
(CIEXYZ->sRGB (spectrum->XYZ CIE:SI-D65 300e-9 830e-9))
@result{} (255 255 255)
@end example

@defun illuminant-map proc siv
@var{siv} must be a one-dimensional array or vector of 107 numbers.
@code{illuminant-map} returns a vector of length 107 containing the
result of applying @var{proc} to each element of @var{siv}.
@end defun

@defun illuminant-map->XYZ proc siv
@code{(spectrum->XYZ (illuminant-map @var{proc} @var{siv}) 300e-9 830e-9)}
@end defun

@defun spectrum->XYZ proc
@var{proc} must be a function of one argument.  @code{spectrum->XYZ}
computes the CIEXYZ(1931) values for the spectrum returned by @var{proc}
when called with arguments from 380e-9 to 780e-9, the wavelength in
meters.

@defunx spectrum->XYZ spectrum x1 x2
@var{x1} and @var{x2} must be positive real numbers specifying the
wavelengths (in meters) corresponding to the zeroth and last elements of
vector or list @var{spectrum}.  @code{spectrum->XYZ} returns the
CIEXYZ(1931) values for a light source with spectral values proportional
to the elements of @var{spectrum} at evenly spaced wavelengths between
@var{x1} and @var{x2}.

Compute the colors of 6500.K and 5000.K blackbody radiation:

@example
(require 'color-space)
(define xyz (spectrum->XYZ (blackbody-spectrum 6500)))
(define y_n (cadr xyz))
(map (lambda (x) (/ x y_n)) xyz)
    @result{} (0.9687111145512467 1.0 1.1210875945303613)

(define xyz (spectrum->XYZ (blackbody-spectrum 5000)))
(map (lambda (x) (/ x y_n)) xyz)
    @result{} (0.2933441826889158 0.2988931825387761 0.25783646831201573)
@end example
@end defun

@defun spectrum->chromaticity proc
@defunx spectrum->chromaticity spectrum x1 x2
Computes the chromaticity for the given spectrum.
@end defun

@defun wavelength->XYZ w
@var{w} must be a number between 380e-9 to 780e-9.
@code{wavelength->XYZ} returns (unnormalized) XYZ values for a
monochromatic light source with wavelength @var{w}.
@end defun

@defun wavelength->chromaticity w
@var{w} must be a number between 380e-9 to 780e-9.
@code{wavelength->chromaticity} returns the chromaticity for a
monochromatic light source with wavelength @var{w}.
@end defun

@defun blackbody-spectrum temp
@defunx blackbody-spectrum temp span
Returns a procedure of one argument (wavelength in meters), which
returns the radiance of a black body at @var{temp}.

The optional argument @var{span} is the wavelength analog of bandwidth.
With the default @var{span} of 1.nm (1e-9.m), the values returned by the
procedure correspond to the power of the photons with wavelengths
@var{w} to @var{w}+1e-9.
@end defun

@defun temperature->XYZ x
The positive number @var{x} is a temperature in degrees kelvin.
@code{temperature->XYZ} computes the unnormalized CIEXYZ(1931) values
for the spectrum of a black body at temperature @var{x}.

Compute the chromaticities of 6500.K and 5000.K blackbody radiation:

@example
(require 'color-space)
(XYZ->chromaticity (temperature->XYZ 6500))
    @result{} (0.3135191660557008 0.3236456786200268)

(XYZ->chromaticity (temperature->XYZ 5000))
    @result{} (0.34508082841161052 0.3516084965163377)
@end example
@end defun

@defun temperature->chromaticity x
The positive number @var{x} is a temperature in degrees kelvin.
@code{temperature->cromaticity} computes the chromaticity for the
spectrum of a black body at temperature @var{x}.

Compute the chromaticities of 6500.K and 5000.K blackbody radiation:

@example
(require 'color-space)
(temperature->chromaticity 6500)
    @result{} (0.3135191660557008 0.3236456786200268)

(temperature->chromaticity 5000)
    @result{} (0.34508082841161052 0.3516084965163377)
@end example
@end defun

@defun XYZ->chromaticity xyz
Returns a two element list: the x and y components of @var{xyz}
normalized to 1 (= @var{x} + @var{y} + @var{z}).
@end defun

@defun chromaticity->CIEXYZ x y
Returns the list of @var{x}, and @var{y}, 1 - @var{y} - @var{x}.
@end defun

@defun chromaticity->whitepoint x y
Returns the CIEXYZ(1931) values having luminosity 1 and chromaticity
@var{x} and @var{y}.
@end defun

@cindex xyY
@noindent
Many color datasets are expressed in @dfn{xyY} format; chromaticity with
CIE luminance (Y).  But xyY is not a CIE standard like CIEXYZ, CIELAB,
and CIELUV.  Although chrominance is well defined, the luminance
component is sometimes scaled to 1, sometimes to 100, but usually has no
obvious range.  With no given whitepoint, the only reasonable course is
to ascertain the luminance range of a dataset and normalize the values
to lie from 0 to 1.

@defun XYZ->xyY xyz
Returns a three element list: the @var{x} and @var{y} components of
@var{XYZ} normalized to 1, and CIE luminance @var{Y}.
@end defun

@defun xyY->XYZ xyY
@end defun

@defun xyY:normalize-colors colors
@var{colors} is a list of xyY triples.  @code{xyY:normalize-colors}
scales each chromaticity so it sums to 1 or less; and divides the
@var{Y} values by the maximum @var{Y} in the dataset, so all lie between
0 and 1.

@defunx xyY:normalize-colors colors n
If @var{n} is positive real, then @code{xyY:normalize-colors} divides
the @var{Y} values by @var{n} times the maximum @var{Y} in the dataset.

If @var{n} is an exact non-positive integer, then
@code{xyY:normalize-colors} divides the @var{Y} values by the maximum of
the @var{Y}s in the dataset excepting the -@var{n} largest @var{Y}
values.

In all cases, returned @var{Y} values are limited to lie from 0 to 1.
@end defun

@noindent
Why would one want to normalize to other than 1?  If the sun or its
reflection is the brightest object in a scene, then normalizing to its
luminance will tend to make the rest of the scene very dark.  As with
photographs, limiting the specular highlights looks better than
darkening everything else.

@noindent
The results of measurements being what they are,
@code{xyY:normalize-colors} is extremely tolerant.  Negative numbers are
replaced with zero, and chromaticities with sums greater than one are
scaled to sum to one.


@node Color Difference Metrics, Color Conversions, Spectra, Color
@subsection Color Difference Metrics

@ifset html
<A NAME="Color_Difference_Metrics"></A>
@end ifset

@code{(require 'color-space)}

The low-level metric functions operate on lists of 3 numbers, lab1,
lab2, lch1, or lch2.

@code{(require 'color)}

The wrapped functions operate on objects of type color, color1 and
color2 in the function entries.

@defun L*a*b*:DE* lab1 lab2
Returns the Euclidean distance between @var{lab1} and @var{lab2}.

@defunx CIE:DE* color1 color2 white-point
@defunx CIE:DE* color1 color2
Returns the Euclidean distance in L*a*b* space between @var{color1} and
@var{color2}.
@end defun


@defun L*C*h:DE*94 lch1 lch2 parametric-factors
@defunx L*C*h:DE*94 lch1 lch2

@defunx CIE:DE*94 color1 color2 parametric-factors
@defunx CIE:DE*94 color1 color2

Measures distance in the L*C*h cylindrical color-space.
The three axes are individually scaled (depending on C*) in their
contributions to the total distance.

The CIE has defined reference conditions under which the metric with
default parameters can be expected to perform well.  These are:

@itemize @bullet
@item
The specimens are homogeneous in colour.
@item
The colour difference (CIELAB) is <= 5 units.
@item
They are placed in direct edge contact.
@item
Each specimen subtends an angle of >4 degrees to the assessor, whose
colour vision is normal.
@item
They are illuminated at 1000 lux, and viewed against a background of
uniform grey, with L* of 50, under illumination simulating D65.
@end itemize

The @var{parametric-factors} argument is a list of 3 quantities kL, kC
and kH.  @var{parametric-factors} independently adjust each
colour-difference term to account for any deviations from the reference
viewing conditions.  Under the reference conditions explained above, the
default is kL = kC = kH = 1.
@end defun


@noindent
The Color Measurement Committee of The Society of Dyers and Colorists in
Great Britain created a more sophisticated color-distance function for
use in judging the consistency of dye lots.  With CMC:DE* it is possible
to use a single value pass/fail tolerance for all shades.

@defun CMC-DE lch1 lch2 parametric-factors
@defunx CMC-DE lch1 lch2 l c
@defunx CMC-DE lch1 lch2 l
@defunx CMC-DE lch1 lch2

@defunx CMC:DE* color1 color2 l c
@defunx CMC:DE* color1 color2

@code{CMC:DE} is a L*C*h metric.  The @var{parametric-factors}
argument is a list of 2 numbers @var{l} and @var{c}.  @var{l} and
@var{c} parameterize this metric.  1 and 1 are recommended for
perceptibility; the default, 2 and 1, for acceptability.
@end defun



@node Color Conversions, Color Names, Color Difference Metrics, Color
@subsection Color Conversions

@ifset html
<A NAME="Color_Conversions"></A>
@end ifset

@noindent
This package contains the low-level color conversion and color metric
routines operating on lists of 3 numbers.  There is no type or range
checking.

@code{(require 'color-space)}

@defvr Constant CIEXYZ:D65
Is the color of 6500.K (blackbody) illumination.  D65 is close to the
average color of daylight.
@end defvr

@defvr Constant CIEXYZ:D50
Is the color of 5000.K (blackbody) illumination.  D50 is the color of
indoor lighting by incandescent bulbs.
@end defvr

@defvr Constant CIEXYZ:A
@defvrx Constant CIEXYZ:B
@defvrx Constant CIEXYZ:C
@defvrx Constant CIEXYZ:E
CIE 1931 illuminants normalized to 1 = y.
@end defvr

@defun color:linear-transform matrix row
@end defun

@defun CIEXYZ->RGB709 xyz
@defunx RGB709->CIEXYZ srgb
@end defun

@defun CIEXYZ->L*u*v* xyz white-point
@defunx CIEXYZ->L*u*v* xyz
@defunx L*u*v*->CIEXYZ L*u*v* white-point
@defunx L*u*v*->CIEXYZ L*u*v*
The @var{white-point} defaults to CIEXYZ:D65.
@end defun

@defun CIEXYZ->L*a*b* xyz white-point
@defunx CIEXYZ->L*a*b* xyz
@defunx L*a*b*->CIEXYZ L*a*b* white-point
@defunx L*a*b*->CIEXYZ L*a*b*
The XYZ @var{white-point} defaults to CIEXYZ:D65.
@end defun

@defun L*a*b*->L*C*h L*a*b*
@defunx L*C*h->L*a*b* L*C*h
@end defun

@defun CIEXYZ->sRGB xyz
@defunx sRGB->CIEXYZ srgb
@end defun

@defun CIEXYZ->xRGB xyz
@defunx xRGB->CIEXYZ srgb
@end defun

@defun sRGB->xRGB xyz
@defunx xRGB->sRGB srgb
@end defun

@defun CIEXYZ->e-sRGB n xyz
@defunx e-sRGB->CIEXYZ n srgb
@end defun

@defun sRGB->e-sRGB n srgb
@defunx e-sRGB->sRGB n srgb
The integer @var{n} must be 10, 12, or 16.  Because sRGB and e-sRGB use
the same RGB709 chromaticities, conversion between them is simpler than
conversion through CIEXYZ.
@end defun

@noindent
Do not convert e-sRGB precision through @code{e-sRGB->sRGB} then
@code{sRGB->e-sRGB} -- values would be truncated to 8-bits!

@defun e-sRGB->e-sRGB n1 srgb n2
The integers @var{n1} and @var{n2} must be 10, 12, or 16.
@code{e-sRGB->e-sRGB} converts @var{srgb} to e-sRGB of precision
@var{n2}.
@end defun



@node Color Names, Daylight, Color Conversions, Color
@subsection Color Names

@ifset html
<A NAME="Color_Names"></A>
@end ifset
@include colornam.txi

@include mkclrnam.txi

@subsubheading The Short List

@code{(require 'saturate)}
@ftindex saturate

@defun saturate name
Looks for @var{name} among the 19 saturated colors from
@cite{Approximate Colors on CIE Chromaticity Diagram}:

@multitable @columnfractions .25 .25 .25 .25
@item reddish orange  @tab orange        @tab yellowish orange @tab yellow
@item greenish yellow @tab yellow green  @tab yellowish green  @tab green
@item bluish green    @tab blue green    @tab greenish blue    @tab blue
@item purplish blue   @tab bluish purple @tab purple           @tab reddish purple
@item red purple      @tab purplish red  @tab red
@end multitable

(@url{http://swiss.csail.mit.edu/~jaffer/Color/saturate.pdf}).  If
@var{name} is found, the corresponding color is returned.  Otherwise #f
is returned.  Use saturate only for light source colors.
@end defun


@noindent
Resene Paints Limited, New Zealand's largest privately-owned and
operated paint manufacturing company, has generously made their
@cite{Resene RGB Values List} available.

@code{(require 'resene)}
@ftindex resene

@defun resene name
Looks for @var{name} among the 1300 entries in the Resene color-name
dictionary (@url{http://swiss.csail.mit.edu/~jaffer/Color/resene.pdf}).
If @var{name} is found, the corresponding color is returned.  Otherwise
#f is returned.  The @cite{Resene RGB Values List} is an excellent
source for surface colors.
@end defun

@noindent
If you include the @dfn{Resene RGB Values List} in binary form in a
program, then you must include its license with your program:

@quotation
Resene RGB Values List@*
For further information refer to http://www.resene.co.nz@*
Copyright Resene Paints Ltd 2001

Permission to copy this dictionary, to modify it, to redistribute it,
to distribute modified versions, and to use it for any purpose is
granted, subject to the following restrictions and understandings.

@enumerate
@item
Any text copy made of this dictionary must include this copyright
notice in full.

@item
Any redistribution in binary form must reproduce this copyright
notice in the documentation or other materials provided with the
distribution.

@item
Resene Paints Ltd makes no warranty or representation that this
dictionary is error-free, and is under no obligation to provide any
services, by way of maintenance, update, or otherwise.

@item
There shall be no use of the name of Resene or Resene Paints Ltd
in any advertising, promotional, or sales literature without prior
written consent in each case.

@item
These RGB colour formulations may not be used to the detriment of
Resene Paints Ltd.
@end enumerate
@end quotation


@node Daylight,  , Color Names, Color
@subsection Daylight

@ifset html
<A NAME="Daylight"></A>
@end ifset
@include daylight.txi



@node Root Finding, Minimizing, Color, Mathematical Packages
@section Root Finding

@code{(require 'root)}
@ftindex root

@defun integer-sqrt y
Given a non-negative integer @var{y}, returns the largest integer
whose square is less than or equal to @var{y}.
@end defun

@defun newton:find-integer-root f df/dx x0
Given integer valued procedure @var{f}, its derivative (with respect to
its argument) @var{df/dx}, and initial integer value @var{x0} for which
@var{df/dx}(@var{x0}) is non-zero, returns an integer @var{x} for which
@var{f}(@var{x}) is closer to zero than either of the integers adjacent
to @var{x}; or returns @code{#f} if such an integer can't be found.

To find the closest integer to a given integer's square root:

@example
(define (integer-sqrt y)
  (newton:find-integer-root
   (lambda (x) (- (* x x) y))
   (lambda (x) (* 2 x))
   (ash 1 (quotient (integer-length y) 2))))

(integer-sqrt 15) @result{} 4
@end example
@end defun

@defun newton:find-root f df/dx x0 prec
Given real valued procedures @var{f}, @var{df/dx} of one (real)
argument, initial real value @var{x0} for which @var{df/dx}(@var{x0}) is
non-zero, and positive real number @var{prec}, returns a real @var{x}
for which @code{abs}(@var{f}(@var{x})) is less than @var{prec}; or
returns @code{#f} if such a real can't be found.

If @var{prec} is instead a negative integer, @code{newton:find-root}
returns the result of -@var{prec} iterations.
@end defun

@noindent
H. J. Orchard, @cite{The Laguerre Method for Finding the Zeros of
Polynomials}, IEEE Transactions on Circuits and Systems, Vol. 36,
No. 11, November 1989, pp 1377-1381.

@quotation
There are 2 errors in Orchard's Table II.  Line k=2 for starting
value of 1000+j0 should have Z_k of 1.0475 + j4.1036 and line k=2
for starting value of 0+j1000 should have Z_k of 1.0988 + j4.0833.
@end quotation


@defun laguerre:find-root f df/dz ddf/dz^2 z0 prec
Given complex valued procedure @var{f} of one (complex) argument, its
derivative (with respect to its argument) @var{df/dx}, its second
derivative @var{ddf/dz^2}, initial complex value @var{z0}, and positive
real number @var{prec}, returns a complex number @var{z} for which
@code{magnitude}(@var{f}(@var{z})) is less than @var{prec}; or returns
@code{#f} if such a number can't be found.

If @var{prec} is instead a negative integer, @code{laguerre:find-root}
returns the result of -@var{prec} iterations.
@end defun

@defun laguerre:find-polynomial-root deg f df/dz ddf/dz^2 z0 prec
Given polynomial procedure @var{f} of integer degree @var{deg} of one
argument, its derivative (with respect to its argument) @var{df/dx}, its
second derivative @var{ddf/dz^2}, initial complex value @var{z0}, and
positive real number @var{prec}, returns a complex number @var{z} for
which @code{magnitude}(@var{f}(@var{z})) is less than @var{prec}; or
returns @code{#f} if such a number can't be found.

If @var{prec} is instead a negative integer,
@code{laguerre:find-polynomial-root} returns the result of -@var{prec}
iterations.
@end defun

@defun secant:find-root f x0 x1 prec
@defunx secant:find-bracketed-root f x0 x1 prec
Given a real valued procedure @var{f} and two real valued starting
points @var{x0} and @var{x1}, returns a real @var{x} for which
@code{(abs (f x))} is less than @var{prec}; or returns
@code{#f} if such a real can't be found.

If @var{x0} and @var{x1} are chosen such that they bracket a root, that is
@example
(or (< (f x0) 0 (f x1))
    (< (f x1) 0 (f x0)))
@end example
then the root returned will be between @var{x0} and @var{x1}, and
@var{f} will not be passed an argument outside of that interval.

@code{secant:find-bracketed-root} will return @code{#f} unless @var{x0}
and @var{x1} bracket a root.

The secant method is used until a bracketing interval is found, at which point
a modified @i{regula falsi} method is used.

If @var{prec} is instead a negative integer, @code{secant:find-root}
returns the result of -@var{prec} iterations.

If @var{prec} is a procedure it should accept 5 arguments: @var{x0}
@var{f0} @var{x1} @var{f1} and @var{count}, where @var{f0} will be
@code{(f x0)}, @var{f1} @code{(f x1)}, and @var{count} the number of
iterations performed so far.  @var{prec} should return non-false
if the iteration should be stopped.
@end defun

@node Minimizing, The Limit, Root Finding, Mathematical Packages
@section Minimizing

@code{(require 'minimize)}
@ftindex minimize
@cindex minimize

@include minimize.txi

@node The Limit, Commutative Rings, Minimizing, Mathematical Packages
@section The Limit

@include limit.texi


@node Commutative Rings, Matrix Algebra, The Limit, Mathematical Packages
@section Commutative Rings

Scheme provides a consistent and capable set of numeric functions.
Inexacts implement a field; integers a commutative ring (and Euclidean
domain).  This package allows one to use basic Scheme numeric functions
with symbols and non-numeric elements of commutative rings.

@code{(require 'commutative-ring)}
@ftindex commutative-ring
@cindex ring, commutative

The @dfn{commutative-ring} package makes the procedures @code{+},
@code{-}, @code{*}, @code{/}, and @code{^} @dfn{careful} in the sense
@cindex careful
that any non-numeric arguments they do not reduce appear in the
expression output.  In order to see what working with this package is
like, self-set all the single letter identifiers (to their corresponding
symbols).
@cindex self-set

@example
(define a 'a)
@dots{}
(define z 'z)
@end example

Or just @code{(require 'self-set)}.  Now try some sample expressions:
@ftindex self-set

@example
(+ (+ a b) (- a b)) @result{} (* a 2)
(* (+ a b) (+ a b)) @result{} (^ (+ a b) 2)
(* (+ a b) (- a b)) @result{} (* (+ a b) (- a b))
(* (- a b) (- a b)) @result{} (^ (- a b) 2)
(* (- a b) (+ a b)) @result{} (* (+ a b) (- a b))
(/ (+ a b) (+ c d)) @result{} (/ (+ a b) (+ c d))
(^ (+ a b) 3) @result{} (^ (+ a b) 3)
(^ (+ a 2) 3) @result{} (^ (+ 2 a) 3)
@end example

Associative rules have been applied and repeated addition and
multiplication converted to multiplication and exponentiation.

We can enable distributive rules, thus expanding to sum of products
form:
@example
(set! *ruleset* (combined-rulesets distribute* distribute/))

(* (+ a b) (+ a b)) @result{} (+ (* 2 a b) (^ a 2) (^ b 2))
(* (+ a b) (- a b)) @result{} (- (^ a 2) (^ b 2))
(* (- a b) (- a b)) @result{} (- (+ (^ a 2) (^ b 2)) (* 2 a b))
(* (- a b) (+ a b)) @result{} (- (^ a 2) (^ b 2))
(/ (+ a b) (+ c d)) @result{} (+ (/ a (+ c d)) (/ b (+ c d)))
(/ (+ a b) (- c d)) @result{} (+ (/ a (- c d)) (/ b (- c d)))
(/ (- a b) (- c d)) @result{} (- (/ a (- c d)) (/ b (- c d)))
(/ (- a b) (+ c d)) @result{} (- (/ a (+ c d)) (/ b (+ c d)))
(^ (+ a b) 3) @result{} (+ (* 3 a (^ b 2)) (* 3 b (^ a 2)) (^ a 3) (^ b 3))
(^ (+ a 2) 3) @result{} (+ 8 (* a 12) (* (^ a 2) 6) (^ a 3))
@end example

Use of this package is not restricted to simple arithmetic expressions:

@example
(require 'determinant)

(determinant '((a b c) (d e f) (g h i))) @result{}
(- (+ (* a e i) (* b f g) (* c d h)) (* a f h) (* b d i) (* c e g))
@end example

Currently, only @code{+}, @code{-}, @code{*}, @code{/}, and @code{^}
support non-numeric elements.  Expressions with @code{-} are converted
to equivalent expressions without @code{-}, so behavior for @code{-} is
not defined separately.  @code{/} expressions are handled similarly.

This list might be extended to include @code{quotient}, @code{modulo},
@code{remainder}, @code{lcm}, and @code{gcd}; but these work only for
the more restrictive Euclidean (Unique Factorization) Domain.
@cindex Unique Factorization
@cindex Euclidean Domain

@section Rules and Rulesets

The @dfn{commutative-ring} package allows control of ring properties
through the use of @dfn{rulesets}.

@defvar *ruleset*
Contains the set of rules currently in effect.  Rules defined by
@code{cring:define-rule} are stored within the value of *ruleset* at the
time @code{cring:define-rule} is called.  If @var{*ruleset*} is
@code{#f}, then no rules apply.
@end defvar

@defun make-ruleset rule1 @dots{}
@defunx make-ruleset name rule1 @dots{}
Returns a new ruleset containing the rules formed by applying
@code{cring:define-rule} to each 4-element list argument @var{rule}.  If
the first argument to @code{make-ruleset} is a symbol, then the database
table created for the new ruleset will be named @var{name}.  Calling
@code{make-ruleset} with no rule arguments creates an empty ruleset.
@end defun

@defun combined-rulesets ruleset1 @dots{}
@defunx combined-rulesets name ruleset1 @dots{}
Returns a new ruleset containing the rules contained in each ruleset
argument @var{ruleset}.  If the first argument to
@code{combined-ruleset} is a symbol, then the database table created for
the new ruleset will be named @var{name}.  Calling
@code{combined-ruleset} with no ruleset arguments creates an empty
ruleset.
@end defun

Two rulesets are defined by this package.

@defvr Constant distribute*
Contains the ruleset to distribute multiplication over addition and
subtraction.
@end defvr

@defvr Constant distribute/
Contains the ruleset to distribute division over addition and
subtraction.

Take care when using both @var{distribute*} and @var{distribute/}
simultaneously.  It is possible to put @code{/} into an infinite loop.
@end defvr

You can specify how sum and product expressions containing non-numeric
elements simplify by specifying the rules for @code{+} or @code{*} for
cases where expressions involving objects reduce to numbers or to
expressions involving different non-numeric elements.

@defun cring:define-rule op sub-op1 sub-op2 reduction
Defines a rule for the case when the operation represented by symbol
@var{op} is applied to lists whose @code{car}s are @var{sub-op1} and
@var{sub-op2}, respectively.  The argument @var{reduction} is a
procedure accepting 2 arguments which will be lists whose @code{car}s
are @var{sub-op1} and @var{sub-op2}.

@defunx cring:define-rule op sub-op1 'identity reduction
Defines a rule for the case when the operation represented by symbol
@var{op} is applied to a list whose @code{car} is @var{sub-op1}, and
some other argument.  @var{Reduction} will be called with the list whose
@code{car} is @var{sub-op1} and some other argument.

If @var{reduction} returns @code{#f}, the reduction has failed and other
reductions will be tried.  If @var{reduction} returns a non-false value,
that value will replace the two arguments in arithmetic (@code{+},
@code{-}, and @code{*}) calculations involving non-numeric elements.

The operations @code{+} and @code{*} are assumed commutative; hence both
orders of arguments to @var{reduction} will be tried if necessary.

The following rule is the definition for distributing @code{*} over
@code{+}.

@example
(cring:define-rule
 '* '+ 'identity
 (lambda (exp1 exp2)
   (apply + (map (lambda (trm) (* trm exp2)) (cdr exp1))))))
@end example
@end defun

@section How to Create a Commutative Ring

The first step in creating your commutative ring is to write procedures
to create elements of the ring.  A non-numeric element of the ring must
be represented as a list whose first element is a symbol or string.
This first element identifies the type of the object.  A convenient and
clear convention is to make the type-identifying element be the same
symbol whose top-level value is the procedure to create it.

@example
(define (n . list1)
  (cond ((and (= 2 (length list1))
              (eq? (car list1) (cadr list1)))
         0)
        ((not (term< (first list1) (last1 list1)))
         (apply n (reverse list1)))
        (else (cons 'n list1))))

(define (s x y) (n x y))

(define (m . list1)
  (cond ((neq? (first list1) (term_min list1))
         (apply m (cyclicrotate list1)))
        ((term< (last1 list1) (cadr list1))
         (apply m (reverse (cyclicrotate list1))))
        (else (cons 'm list1))))
@end example

Define a procedure to multiply 2 non-numeric elements of the ring.
Other multiplicatons are handled automatically.  Objects for which rules
have @emph{not} been defined are not changed.

@example
(define (n*n ni nj)
  (let ((list1 (cdr ni)) (list2 (cdr nj)))
    (cond ((null? (intersection list1 list2)) #f)
          ((and (eq? (last1 list1) (first list2))
                (neq? (first list1) (last1 list2)))
           (apply n (splice list1 list2)))
          ((and (eq? (first list1) (first list2))
                (neq? (last1 list1) (last1 list2)))
           (apply n (splice (reverse list1) list2)))
          ((and (eq? (last1 list1) (last1 list2))
                (neq? (first list1) (first list2)))
           (apply n (splice list1 (reverse list2))))
          ((and (eq? (last1 list1) (first list2))
                (eq? (first list1) (last1 list2)))
           (apply m (cyclicsplice list1 list2)))
          ((and (eq? (first list1) (first list2))
                (eq? (last1 list1) (last1 list2)))
           (apply m (cyclicsplice (reverse list1) list2)))
          (else #f))))
@end example

Test the procedures to see if they work.

@example
;;; where cyclicrotate(list) is cyclic rotation of the list one step
;;; by putting the first element at the end
(define (cyclicrotate list1)
  (append (rest list1) (list (first list1))))
;;; and where term_min(list) is the element of the list which is
;;; first in the term ordering.
(define (term_min list1)
  (car (sort list1 term<)))
(define (term< sym1 sym2)
  (string<? (symbol->string sym1) (symbol->string sym2)))
(define first car)
(define rest cdr)
(define (last1 list1) (car (last-pair list1)))
(define (neq? obj1 obj2) (not (eq? obj1 obj2)))
;;; where splice is the concatenation of list1 and list2 except that their
;;; common element is not repeated.
(define (splice list1 list2)
  (cond ((eq? (last1 list1) (first list2))
         (append list1 (cdr list2)))
        (else (slib:error 'splice list1 list2))))
;;; where cyclicsplice is the result of leaving off the last element of
;;; splice(list1,list2).
(define (cyclicsplice list1 list2)
  (cond ((and (eq? (last1 list1) (first list2))
              (eq? (first list1) (last1 list2)))
         (butlast (splice list1 list2) 1))
        (else (slib:error 'cyclicsplice list1 list2))))

(N*N (S a b) (S a b)) @result{} (m a b)
@end example

Then register the rule for multiplying type N objects by type N objects.

@example
(cring:define-rule '* 'N 'N N*N))
@end example

Now we are ready to compute!

@example
(define (t)
  (define detM
    (+ (* (S g b)
          (+ (* (S f d)
                (- (* (S a f) (S d g)) (* (S a g) (S d f))))
             (* (S f f)
                (- (* (S a g) (S d d)) (* (S a d) (S d g))))
             (* (S f g)
                (- (* (S a d) (S d f)) (* (S a f) (S d d))))))
       (* (S g d)
          (+ (* (S f b)
                (- (* (S a g) (S d f)) (* (S a f) (S d g))))
             (* (S f f)
                (- (* (S a b) (S d g)) (* (S a g) (S d b))))
             (* (S f g)
                (- (* (S a f) (S d b)) (* (S a b) (S d f))))))
       (* (S g f)
          (+ (* (S f b)
                (- (* (S a d) (S d g)) (* (S a g) (S d d))))
             (* (S f d)
                (- (* (S a g) (S d b)) (* (S a b) (S d g))))
             (* (S f g)
                (- (* (S a b) (S d d)) (* (S a d) (S d b))))))
       (* (S g g)
          (+ (* (S f b)
                (- (* (S a f) (S d d)) (* (S a d) (S d f))))
             (* (S f d)
                (- (* (S a b) (S d f)) (* (S a f) (S d b))))
             (* (S f f)
                (- (* (S a d) (S d b)) (* (S a b) (S d d))))))))
  (* (S b e) (S c a) (S e c)
     detM
     ))
(pretty-print (t))
@print{}
(- (+ (m a c e b d f g)
      (m a c e b d g f)
      (m a c e b f d g)
      (m a c e b f g d)
      (m a c e b g d f)
      (m a c e b g f d))
   (* 2 (m a b e c) (m d f g))
   (* (m a c e b d) (m f g))
   (* (m a c e b f) (m d g))
   (* (m a c e b g) (m d f)))
@end example


@node Matrix Algebra,  , Commutative Rings, Mathematical Packages
@section Matrix Algebra

@include determ.txi


@node Database Packages, Other Packages, Mathematical Packages, Top
@chapter Database Packages

@menu
* Relational Database::         'relational-database
* Relational Infrastructure::   
* Weight-Balanced Trees::       'wt-tree
@end menu

@node Relational Database, Relational Infrastructure, Database Packages, Database Packages
@section Relational Database

@code{(require 'relational-database)}
@ftindex relational-database

This package implements a database system inspired by the Relational
Model (@cite{E. F. Codd, A Relational Model of Data for Large Shared
Data Banks}).  An SLIB relational database implementation can be created
from any @ref{Base Table} implementation.

Why relational database?  For motivations and design issues see@*
@uref{http://swiss.csail.mit.edu/~jaffer/DBManifesto.html}.

@menu
* Using Databases::             'databases
* Table Operations::            
* Database Interpolation::      'database-interpolate
* Embedded Commands::           'database-commands
* Database Macros::             'within-database
* Database Browser::            'database-browse
@end menu

@node Using Databases, Table Operations, Relational Database, Relational Database
@subsection Using Databases

@include dbutil.txi



@node Table Operations, Database Interpolation, Using Databases, Relational Database
@subsection Table Operations

@noindent
These are the descriptions of the methods available from an open
relational table.  A method is retrieved from a table by calling
the table with the symbol name of the operation.  For example:

@example
((plat 'get 'processor) 'djgpp) @result{} i386
@end example

@noindent
Some operations described below require primary key arguments.  Primary
keys arguments are denoted @var{key1} @var{key2} @dots{}.  It is an
error to call an operation for a table which takes primary key arguments
with the wrong number of primary keys for that table.

@defop {Operation} {relational-table} get column-name
Returns a procedure of arguments @var{key1} @var{key2} @dots{} which
returns the value for the @var{column-name} column of the row associated
with primary keys @var{key1}, @var{key2} @dots{} if that row exists in
the table, or @code{#f} otherwise.

@example
((plat 'get 'processor) 'djgpp) @result{} i386
((plat 'get 'processor) 'be-os) @result{} #f
@end example
@end defop

@menu
* Single Row Operations::       
* Match-Keys::                  
* Multi-Row Operations::        
* Indexed Sequential Access Methods::  
* Sequential Index Operations::  
* Table Administration::        
@end menu


@node Single Row Operations, Match-Keys, Table Operations, Table Operations
@subsubsection Single Row Operations

@noindent
The term @dfn{row} used below refers to a Scheme list of values (one for
each column) in the order specified in the descriptor (table) for this
table.  Missing values appear as @code{#f}.  Primary keys must not
be missing.

@defop {Operation} {relational-table} row:insert
Adds the row @var{row} to this table.  If a row for the primary key(s)
specified by @var{row} already exists in this table an error is
signaled.  The value returned is unspecified.
@end defop

@example
@group
(define telephone-table-desc
        ((my-database 'create-table) 'telephone-table-desc))
(define ndrp (telephone-table-desc 'row:insert))
(ndrp '(1 #t name #f string))
(ndrp '(2 #f telephone
          (lambda (d)
            (and (string? d) (> (string-length d) 2)
                 (every
                  (lambda (c)
                    (memv c '(#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9
                                  #\+ #\( #\space #\) #\-)))
                  (string->list d))))
          string))
@end group
@end example

@defop {Operation} {relational-table} row:update
Returns a procedure of one argument, @var{row}, which adds the row,
@var{row}, to this table.  If a row for the primary key(s) specified by
@var{row} already exists in this table, it will be overwritten.  The
value returned is unspecified.
@end defop

@defop {Operation} {relational-table} row:retrieve
Returns a procedure of arguments @var{key1} @var{key2} @dots{} which
returns the row associated with primary keys @var{key1}, @var{key2}
@dots{} if it exists, or @code{#f} otherwise.
@end defop

@example
((plat 'row:retrieve) 'linux) @result{} (linux i386 linux gcc)
((plat 'row:retrieve) 'multics) @result{} #f
@end example

@defop {Operation} {relational-table} row:remove
Returns a procedure of arguments @var{key1} @var{key2} @dots{} which
removes and returns the row associated with primary keys @var{key1},
@var{key2} @dots{} if it exists, or @code{#f} otherwise.
@end defop

@defop {Operation} {relational-table} row:delete
Returns a procedure of arguments @var{key1} @var{key2} @dots{} which
deletes the row associated with primary keys @var{key1}, @var{key2}
@dots{} if it exists.  The value returned is unspecified.
@end defop


@node Match-Keys, Multi-Row Operations, Single Row Operations, Table Operations
@subsubsection Match-Keys

@noindent
@cindex match-keys
The (optional) @var{match-key1} @dots{} arguments are used to restrict
actions of a whole-table operation to a subset of that table.  Those
procedures (returned by methods) which accept match-key arguments will
accept any number of match-key arguments between zero and the number of
primary keys in the table.  Any unspecified @var{match-key} arguments
default to @code{#f}.

@noindent
The @var{match-key1} @dots{} restrict the actions of the table command
to those records whose primary keys each satisfy the corresponding
@var{match-key} argument.  The arguments and their actions are:

@quotation
@table @asis
@item @code{#f}
The false value matches any key in the corresponding position.
@item an object of type procedure
This procedure must take a single argument, the key in the corresponding
position.  Any key for which the procedure returns a non-false value is
a match; Any key for which the procedure returns a @code{#f} is not.
@item other values
Any other value matches only those keys @code{equal?} to it.
@end table
@end quotation

@defop {Operation} {relational-table} get* column-name
Returns a procedure of optional arguments @var{match-key1} @dots{} which
returns a list of the values for the specified column for all rows in
this table.  The optional @var{match-key1} @dots{} arguments restrict
actions to a subset of the table.

@example
((plat 'get* 'processor)) @result{}
(i386 i8086 i386 i8086 i386 i386 i8086 m68000
 m68000 m68000 m68000 m68000 powerpc)

((plat 'get* 'processor) #f) @result{}
(i386 i8086 i386 i8086 i386 i386 i8086 m68000
 m68000 m68000 m68000 m68000 powerpc)

(define (a-key? key)
   (char=? #\a (string-ref (symbol->string key) 0)))

((plat 'get* 'processor) a-key?) @result{}
(m68000 m68000 m68000 m68000 m68000 powerpc)

((plat 'get* 'name) a-key?) @result{}
(atari-st-turbo-c atari-st-gcc amiga-sas/c-5.10
 amiga-aztec amiga-dice-c aix)
@end example
@end defop


@node Multi-Row Operations, Indexed Sequential Access Methods, Match-Keys, Table Operations
@subsubsection Multi-Row Operations

@defop {Operation} {relational-table} row:retrieve*
Returns a procedure of optional arguments @var{match-key1} @dots{}
which returns a list of all rows in this table.  The optional
@var{match-key1} @dots{} arguments restrict actions to a subset of the
table.  For details see @xref{Match-Keys}.
@end defop

@example
((plat 'row:retrieve*) a-key?) @result{}
((atari-st-turbo-c m68000 atari turbo-c)
 (atari-st-gcc m68000 atari gcc)
 (amiga-sas/c-5.10 m68000 amiga sas/c)
 (amiga-aztec m68000 amiga aztec)
 (amiga-dice-c m68000 amiga dice-c)
 (aix powerpc aix -))
@end example

@defop {Operation} {relational-table} row:remove*
Returns a procedure of optional arguments @var{match-key1} @dots{} which
removes and returns a list of all rows in this table.  The optional
@var{match-key1} @dots{} arguments restrict actions to a subset of the
table.
@end defop

@defop {Operation} {relational-table} row:delete*
Returns a procedure of optional arguments @var{match-key1} @dots{}
which Deletes all rows from this table.  The optional @var{match-key1}
@dots{} arguments restrict deletions to a subset of the table.  The
value returned is unspecified.  The descriptor table and catalog entry
for this table are not affected.
@end defop

@defop {Operation} {relational-table} for-each-row
Returns a procedure of arguments @var{proc} @var{match-key1} @dots{}
which calls @var{proc} with each @var{row} in this table.  The
optional @var{match-key1} @dots{} arguments restrict actions to a
subset of the table.  For details see @xref{Match-Keys}.
@end defop

@noindent
Note that @code{row:insert*} and @code{row:update*} do @emph{not} use
match-keys.

@defop {Operation} {relational-table} row:insert*
Returns a procedure of one argument, @var{rows}, which adds each row in
the list of rows, @var{rows}, to this table.  If a row for the primary
key specified by an element of @var{rows} already exists in this table,
an error is signaled.  The value returned is unspecified.
@end defop

@defop {Operation} {relational-table} row:update*
Returns a procedure of one argument, @var{rows}, which adds each row in
the list of rows, @var{rows}, to this table.  If a row for the primary
key specified by an element of @var{rows} already exists in this table,
it will be overwritten.  The value returned is unspecified.
@end defop


@node Indexed Sequential Access Methods, Sequential Index Operations, Multi-Row Operations, Table Operations
@subsubsection Indexed Sequential Access Methods

@noindent
@cindex ISAM
@dfn{Indexed Sequential Access Methods} are a way of arranging
database information so that records can be accessed both by key and
by key sequence (ordering).  @dfn{ISAM} is not part of Codd's
relational model.  Hardcore relational programmers might use some
least-upper-bound join for every row to get them into an order.

@noindent
Associative memory in B-Trees is an example of a database
implementation which can support a native key ordering.  SLIB's
@code{alist-table} implementation uses @code{sort} to implement
@code{for-each-row-in-order}, but does not support @code{isam-next}
and @code{isam-prev}.

@noindent
The multi-primary-key ordering employed by these operations is the
lexicographic collation of those primary-key fields in their given
order.  For example:

@example
(12 a 34) < (12 a 36) < (12 b 1) < (13 a 0)
@end example


@node Sequential Index Operations, Table Administration, Indexed Sequential Access Methods, Table Operations
@subsubsection Sequential Index Operations

@noindent
The following procedures are individually optional depending on the
base-table implememtation.  If an operation is @emph{not} supported,
then calling the table with that operation symbol will return false.

@defop {Operation} {relational-table} for-each-row-in-order
Returns a procedure of arguments @var{proc} @var{match-key1} @dots{}
which calls @var{proc} with each @var{row} in this table in the
(implementation-dependent) natural, repeatable ordering for rows.  The
optional @var{match-key1} @dots{} arguments restrict actions to a
subset of the table.  For details see @xref{Match-Keys}.
@end defop

@defop {Operation} {relational-table} isam-next
Returns a procedure of arguments @var{key1} @var{key2} @dots{} which
returns the key-list identifying the lowest record higher than
@var{key1} @var{key2} @dots{} which is stored in the relational-table;
or false if no higher record is present.

@defopx {Operation} {relational-table} isam-next column-name
The symbol @var{column-name} names a key field.  In the list returned
by @code{isam-next}, that field, or a field to its left, will be
changed.  This allows one to skip over less significant key fields.
@end defop

@defop {Operation} {relational-table} isam-prev
Returns a procedure of arguments @var{key1} @var{key2} @dots{} which
returns the key-list identifying the highest record less than
@var{key1} @var{key2} @dots{} which is stored in the relational-table;
or false if no lower record is present.

@defopx {Operation} {relational-table} isam-prev column-name
The symbol @var{column-name} names a key field.  In the list returned
by @code{isam-next}, that field, or a field to its left, will be
changed.  This allows one to skip over less significant key fields.
@end defop

For example, if a table has key fields:
@example
(col1 col2)
(9 5)
(9 6)
(9 7)
(9 8)
(12 5)
(12 6)
(12 7)
@end example

Then:
@example
((table 'isam-next)       '(9 5))       @result{} (9 6)
((table 'isam-next 'col2) '(9 5))       @result{} (9 6)
((table 'isam-next 'col1) '(9 5))       @result{} (12 5)
((table 'isam-prev)       '(12 7))      @result{} (12 6)
((table 'isam-prev 'col2) '(12 7))      @result{} (12 6)
((table 'isam-prev 'col1) '(12 7))      @result{} (9 8)
@end example


@node Table Administration,  , Sequential Index Operations, Table Operations
@subsubsection Table Administration

@defop {Operation} {relational-table} column-names
@defopx {Operation} {relational-table} column-foreigns
@defopx {Operation} {relational-table} column-domains
@defopx {Operation} {relational-table} column-types
Return a list of the column names, foreign-key table names, domain
names, or type names respectively for this table.  These 4 methods are
different from the others in that the list is returned, rather than a
procedure to obtain the list.

@defopx {Operation} {relational-table} primary-limit
Returns the number of primary keys fields in the relations in this
table.
@end defop

@defop {Operation} {relational-table} close-table
Subsequent operations to this table will signal an error.
@end defop

@node Database Interpolation, Embedded Commands, Table Operations, Relational Database
@subsection Database Interpolation

@code{(require 'database-interpolate)}

@noindent
Indexed sequential access methods allow finding the keys (having
associations) closest to a given value.  This facilitates the
interpolation of associations between those in the table.

@defun interpolate-from-table table column
@var{Table} should be a relational table with one numeric primary key
field which supports the @code{isam-prev} and @code{isam-next}
operations.  @var{column} should be a symbol or exact positive integer
designating a numerically valued column of @var{table}.

@code{interpolate-from-table} calculates and returns a value
proportionally intermediate between its values in the next and
previous key records contained in @var{table}.  For keys larger than
all the stored keys the value associated with the largest stored key
is used.  For keys smaller than all the stored keys the value
associated with the smallest stored key is used.
@end defun



@node Embedded Commands, Database Macros, Database Interpolation, Relational Database
@subsection Embedded Commands

@code{(require 'database-commands)}

@noindent
This enhancement wraps a utility layer on @code{relational-database}
which provides:

@itemize @bullet
@item
Automatic execution of initialization commands stored in database.
@item
Transparent execution of database commands stored in @code{*commands*}
table in database.
@end itemize

When an enhanced relational-database is called with a symbol which
matches a @var{name} in the @code{*commands*} table, the associated
procedure expression is evaluated and applied to the enhanced
relational-database.  A procedure should then be returned which the user
can invoke on (optional) arguments.

The command @code{*initialize*} is special.  If present in the
@code{*commands*} table, @code{open-database} or @code{open-database!}
will return the value of the @code{*initialize*} command.  Notice that
arbitrary code can be run when the @code{*initialize*} procedure is
automatically applied to the enhanced relational-database.

Note also that if you wish to shadow or hide from the user
relational-database methods described in @ref{Database Operations}, this
can be done by a dispatch in the closure returned by the
@code{*initialize*} expression rather than by entries in the
@code{*commands*} table if it is desired that the underlying methods
remain accessible to code in the @code{*commands*} table.


@menu
* Database Extension::          
* Command Intrinsics::          
* Define-tables Example::       
* The *commands* Table::        
* Command Service::             
* Command Example::             
@end menu


@node Database Extension, Command Intrinsics, Embedded Commands, Embedded Commands
@subsubsection Database Extension

@defun wrap-command-interface rdb
Returns relational database @var{rdb} wrapped with additional commands
defined in its *commands* table.
@end defun

@defun add-command-tables rdb
The relational database @var{rdb} must be mutable.
@var{add-command-tables} adds a *command* table to @var{rdb}; then
returns @code{(wrap-command-interface @var{rdb})}.
@end defun

@defun define-*commands* rdb spec-0 @dots{}

Adds commands to the @code{*commands*} table as specified in
@var{spec-0} @dots{} to the open relational-database @var{rdb}.  Each
@var{spec} has the form:

@lisp
((@r{<name>} @r{<rdb>}) @r{"comment"} @r{<expression1>} @r{<expression2>} @dots{})
@end lisp
or
@lisp
((@r{<name>} @r{<rdb>}) @r{<expression1>} @r{<expression2>} @dots{})
@end lisp

where @r{<name>} is the command name, @r{<rdb>} is a formal passed the
calling relational database, @r{"comment"} describes the
command, and @r{<expression1>}, @r{<expression1>}, @dots{} are the
body of the procedure.

@code{define-*commands*} adds to the @code{*commands*} table a command
@r{<name>}:

@lisp
(lambda (@r{<name>} @r{<rdb>}) @r{<expression1>} @r{<expression2>} @dots{})
@end lisp

@end defun


@defun open-command-database filename
@defunx open-command-database filename base-table-type
Returns an open enhanced relational database associated with
@var{filename}.  The database will be opened with base-table type
@var{base-table-type}) if supplied.  If @var{base-table-type} is not
supplied, @code{open-command-database} will attempt to deduce the correct
base-table-type.  If the database can not be opened or if it lacks the
@code{*commands*} table, @code{#f} is returned.

@defunx open-command-database! filename
@defunx open-command-database! filename base-table-type
Returns @emph{mutable} open enhanced relational database @dots{}

@defunx open-command-database database
Returns @var{database} if it is an immutable relational database; #f
otherwise.

@defunx open-command-database! database
Returns @var{database} if it is a mutable relational database; #f
otherwise.
@end defun


@node Command Intrinsics, Define-tables Example, Database Extension, Embedded Commands
@subsubsection Command Intrinsics

Some commands are defined in all extended relational-databases.  The are
called just like @ref{Database Operations}.

@defop {Operation} {relational-database} add-domain domain-row
Adds @var{domain-row} to the @dfn{domains} table if there is no row in
the domains table associated with key @code{(car @var{domain-row})} and
returns @code{#t}.  Otherwise returns @code{#f}.

For the fields and layout of the domain table, @xref{Catalog
Representation}.  Currently, these fields are
@itemize @bullet
@item
domain-name
@item
foreign-table
@item
domain-integrity-rule
@item
type-id
@item
type-param
@end itemize

The following example adds 3 domains to the @samp{build} database.
@samp{Optstring} is either a string or @code{#f}.  @code{filename} is a
string and @code{build-whats} is a symbol.

@example
(for-each (build 'add-domain)
          '((optstring #f
                       (lambda (x) (or (not x) (string? x)))
                       string
                       #f)
            (filename #f #f string #f)
            (build-whats #f #f symbol #f)))
@end example
@end defop

@defop {Operation} {relational-database} delete-domain domain-name
Removes and returns the @var{domain-name} row from the @dfn{domains}
table.
@end defop

@defop {Operation} {relational-database} domain-checker domain
Returns a procedure to check an argument for conformance to domain
@var{domain}.
@end defop


@node Define-tables Example, The *commands* Table, Command Intrinsics, Embedded Commands
@subsubsection Define-tables Example

@noindent
The following example shows a new database with the name of
@file{foo.db} being created with tables describing processor families
and processor/os/compiler combinations.  The database is then
solidified; saved and changed to immutable.

@example
(require 'databases)
@ftindex databases
(define my-rdb (create-database "foo.db" 'alist-table))
(define-tables my-rdb
  '(processor-family
    ((family    atom))
    ((also-ran  processor-family))
    ((m68000           #f)
     (m68030           m68000)
     (i386             i8086)
     (i8086            #f)
     (powerpc          #f)))

  '(platform
    ((name      symbol))
    ((processor processor-family)
     (os        symbol)
     (compiler  symbol))
    ((aix              powerpc aix     -)
     (amiga-dice-c     m68000  amiga   dice-c)
     (amiga-aztec      m68000  amiga   aztec)
     (amiga-sas/c-5.10 m68000  amiga   sas/c)
     (atari-st-gcc     m68000  atari   gcc)
     (atari-st-turbo-c m68000  atari   turbo-c)
     (borland-c-3.1    i8086   ms-dos  borland-c)
     (djgpp            i386    ms-dos  gcc)
     (linux            i386    linux   gcc)
     (microsoft-c      i8086   ms-dos  microsoft-c)
     (os/2-emx         i386    os/2    gcc)
     (turbo-c-2        i8086   ms-dos  turbo-c)
     (watcom-9.0       i386    ms-dos  watcom))))

(solidify-database my-rdb)
@end example


@node The *commands* Table, Command Service, Define-tables Example, Embedded Commands
@subsubsection The *commands* Table

@noindent
The table @code{*commands*} in an @dfn{enhanced} relational-database has
the fields (with domains):
@example
@group
PRI name        symbol
    parameters  parameter-list
    procedure   expression
    documentation string
@end group
@end example

The @code{parameters} field is a foreign key (domain
@code{parameter-list}) of the @code{*catalog-data*} table and should
have the value of a table described by @code{*parameter-columns*}.  This
@code{parameter-list} table describes the arguments suitable for passing
to the associated command.  The intent of this table is to be of a form
such that different user-interfaces (for instance, pull-down menus or
plain-text queries) can operate from the same table.  A
@code{parameter-list} table has the following fields:
@example
@group
PRI index       ordinal
    name        symbol
    arity       parameter-arity
    domain      domain
    defaulter   expression
    expander    expression
    documentation string
@end group
@end example

The @code{arity} field can take the values:

@table @code
@item single
Requires a single parameter of the specified domain.
@item optional
A single parameter of the specified domain or zero parameters is
acceptable.
@item boolean
A single boolean parameter or zero parameters (in which case @code{#f}
is substituted) is acceptable.
@item nary
Any number of parameters of the specified domain are acceptable.  The
argument passed to the command function is always a list of the
parameters.
@item nary1
One or more of parameters of the specified domain are acceptable.  The
argument passed to the command function is always a list of the
parameters.
@end table

The @code{domain} field specifies the domain which a parameter or
parameters in the @code{index}th field must satisfy.

The @code{defaulter} field is an expression whose value is either
@code{#f} or a procedure of one argument (the parameter-list) which
returns a @emph{list} of the default value or values as appropriate.
Note that since the @code{defaulter} procedure is called every time a
default parameter is needed for this column, @dfn{sticky} defaults can
be implemented using shared state with the domain-integrity-rule.


@node Command Service, Command Example, The *commands* Table, Embedded Commands
@subsubsection Command Service

@defun make-command-server rdb table-name
Returns a procedure of 2 arguments, a (symbol) command and a call-back
procedure.  When this returned procedure is called, it looks up
@var{command} in table @var{table-name} and calls the call-back
procedure with arguments:
@table @var
@item command
The @var{command}
@item command-value
The result of evaluating the expression in the @var{procedure} field of
@var{table-name} and calling it with @var{rdb}.
@item parameter-name
A list of the @dfn{official} name of each parameter.  Corresponds to the
@code{name} field of the @var{command}'s parameter-table.
@item positions
A list of the positive integer index of each parameter.  Corresponds to
the @code{index} field of the @var{command}'s parameter-table.
@item arities
A list of the arities of each parameter.  Corresponds to the
@code{arity} field of the @var{command}'s parameter-table.  For a
description of @code{arity} see table above.
@item types
A list of the type name of each parameter.  Correspnds to the
@code{type-id} field of the contents of the @code{domain} of the
@var{command}'s parameter-table.
@item defaulters
A list of the defaulters for each parameter.  Corresponds to
the @code{defaulters} field of the @var{command}'s parameter-table.
@item domain-integrity-rules
A list of procedures (one for each parameter) which tests whether a
value for a parameter is acceptable for that parameter.  The procedure
should be called with each datum in the list for @code{nary} arity
parameters.
@item aliases
A list of lists of @code{(@r{alias} @r{parameter-name})}.  There can be
more than one alias per @var{parameter-name}.
@end table
@end defun

For information about parameters, @xref{Parameter lists}.


@node Command Example,  , Command Service, Embedded Commands
@subsubsection Command Example

Here is an example of setting up a command with arguments and parsing
those arguments from a @code{getopt} style argument list
(@pxref{Getopt}).

@example
(require 'database-commands)
@ftindex database-commands
(require 'databases)
@ftindex databases
(require 'getopt-parameters)
@ftindex getopt-parameters
(require 'parameters)
@ftindex parameters
(require 'getopt)
@ftindex getopt
(require 'fluid-let)
(require 'printf)

(define my-rdb (add-command-tables (create-database #f 'alist-table)))

(define-tables my-rdb
  '(foo-params
    *parameter-columns*
    *parameter-columns*
    ((1 single-string single string
        (lambda (pl) '("str")) #f "single string")
     (2 nary-symbols nary symbol
        (lambda (pl) '()) #f "zero or more symbols")
     (3 nary1-symbols nary1 symbol
        (lambda (pl) '(symb)) #f "one or more symbols")
     (4 optional-number optional ordinal
        (lambda (pl) '()) #f "zero or one number")
     (5 flag boolean boolean
        (lambda (pl) '(#f)) #f "a boolean flag")))
  '(foo-pnames
    ((name string))
    ((parameter-index ordinal))
    (("s" 1)
     ("single-string" 1)
     ("n" 2)
     ("nary-symbols" 2)
     ("N" 3)
     ("nary1-symbols" 3)
     ("o" 4)
     ("optional-number" 4)
     ("f" 5)
     ("flag" 5)))
  '(my-commands
    ((name symbol))
    ((parameters parameter-list)
     (parameter-names parameter-name-translation)
     (procedure expression)
     (documentation string))
    ((foo
      foo-params
      foo-pnames
      (lambda (rdb) (lambda args (print args)))
      "test command arguments"))))

(define (dbutil:serve-command-line rdb command-table command argv)
  (set! *argv* (if (vector? argv) (vector->list argv) argv))
  ((make-command-server rdb command-table)
   command
   (lambda (comname comval options positions
                    arities types defaulters dirs aliases)
     (apply comval (getopt->arglist options positions
                    arities types defaulters dirs aliases)))))

(define (cmd . opts)
  (fluid-let ((*optind* 1))
    (printf "%-34s @result{} "
            (call-with-output-string
             (lambda (pt) (write (cons 'cmd opts) pt))))
    (set! opts (cons "cmd" opts))
    (force-output)
    (dbutil:serve-command-line
     my-rdb 'my-commands 'foo (length opts) opts)))

(cmd)                              @result{} ("str" () (symb) () #f)
(cmd "-f")                         @result{} ("str" () (symb) () #t)
(cmd "--flag")                     @result{} ("str" () (symb) () #t)
(cmd "-o177")                      @result{} ("str" () (symb) (177) #f)
(cmd "-o" "177")                   @result{} ("str" () (symb) (177) #f)
(cmd "--optional" "621")           @result{} ("str" () (symb) (621) #f)
(cmd "--optional=621")             @result{} ("str" () (symb) (621) #f)
(cmd "-s" "speciality")            @result{} ("speciality" () (symb) () #f)
(cmd "-sspeciality")               @result{} ("speciality" () (symb) () #f)
(cmd "--single" "serendipity")     @result{} ("serendipity" () (symb) () #f)
(cmd "--single=serendipity")       @result{} ("serendipity" () (symb) () #f)
(cmd "-n" "gravity" "piety")       @result{} ("str" () (piety gravity) () #f)
(cmd "-ngravity" "piety")          @result{} ("str" () (piety gravity) () #f)
(cmd "--nary" "chastity")          @result{} ("str" () (chastity) () #f)
(cmd "--nary=chastity" "")         @result{} ("str" () ( chastity) () #f)
(cmd "-N" "calamity")              @result{} ("str" () (calamity) () #f)
(cmd "-Ncalamity")                 @result{} ("str" () (calamity) () #f)
(cmd "--nary1" "surety")           @result{} ("str" () (surety) () #f)
(cmd "--nary1=surety")             @result{} ("str" () (surety) () #f)
(cmd "-N" "levity" "fealty")       @result{} ("str" () (fealty levity) () #f)
(cmd "-Nlevity" "fealty")          @result{} ("str" () (fealty levity) () #f)
(cmd "--nary1" "surety" "brevity") @result{} ("str" () (brevity surety) () #f)
(cmd "--nary1=surety" "brevity")   @result{} ("str" () (brevity surety) () #f)
(cmd "-?")
@print{}
Usage: cmd [OPTION ARGUMENT ...] ...

  -f, --flag
  -o, --optional[=]<number>
  -n, --nary[=]<symbols> ...
  -N, --nary1[=]<symbols> ...
  -s, --single[=]<string>

ERROR: getopt->parameter-list "unrecognized option" "-?"
@end example



@node Database Macros, Database Browser, Embedded Commands, Relational Database
@subsection Database Macros

@code{(require 'within-database)}

The object-oriented programming interface to SLIB relational databases
has failed to support clear, understandable, and modular code-writing
for database applications.

This seems to be a failure of the object-oriented paradigm where the
type of an object is not manifest (or even traceable) in source code.

@code{within-database}, along with the @samp{databases} package,
reorganizes high-level database functions toward a more declarative
style.  Using this package, one can tag database table and command
declarations for emacs:

@example
etags -lscheme -r'/ *(define-\(command\|table\) (\([^; \t]+\)/\2/' \
      source1.scm ...
@end example

@menu
* Within-database::             
* Within-database Example::     
@end menu

@node Within-database, Within-database Example, Database Macros, Database Macros
@subsubsection Within-database

@defun within-database database statement-1 @dots{}

@code{within-database} creates a lexical scope in which the commands
@code{define-table} and @code{define-command} create tables and
@code{*commands*}-table entries respectively in open relational
database @var{database}.  The expressions in `within-database' form
are executed in order.

@code{within-database} Returns @var{database}.
@end defun

@deffn Syntax define-command (@r{<name>} @r{<rdb>}) @r{"comment"} @r{<expression1>} @r{<expression2>} @dots{}
@deffnx Syntax define-command (@r{<name>} @r{<rdb>}) @r{<expression1>} @r{<expression2>} @dots{}

Adds to the @code{*commands*} table a command
@r{<name>}:

@lisp
(lambda (@r{<name>} @r{<rdb>}) @r{<expression1>} @r{<expression2>} @dots{})
@end lisp

@end deffn

@deffn Syntax define-table @r{<name>} @r{<descriptor-name>} @r{<descriptor-name>} @r{<rows>}
@deffnx Syntax define-table @r{<name>} @r{<primary-key-fields>} @r{<other-fields>} @r{<rows>}

where @r{<name>} is the table name, @r{<descriptor-name>} is the symbol
name of a descriptor table, @r{<primary-key-fields>} and
@r{<other-fields>} describe the primary keys and other fields
respectively, and @r{<rows>} is a list of data rows to be added to the
table.

@r{<primary-key-fields>} and @r{<other-fields>} are lists of field
descriptors of the form:

@lisp
(@r{<column-name>} @r{<domain>})
@end lisp
or
@lisp
(@r{<column-name>} @r{<domain>} @r{<column-integrity-rule>})
@end lisp

where @r{<column-name>} is the column name, @r{<domain>} is the domain
of the column, and @r{<column-integrity-rule>} is an expression whose
value is a procedure of one argument (which returns @code{#f} to signal
an error).

If @r{<domain>} is not a defined domain name and it matches the name of
this table or an already defined (in one of @var{spec-0} @dots{}) single
key field table, a foreign-key domain will be created for it.

@end deffn

@defun add-macro-support database
The relational database @var{database} must be mutable.
@code{add-macro-support} adds a @code{*macros*} table and
@code{define-macro} macro to @var{database}; then @var{database} is
returned.
@end defun

@deffn Syntax define-macro (@r{<name>} @r{arg1} @dots{}) @r{"comment"} @r{<expression1>} @r{<expression2>} @dots{}
@deffnx Syntax define-macro (@r{<name>} @r{arg1} @dots{}) @r{<expression1>} @r{<expression2>} @dots{}
Adds a macro @r{<name>} to the @code{*macros*}.

@emph{Note:} @code{within-database} creates lexical scope where not
only @code{define-command} and @code{define-table}, but every command
and macro are defined, ie.:

@example
(within-database my-rdb
  (define-command (message rdb)
    (lambda (msg)
      (display "message: ")
      (display msg)
      (newline)))
  (message "Defining FOO...")
  ;; ... defining FOO ...
  (message "Defining BAR...")
  ;; ... defining BAR ...
  )
@end example
@end deffn


@node Within-database Example,  , Within-database, Database Macros
@subsubsection Within-database Example

@noindent
Here is an example of @code{within-database} macros:

@example
(require 'within-database)

(define my-rdb
  (add-command-tables
   (create-database "foo.db" 'alist-table)))

(within-database my-rdb
  (define-command (*initialize* rdb)
    "Print Welcome"
    (display "Welcome")
    (newline)
    rdb)
  (define-command (without-documentation rdb)
    (display "without-documentation called")
    (newline))
  (define-table (processor-family
                 ((family   atom))
                 ((also-ran processor-family)))
    (m68000  #f)
    (m68030  m68000)
    (i386    i8086)
    (i8086   #f)
    (powerpc #f))
  (define-table (platform
                 ((name symbol))
                 ((processor processor-family)
                  (os        symbol)
                  (compiler  symbol)))
    (aix              powerpc aix     -)
    ;; ...
    (amiga-aztec      m68000  amiga   aztec)
    (amiga-sas/c-5.10 m68000  amiga   sas/c)
    (atari-st-gcc     m68000  atari   gcc)
    ;; ...
    (watcom-9.0       i386    ms-dos  watcom))
  (define-command (get-processor rdb)
    "Get processor for given platform."
    (((rdb 'open-table) 'platform #f) 'get 'processor)))

(close-database my-rdb)

(set! my-rdb (open-command-database! "foo.db"))
@print{}
Welcome

(my-rdb 'without-documentation)
@print{}
without-documentation called

((my-rdb 'get-processor) 'amiga-sas/c-5.10)
@result{} m68000

(close-database my-rdb)
@end example



@node Database Browser,  , Database Macros, Relational Database
@subsection Database Browser

(require 'database-browse)

@deffn {Procedure} browse database

Prints the names of all the tables in @var{database} and sets browse's
default to @var{database}.

@deffnx {Procedure} browse

Prints the names of all the tables in the default database.

@deffnx {Procedure} browse table-name

For each record of the table named by the symbol @var{table-name},
prints a line composed of all the field values.

@deffnx {Procedure} browse pathname

Opens the database named by the string @var{pathname}, prints the names
of all its tables, and sets browse's default to the database.

@deffnx {Procedure} browse database table-name

Sets browse's default to @var{database} and prints the records of the
table named by the symbol @var{table-name}.

@deffnx {Procedure} browse pathname table-name

Opens the database named by the string @var{pathname} and sets browse's
default to it; @code{browse} prints the records of the table named by
the symbol @var{table-name}.

@end deffn


@node Relational Infrastructure, Weight-Balanced Trees, Relational Database, Database Packages
@section Relational Infrastructure


@menu
* Base Table::                  
* Catalog Representation::      
* Relational Database Objects::  
* Database Operations::         
@end menu


@node Base Table, Catalog Representation, Relational Infrastructure, Relational Infrastructure
@subsection Base Table

@cindex base-table
A @dfn{base-table} is the primitive database layer upon which SLIB
relational databases are built.  At the minimum, it must support the
types integer, symbol, string, and boolean.  The base-table may restrict
the size of integers, symbols, and strings it supports.

A base table implementation is available as the value of the identifier
naming it (eg. @var{alist-table}) after requiring the symbol of that
name.

@deftp {Feature} alist-table
@code{(require 'alist-table)}
@ftindex alist-table

Association-list base tables support all Scheme types and are suitable
for small databases.  In order to be retrieved after being written to a
file, the data stored should include only objects which are readable and
writeable in the Scheme implementation.

The @dfn{alist-table} base-table implementation is included in the
SLIB distribution.
@end deftp

@dfn{WB} is a B-tree database package with SCM interfaces.  Being
disk-based, WB databases readily store and access hundreds of
megabytes of data.  WB comes with two base-table embeddings.

@deftp {Feature} wb-table
@code{(require 'wb-table)}
@ftindex wb-table

@cindex WB
@code{wb-table} supports scheme expressions for keys and values whose
text representations are less than 255 characters in length.
@xref{wb-table, , , wb, WB}.
@end deftp


@deftp {Feature} rwb-isam
@code{(require 'rwb-isam)}
@ftindex rwb-isam

@dfn{rwb-isam} is a sophisticated base-table implementation built on
WB and SCM which uses binary numerical formats for key and non-key
fields.  It supports IEEE floating-point and fixed-precision integer
keys with the correct numerical collation order.
@end deftp

This rest of this section documents the interface for a base table
implementation from which the @ref{Relational Database} package
constructs a Relational system.  It will be of interest primarily to
those wishing to port or write new base-table implementations.

@defvar *base-table-implementations*
To support automatic dispatch for @code{open-database}, each base-table
module adds an association to @var{*base-table-implementations*} when
loaded.  This association is the list of the base-table symbol and the
value returned by @code{(make-relational-system @var{base-table})}.
@end defvar

@menu
* The Base::                    
* Base Tables::                 
* Base Field Types::            
* Composite Keys::              
* Base Record Operations::      
* Match Keys::                  
* Aggregate Base Operations::   
* Base ISAM Operations::        
@end menu

@node The Base, Base Tables, Base Table, Base Table
@subsubsection The Base

All of these functions are accessed through a single procedure by
calling that procedure with the symbol name of the operation.  A
procedure will be returned if that operation is supported and @code{#f}
otherwise.  For example:

@example
@group
(require 'alist-table)
@ftindex alist-table
@findex alist-table
(define my-base (alist-table 'make-base))
my-base         @result{} *a procedure*
(define foo (alist-table 'foo))
foo             @result{} #f
@end group
@end example

@defop {Operation} {base-table} make-base filename key-dimension column-types
Returns a new, open, low-level database (collection of tables)
associated with @var{filename}.  This returned database has an empty
table associated with @var{catalog-id}.  The positive integer
@var{key-dimension} is the number of keys composed to make a
@var{primary-key} for the catalog table.  The list of symbols
@var{column-types} describes the types of each column for that table.
If the database cannot be created as specified, @code{#f} is returned.

Calling the @code{close-base} method on this database and possibly other
operations will cause @var{filename} to be written to.  If
@var{filename} is @code{#f} a temporary, non-disk based database will be
created if such can be supported by the base table implelentation.
@end defop

@defop {Operation} {base-table} open-base filename mutable
Returns an open low-level database associated with @var{filename}.  If
@var{mutable} is @code{#t}, this database will have methods capable of
effecting change to the database.  If @var{mutable} is @code{#f}, only
methods for inquiring the database will be available.  If the database
cannot be opened as specified @code{#f} is returned.

Calling the @code{close-base} (and possibly other) method on a
@var{mutable} database will cause @var{filename} to be written to.
@end defop

@defop {Operation} {base-table} write-base lldb filename
Causes the low-level database @var{lldb} to be written to
@var{filename}.  If the write is successful, also causes @var{lldb} to
henceforth be associated with @var{filename}.  Calling the
@code{close-database} (and possibly other) method on @var{lldb} may
cause @var{filename} to be written to.  If @var{filename} is @code{#f}
this database will be changed to a temporary, non-disk based database if
such can be supported by the underlying base table implelentation.  If
the operations completed successfully, @code{#t} is returned.
Otherwise, @code{#f} is returned.
@end defop

@defop {Operation} {base-table} sync-base lldb
Causes the file associated with the low-level database @var{lldb} to be
updated to reflect its current state.  If the associated filename is
@code{#f}, no action is taken and @code{#f} is returned.  If this
operation completes successfully, @code{#t} is returned.  Otherwise,
@code{#f} is returned.
@end defop

@defop {Operation} {base-table} close-base lldb
Causes the low-level database @var{lldb} to be written to its associated
file (if any).  If the write is successful, subsequent operations to
@var{lldb} will signal an error.  If the operations complete
successfully, @code{#t} is returned.  Otherwise, @code{#f} is returned.
@end defop


@node Base Tables, Base Field Types, The Base, Base Table
@subsubsection Base Tables

@defop {Operation} {base-table} make-table lldb key-dimension column-types
Returns the ordinal @var{base-id} for a new base table, otherwise
returns @code{#f}.  The base table can then be opened using
@code{(open-table @var{lldb} @var{base-id})}.  The positive integer
@var{key-dimension} is the number of keys composed to make a
@var{primary-key} for this table.  The list of symbols
@var{column-types} describes the types of each column.
@end defop

@defop {Operation} {base-table} open-table lldb base-id key-dimension column-types
Returns a @var{handle} for an existing base table in the low-level
database @var{lldb} if that table exists and can be opened in the mode
indicated by @var{mutable}, otherwise returns @code{#f}.

As with @code{make-table}, the positive integer @var{key-dimension} is
the number of keys composed to make a @var{primary-key} for this table.
The list of symbols @var{column-types} describes the types of each
column.
@end defop

@defop {Operation} {base-table} kill-table lldb base-id key-dimension column-types
Returns @code{#t} if the base table associated with @var{base-id} was
removed from the low level database @var{lldb}, and @code{#f} otherwise.
@end defop

@defop {Operation} {base-table} catalog-id
A constant @var{base-id} ordinal suitable for passing as a parameter to
@code{open-table}.  @var{catalog-id} will be used as the base table for
the system catalog.
@end defop


@node Base Field Types, Composite Keys, Base Tables, Base Table
@subsubsection Base Field Types

@defop {Operation} {base-table} supported-type? symbol
Returns @code{#t} if @var{symbol} names a type allowed as a column
value by the implementation, and @code{#f} otherwise.  At a minimum,
an implementation must support the types @code{integer},
@code{ordinal}, @code{symbol}, @code{string}, and @code{boolean}.
@end defop

@defop {Operation} {base-table} supported-key-type? symbol
Returns @code{#t} if @var{symbol} names a type allowed as a key value
by the implementation, and @code{#f} otherwise.  At a minimum, an
implementation must support the types @code{ordinal}, and
@code{symbol}.
@end defop

@noindent
An @dfn{ordinal} is an exact positive integer.  The other types are
standard Scheme.


@node Composite Keys, Base Record Operations, Base Field Types, Base Table
@subsubsection Composite Keys

@defop {Operation} {base-table} make-keyifier-1 type
Returns a procedure which accepts a single argument which must be of
type @var{type}.  This returned procedure returns an object suitable for
being a @var{key} argument in the functions whose descriptions follow.

Any 2 arguments of the supported type passed to the returned function
which are not @code{equal?} must result in returned values which are not
@code{equal?}.
@end defop

@defop {Operation} {base-table} make-list-keyifier key-dimension types
The list of symbols @var{types} must have at least @var{key-dimension}
elements.  Returns a procedure which accepts a list of length
@var{key-dimension} and whose types must corresopond to the types named
by @var{types}.  This returned procedure combines the elements of its
list argument into an object suitable for being a @var{key} argument in
the functions whose descriptions follow.

Any 2 lists of supported types (which must at least include symbols and
non-negative integers) passed to the returned function which are not
@code{equal?} must result in returned values which are not
@code{equal?}.
@end defop

@defop {Operation} {base-table} make-key-extractor key-dimension types column-number
Returns a procedure which accepts objects produced by application of the
result of @code{(make-list-keyifier @var{key-dimension} @var{types})}.
This procedure returns a @var{key} which is @code{equal?} to the
@var{column-number}th element of the list which was passed to create
@var{composite-key}.  The list @var{types} must have at least
@var{key-dimension} elements.
@end defop

@defop {Operation} {base-table} make-key->list key-dimension types
Returns a procedure which accepts objects produced by application of
the result of @code{(make-list-keyifier @var{key-dimension}
@var{types})}.  This procedure returns a list of @var{key}s which are
elementwise @code{equal?} to the list which was passed to create
@var{composite-key}.
@end defop


@node Base Record Operations, Match Keys, Composite Keys, Base Table
@subsubsection Base Record Operations

@noindent
In the following functions, the @var{key} argument can always be assumed
to be the value returned by a call to a @emph{keyify} routine.

@defop {Operation} {base-table} present? handle key
Returns a non-@code{#f} value if there is a row associated with
@var{key} in the table opened in @var{handle} and @code{#f} otherwise.
@end defop

@defop {Operation} {base-table} make-getter key-dimension types
Returns a procedure which takes arguments @var{handle} and @var{key}.
This procedure returns a list of the non-primary values of the relation
(in the base table opened in @var{handle}) whose primary key is
@var{key} if it exists, and @code{#f} otherwise.
@end defop

@noindent
@code{make-getter-1} is a new operation.  The relational-database
module works with older base-table implementations by using
@code{make-getter}.

@defop {Operation} {base-table} make-getter-1 key-dimension types index
Returns a procedure which takes arguments @var{handle} and @var{key}.
This procedure returns the value of the @var{index}th field (in the
base table opened in @var{handle}) whose primary key is @var{key} if
it exists, and @code{#f} otherwise.

@var{index} must be larger than @var{key-dimension}.
@end defop

@defop {Operation} {base-table} make-putter key-dimension types
Returns a procedure which takes arguments @var{handle} and @var{key} and
@var{value-list}.  This procedure associates the primary key @var{key}
with the values in @var{value-list} (in the base table opened in
@var{handle}) and returns an unspecified value.
@end defop

@defop {Operation} {base-table} delete handle key
Removes the row associated with @var{key} from the table opened in
@var{handle}.  An unspecified value is returned.
@end defop


@node Match Keys, Aggregate Base Operations, Base Record Operations, Base Table
@subsubsection Match Keys

@noindent
@cindex match-keys
@cindex match
@cindex wild-card
A @var{match-keys} argument is a list of length equal to
the number of primary keys.  The @var{match-keys} restrict the actions
of the table command to those records whose primary keys all satisfy the
corresponding element of the @var{match-keys} list.  The elements and
their actions are:

@quotation
@table @asis
@item @code{#f}
The false value matches any key in the corresponding position.
@item an object of type procedure
This procedure must take a single argument, the key in the corresponding
position.  Any key for which the procedure returns a non-false value is
a match; Any key for which the procedure returns a @code{#f} is not.
@item other values
Any other value matches only those keys @code{equal?} to it.
@end table
@end quotation


@node Aggregate Base Operations, Base ISAM Operations, Match Keys, Base Table
@subsubsection Aggregate Base Operations

@noindent
The @var{key-dimension} and @var{column-types} arguments are needed to
decode the composite-keys for matching with @var{match-keys}.

@defop {Operation} {base-table} delete* handle key-dimension column-types match-keys
Removes all rows which satisfy @var{match-keys} from the table opened in
@var{handle}.  An unspecified value is returned.
@end defop

@defop {Operation} {base-table} for-each-key handle procedure key-dimension column-types match-keys
Calls @var{procedure} once with each @var{key} in the table opened in
@var{handle} which satisfy @var{match-keys} in an unspecified order.
An unspecified value is returned.
@end defop

@defop {Operation} {base-table} map-key handle procedure key-dimension column-types match-keys
Returns a list of the values returned by calling @var{procedure} once
with each @var{key} in the table opened in @var{handle} which satisfy
@var{match-keys} in an unspecified order.
@end defop


@node Base ISAM Operations,  , Aggregate Base Operations, Base Table
@subsubsection Base ISAM Operations

@noindent
These operations are optional for a Base-Table implementation.

@defop {Operation} {base-table} ordered-for-each-key handle procedure key-dimension column-types match-keys
Calls @var{procedure} once with each @var{key} in the table opened in
@var{handle} which satisfy @var{match-keys} in the natural order for
the types of the primary key fields of that table.  An unspecified value
is returned.
@end defop

@defop {Operation} {base-table} make-nexter handle key-dimension column-types index
Returns a procedure of arguments @var{key1} @var{key2} @dots{} which
returns the key-list identifying the lowest record higher than
@var{key1} @var{key2} @dots{} which is stored in the base-table and
which differs in column @var{index} or a lower indexed key; or false
if no higher record is present.
@end defop

@defop {Operation} {base-table} make-prever handle key-dimension column-types index
Returns a procedure of arguments @var{key1} @var{key2} @dots{} which
returns the key-list identifying the highest record less than
@var{key1} @var{key2} @dots{} which is stored in the base-table and
which differs in column @var{index} or a lower indexed key; or false
if no higher record is present.
@end defop

@node Catalog Representation, Relational Database Objects, Base Table, Relational Infrastructure
@subsection Catalog Representation

@noindent
Each database (in an implementation) has a @dfn{system catalog} which
describes all the user accessible tables in that database (including
itself).

@noindent
The system catalog base table has the following fields.  @code{PRI}
indicates a primary key for that table.

@example
@group
PRI table-name
    column-limit            the highest column number
    coltab-name             descriptor table name
    bastab-id               data base table identifier
    user-integrity-rule
    view-procedure          A scheme thunk which, when called,
                            produces a handle for the view.  coltab
                            and bastab are specified if and only if
                            view-procedure is not.
@end group
@end example

@noindent
Descriptors for base tables (not views) are tables (pointed to by
system catalog).  Descriptor (base) tables have the fields:

@example
@group
PRI column-number           sequential integers from 1
    primary-key?            boolean TRUE for primary key components
    column-name
    column-integrity-rule
    domain-name
@end group
@end example

@noindent
A @dfn{primary key} is any column marked as @code{primary-key?} in the
corresponding descriptor table.  All the @code{primary-key?} columns
must have lower column numbers than any non-@code{primary-key?} columns.
Every table must have at least one primary key.  Primary keys must be
sufficient to distinguish all rows from each other in the table.  All of
the system defined tables have a single primary key.

@noindent
A @dfn{domain} is a category describing the allowable values to occur in
a column.  It is described by a (base) table with the fields:

@example
@group
PRI domain-name
    foreign-table
    domain-integrity-rule
    type-id
    type-param
@end group
@end example

@noindent
The @dfn{type-id} field value is a symbol.  This symbol may be used by
the underlying base table implementation in storing that field.

@noindent
If the @code{foreign-table} field is non-@code{#f} then that field names
a table from the catalog.  The values for that domain must match a
primary key of the table referenced by the @var{type-param} (or
@code{#f}, if allowed).  This package currently does not support
composite foreign-keys.

@noindent
The types for which support is planned are:
@example
@group
    atom
    symbol
    string                  [<length>]
    number                  [<base>]
    money                   <currency>
    date-time
    boolean

    foreign-key             <table-name>
    expression
    virtual                 <expression>
@end group
@end example


@node Relational Database Objects, Database Operations, Catalog Representation, Relational Infrastructure
@subsection Relational Database Objects

@noindent
This object-oriented interface is deprecated for typical database
applications; @ref{Using Databases} provides an application programmer
interface which is easier to understand and use.

@defun make-relational-system base-table-implementation

Returns a procedure implementing a relational database using the
@var{base-table-implementation}.

All of the operations of a base table implementation are accessed
through a procedure defined by @code{require}ing that implementation.
Similarly, all of the operations of the relational database
implementation are accessed through the procedure returned by
@code{make-relational-system}.  For instance, a new relational database
could be created from the procedure returned by
@code{make-relational-system} by:

@example
(require 'alist-table)
@ftindex alist-table
(define relational-alist-system
        (make-relational-system alist-table))
(define create-alist-database
        (relational-alist-system 'create-database))
(define my-database
        (create-alist-database "mydata.db"))
@end example
@end defun

@noindent
What follows are the descriptions of the methods available from
relational system returned by a call to @code{make-relational-system}.

@defop {Operation} {relational-system} create-database filename

Returns an open, nearly empty relational database associated with
@var{filename}.  The only tables defined are the system catalog and
domain table.  Calling the @code{close-database} method on this database
and possibly other operations will cause @var{filename} to be written
to.  If @var{filename} is @code{#f} a temporary, non-disk based database
will be created if such can be supported by the underlying base table
implelentation.  If the database cannot be created as specified
@code{#f} is returned.  For the fields and layout of descriptor tables,
@ref{Catalog Representation}
@end defop

@defop {Operation} {relational-system} open-database filename mutable?

Returns an open relational database associated with @var{filename}.  If
@var{mutable?} is @code{#t}, this database will have methods capable of
effecting change to the database.  If @var{mutable?} is @code{#f}, only
methods for inquiring the database will be available.  Calling the
@code{close-database} (and possibly other) method on a @var{mutable?}
database will cause @var{filename} to be written to.  If the database
cannot be opened as specified @code{#f} is returned.
@end defop


@node Database Operations,  , Relational Database Objects, Relational Infrastructure
@subsection Database Operations

@noindent
This object-oriented interface is deprecated for typical database
applications; @ref{Using Databases} provides an application programmer
interface which is easier to understand and use.

@noindent
These are the descriptions of the methods available from an open
relational database.  A method is retrieved from a database by calling
the database with the symbol name of the operation.  For example:

@example
(define my-database
        (create-alist-database "mydata.db"))
(define telephone-table-desc
        ((my-database 'create-table) 'telephone-table-desc))
@end example

@defop {Operation} {relational-database} close-database
Causes the relational database to be written to its associated file (if
any).  If the write is successful, subsequent operations to this
database will signal an error.  If the operations completed
successfully, @code{#t} is returned.  Otherwise, @code{#f} is returned.
@end defop

@defop {Operation} {relational-database} write-database filename
Causes the relational database to be written to @var{filename}.  If the
write is successful, also causes the database to henceforth be
associated with @var{filename}.  Calling the @code{close-database} (and
possibly other) method on this database will cause @var{filename} to be
written to.  If @var{filename} is @code{#f} this database will be
changed to a temporary, non-disk based database if such can be supported
by the underlying base table implelentation.  If the operations
completed successfully, @code{#t} is returned.  Otherwise, @code{#f} is
returned.
@end defop

@defop {Operation} {relational-database} sync-database
Causes any pending updates to the database file to be written out.  If
the operations completed successfully, @code{#t} is returned.
Otherwise, @code{#f} is returned.
@end defop

@defop {Operation} {relational-database} solidify-database
Causes any pending updates to the database file to be written out.  If
the writes completed successfully, then the database is changed to be
immutable and @code{#t} is returned.  Otherwise, @code{#f} is returned.
@end defop

@defop {Operation} {relational-database} table-exists? table-name
Returns @code{#t} if @var{table-name} exists in the system catalog,
otherwise returns @code{#f}.
@end defop

@defop {Operation} {relational-database} open-table table-name mutable?
Returns a @dfn{methods} procedure for an existing relational table in
this database if it exists and can be opened in the mode indicated by
@var{mutable?}, otherwise returns @code{#f}.
@end defop

@noindent
These methods will be present only in mutable databases.

@defop {Operation} {relational-database} delete-table table-name
Removes and returns the @var{table-name} row from the system catalog if
the table or view associated with @var{table-name} gets removed from the
database, and @code{#f} otherwise.
@end defop

@defop {Operation} {relational-database} create-table table-desc-name
Returns a methods procedure for a new (open) relational table for
describing the columns of a new base table in this database, otherwise
returns @code{#f}.  For the fields and layout of descriptor tables,
@xref{Catalog Representation}.

@defopx {Operation} {relational-database} create-table table-name table-desc-name
Returns a methods procedure for a new (open) relational table with
columns as described by @var{table-desc-name}, otherwise returns
@code{#f}.
@end defop

@defop {Operation} {relational-database} create-view ??
@defopx {Operation} {relational-database} project-table ??
@defopx {Operation} {relational-database} restrict-table ??
@defopx {Operation} {relational-database} cart-prod-tables ??
Not yet implemented.
@end defop


@node Weight-Balanced Trees,  , Relational Infrastructure, Database Packages
@section Weight-Balanced Trees

@code{(require 'wt-tree)}
@ftindex wt-tree

@cindex trees, balanced binary
@cindex balanced binary trees
@cindex binary trees
@cindex weight-balanced binary trees
Balanced binary trees are a useful data structure for maintaining large
sets of ordered objects or sets of associations whose keys are ordered.
MIT Scheme has an comprehensive implementation of weight-balanced binary
trees which has several advantages over the other data structures for
large aggregates:

@itemize @bullet
@item
In addition to the usual element-level operations like insertion,
deletion and lookup, there is a full complement of collection-level
operations, like set intersection, set union and subset test, all of
which are implemented with good orders of growth in time and space.
This makes weight balanced trees ideal for rapid prototyping of
functionally derived specifications.

@item
An element in a tree may be indexed by its position under the ordering
of the keys, and the ordinal position of an element may be determined,
both with reasonable efficiency.

@item
Operations to find and remove minimum element make weight balanced trees
simple to use for priority queues.

@item
The implementation is @emph{functional} rather than @emph{imperative}.
This means that operations like `inserting' an association in a tree do
not destroy the old tree, in much the same way that @code{(+ 1 x)}
modifies neither the constant 1 nor the value bound to @code{x}.  The
trees are referentially transparent thus the programmer need not worry
about copying the trees.  Referential transparency allows space
efficiency to be achieved by sharing subtrees.

@end itemize

These features make weight-balanced trees suitable for a wide range of
applications, especially those that
require large numbers of sets or discrete maps.  Applications that have
a few global databases and/or concentrate on element-level operations like
insertion and lookup are probably better off using hash-tables or
red-black trees.

The @emph{size} of a tree is the number of associations that it
contains.  Weight balanced binary trees are balanced to keep the sizes
of the subtrees of each node within a constant factor of each other.
This ensures logarithmic times for single-path operations (like lookup
and insertion).  A weight balanced tree takes space that is proportional
to the number of associations in the tree.  For the current
implementation, the constant of proportionality is six words per
association.

@cindex binary trees, as sets
@cindex binary trees, as discrete maps
@cindex sets, using binary trees
@cindex discrete maps, using binary trees
Weight balanced trees can be used as an implementation for either
discrete sets or discrete maps (associations).  Sets are implemented by
ignoring the datum that is associated with the key.  Under this scheme
if an associations exists in the tree this indicates that the key of the
association is a member of the set.  Typically a value such as
@code{()}, @code{#t} or @code{#f} is associated with the key.

Many operations can be viewed as computing a result that, depending on
whether the tree arguments are thought of as sets or maps, is known by
two different names.  An example is @code{wt-tree/member?}, which, when
regarding the tree argument as a set, computes the set membership
operation, but, when regarding the tree as a discrete map,
@code{wt-tree/member?} is the predicate testing if the map is defined at
an element in its domain.  Most names in this package have been chosen
based on interpreting the trees as sets, hence the name
@code{wt-tree/member?} rather than @code{wt-tree/defined-at?}.


@cindex run-time-loadable option
@cindex option, run-time-loadable
The weight balanced tree implementation is a run-time-loadable option.
To use weight balanced trees, execute

@example
(load-option 'wt-tree)
@end example
@ftindex load-option

@noindent
once before calling any of the procedures defined here.


@menu
* Construction of Weight-Balanced Trees::  
* Basic Operations on Weight-Balanced Trees::  
* Advanced Operations on Weight-Balanced Trees::  
* Indexing Operations on Weight-Balanced Trees::  
@end menu

@node Construction of Weight-Balanced Trees, Basic Operations on Weight-Balanced Trees, Weight-Balanced Trees, Weight-Balanced Trees
@subsection Construction of Weight-Balanced Trees

Binary trees require there to be a total order on the keys used to
arrange the elements in the tree.  Weight balanced trees are organized
by @emph{types}, where the type is an object encapsulating the ordering
relation.  Creating a tree is a two-stage process.  First a tree type
must be created from the predicate which gives the ordering.  The tree
type is then used for making trees, either empty or singleton trees or
trees from other aggregate structures like association lists.  Once
created, a tree `knows' its type and the type is used to test
compatibility between trees in operations taking two trees.  Usually a
small number of tree types are created at the beginning of a program and
used many times throughout the program's execution.

@deffn {procedure+} make-wt-tree-type key<?
This procedure creates and returns a new tree type based on the ordering
predicate @var{key<?}.
@var{Key<?} must be a total ordering, having the property that for all
key values @code{a}, @code{b} and @code{c}:

@example
(key<? a a)                         @result{} #f
(and (key<? a b) (key<? b a))       @result{} #f
(if (and (key<? a b) (key<? b c))
    (key<? a c)
    #t)                             @result{} #t
@end example

@noindent
Two key values are assumed to be equal if neither is less than the other
by @var{key<?}.

Each call to @code{make-wt-tree-type} returns a distinct value, and
trees are only compatible if their tree types are @code{eq?}.  A
consequence is that trees that are intended to be used in binary tree
operations must all be created with a tree type originating from the
same call to @code{make-wt-tree-type}.
@end deffn

@defvr {variable+} number-wt-type
A standard tree type for trees with numeric keys.  @code{Number-wt-type}
could have been defined by

@example
(define number-wt-type (make-wt-tree-type  <))
@end example
@end defvr

@defvr {variable+} string-wt-type
A standard tree type for trees with string keys.  @code{String-wt-type}
could have been defined by

@example
(define string-wt-type (make-wt-tree-type  string<?))
@end example
@end defvr



@deffn {procedure+} make-wt-tree wt-tree-type
This procedure creates and returns a newly allocated weight balanced
tree.  The tree is empty, i.e. it contains no associations.
@var{Wt-tree-type} is a weight balanced tree type obtained by calling
@code{make-wt-tree-type}; the returned tree has this type.
@end deffn

@deffn {procedure+} singleton-wt-tree wt-tree-type key datum
This procedure creates and returns a newly allocated weight balanced
tree.  The tree contains a single association, that of @var{datum} with
@var{key}.  @var{Wt-tree-type} is a weight balanced tree type obtained
by calling @code{make-wt-tree-type}; the returned tree has this type.
@end deffn

@deffn {procedure+} alist->wt-tree tree-type alist
Returns a newly allocated weight-balanced tree that contains the same
associations as @var{alist}.  This procedure is equivalent to:

@example
(lambda (type alist)
  (let ((tree (make-wt-tree type)))
    (for-each (lambda (association)
                (wt-tree/add! tree
                              (car association)
                              (cdr association)))
              alist)
    tree))
@end example
@end deffn



@node Basic Operations on Weight-Balanced Trees, Advanced Operations on Weight-Balanced Trees, Construction of Weight-Balanced Trees, Weight-Balanced Trees
@subsection Basic Operations on Weight-Balanced Trees

This section describes the basic tree operations on weight balanced
trees.  These operations are the usual tree operations for insertion,
deletion and lookup, some predicates and a procedure for determining the
number of associations in a tree.

@c @deffn {procedure+} wt-tree? object
@c Returns @code{#t} if @var{object} is a weight-balanced tree, otherwise
@c returns @code{#f}.
@c @end deffn

@deffn {procedure+} wt-tree/empty? wt-tree
Returns @code{#t} if @var{wt-tree} contains no associations, otherwise
returns @code{#f}.
@end deffn

@deffn {procedure+} wt-tree/size wt-tree
Returns the number of associations in @var{wt-tree}, an exact
non-negative integer.  This operation takes constant time.
@end deffn


@deffn {procedure+} wt-tree/add wt-tree key datum
Returns a new tree containing all the associations in @var{wt-tree} and
the association of @var{datum} with @var{key}.  If @var{wt-tree} already
had an association for @var{key}, the new association overrides the old.
The average and worst-case times required by this operation are
proportional to the logarithm of the number of associations in
@var{wt-tree}.
@end deffn

@deffn {procedure+} wt-tree/add! wt-tree key datum
Associates @var{datum} with @var{key} in @var{wt-tree} and returns an
unspecified value.  If @var{wt-tree} already has an association for
@var{key}, that association is replaced.  The average and worst-case
times required by this operation are proportional to the logarithm of
the number of associations in @var{wt-tree}.
@end deffn

@deffn {procedure+} wt-tree/member? key wt-tree
Returns @code{#t} if @var{wt-tree} contains an association for
@var{key}, otherwise returns @code{#f}.  The average and worst-case
times required by this operation are proportional to the logarithm of
the number of associations in @var{wt-tree}.
@end deffn

@deffn {procedure+} wt-tree/lookup wt-tree key default
Returns the datum associated with @var{key} in @var{wt-tree}.  If
@var{wt-tree} doesn't contain an association for @var{key},
@var{default} is returned.  The average and worst-case times required by
this operation are proportional to the logarithm of the number of
associations in @var{wt-tree}.
@end deffn

@deffn {procedure+} wt-tree/delete wt-tree key
Returns a new tree containing all the associations in @var{wt-tree},
except that if @var{wt-tree} contains an association for @var{key}, it
is removed from the result.  The average and worst-case times required
by this operation are proportional to the logarithm of the number of
associations in @var{wt-tree}.
@end deffn

@deffn {procedure+} wt-tree/delete! wt-tree key
If @var{wt-tree} contains an association for @var{key} the association
is removed.  Returns an unspecified value.  The average and worst-case
times required by this operation are proportional to the logarithm of
the number of associations in @var{wt-tree}.
@end deffn


@node Advanced Operations on Weight-Balanced Trees, Indexing Operations on Weight-Balanced Trees, Basic Operations on Weight-Balanced Trees, Weight-Balanced Trees
@subsection Advanced Operations on Weight-Balanced Trees

In the following the @emph{size} of a tree is the number of associations
that the tree contains, and a @emph{smaller} tree contains fewer
associations.

@deffn {procedure+} wt-tree/split< wt-tree bound
Returns a new tree containing all and only the associations in
@var{wt-tree} which have a key that is less than @var{bound} in the
ordering relation of the tree type of @var{wt-tree}.  The average and
worst-case times required by this operation are proportional to the
logarithm of the size of @var{wt-tree}.
@end deffn

@deffn {procedure+} wt-tree/split> wt-tree bound
Returns a new tree containing all and only the associations in
@var{wt-tree} which have a key that is greater than @var{bound} in the
ordering relation of the tree type of @var{wt-tree}.  The average and
worst-case times required by this operation are proportional to the
logarithm of size of @var{wt-tree}.
@end deffn

@deffn {procedure+} wt-tree/union wt-tree-1 wt-tree-2
Returns a new tree containing all the associations from both trees.
This operation is asymmetric: when both trees have an association for
the same key, the returned tree associates the datum from @var{wt-tree-2}
with the key.  Thus if the trees are viewed as discrete maps then
@code{wt-tree/union} computes the map override of @var{wt-tree-1} by
@var{wt-tree-2}.  If the trees are viewed as sets the result is the set
union of the arguments.
The worst-case time required by this operation
is proportional to the sum of the sizes of both trees.
If the minimum key of one tree is greater than the maximum key of
the other tree then the time required is at worst proportional to
the logarithm of the size of the larger tree.
@end deffn

@deffn {procedure+} wt-tree/intersection wt-tree-1 wt-tree-2
Returns a new tree containing all and only those associations from
@var{wt-tree-1} which have keys appearing as the key of an association
in @var{wt-tree-2}.  Thus the associated data in the result are those
from @var{wt-tree-1}.  If the trees are being used as sets the result is
the set intersection of the arguments.  As a discrete map operation,
@code{wt-tree/intersection} computes the domain restriction of
@var{wt-tree-1} to (the domain of) @var{wt-tree-2}.
The time required by this operation is never worse that proportional to
the sum of the sizes of the trees.
@end deffn

@deffn {procedure+} wt-tree/difference wt-tree-1 wt-tree-2
Returns a new tree containing all and only those associations from
@var{wt-tree-1} which have keys that @emph{do not} appear as the key of
an association in @var{wt-tree-2}.  If the trees are viewed as sets the
result is the asymmetric set difference of the arguments.  As a discrete
map operation, it computes the domain restriction of @var{wt-tree-1} to
the complement of (the domain of) @var{wt-tree-2}.
The time required by this operation is never worse that proportional to
the sum of the sizes of the trees.
@end deffn


@deffn {procedure+} wt-tree/subset? wt-tree-1 wt-tree-2
Returns @code{#t} iff the key of each association in @var{wt-tree-1} is
the key of some association in @var{wt-tree-2}, otherwise returns @code{#f}.
Viewed as a set operation, @code{wt-tree/subset?} is the improper subset
predicate.
A proper subset predicate can be constructed:

@example
(define (proper-subset? s1 s2)
  (and (wt-tree/subset? s1 s2)
       (< (wt-tree/size s1) (wt-tree/size s2))))
@end example

As a discrete map operation, @code{wt-tree/subset?} is the subset
test on the domain(s) of the map(s).  In the worst-case the time
required by this operation is proportional to the size of
@var{wt-tree-1}.
@end deffn


@deffn {procedure+} wt-tree/set-equal? wt-tree-1 wt-tree-2
Returns @code{#t} iff for every association in @var{wt-tree-1} there is
an association in @var{wt-tree-2} that has the same key, and @emph{vice
versa}.

Viewing the arguments as sets @code{wt-tree/set-equal?} is the set
equality predicate.  As a map operation it determines if two maps are
defined on the same domain.

This procedure is equivalent to

@example
(lambda (wt-tree-1 wt-tree-2)
  (and (wt-tree/subset? wt-tree-1 wt-tree-2
       (wt-tree/subset? wt-tree-2 wt-tree-1)))
@end example

In the worst-case the time required by this operation is proportional to
the size of the smaller tree.
@end deffn


@deffn {procedure+} wt-tree/fold combiner initial wt-tree
This procedure reduces @var{wt-tree} by combining all the associations,
using an reverse in-order traversal, so the associations are visited in
reverse order.  @var{Combiner} is a procedure of three arguments: a key,
a datum and the accumulated result so far.  Provided @var{combiner}
takes time bounded by a constant, @code{wt-tree/fold} takes time
proportional to the size of @var{wt-tree}.

A sorted association list can be derived simply:

@example
(wt-tree/fold  (lambda (key datum list)
                 (cons (cons key datum) list))
               '()
               @var{wt-tree}))
@end example

The data in the associations can be summed like this:

@example
(wt-tree/fold  (lambda (key datum sum) (+ sum datum))
               0
               @var{wt-tree})
@end example
@end deffn

@deffn {procedure+} wt-tree/for-each action wt-tree
This procedure traverses the tree in-order, applying @var{action} to
each association.
The associations are processed in increasing order of their keys.
@var{Action} is a procedure of two arguments which take the key and
datum respectively of the association.
Provided @var{action} takes time bounded by a constant,
@code{wt-tree/for-each} takes time proportional to in the size of
@var{wt-tree}.
The example prints the tree:

@example
(wt-tree/for-each (lambda (key value)
                    (display (list key value)))
                  @var{wt-tree}))
@end example
@end deffn


@node Indexing Operations on Weight-Balanced Trees,  , Advanced Operations on Weight-Balanced Trees, Weight-Balanced Trees
@subsection Indexing Operations on Weight-Balanced Trees

Weight balanced trees support operations that view the tree as sorted
sequence of associations.  Elements of the sequence can be accessed by
position, and the position of an element in the sequence can be
determined, both in logarthmic time.

@deffn {procedure+} wt-tree/index wt-tree index
@deffnx {procedure+} wt-tree/index-datum wt-tree index
@deffnx {procedure+} wt-tree/index-pair wt-tree index
Returns the 0-based @var{index}th association of @var{wt-tree} in the
sorted sequence under the tree's ordering relation on the keys.
@code{wt-tree/index} returns the @var{index}th key,
@code{wt-tree/index-datum} returns the datum associated with the
@var{index}th key and @code{wt-tree/index-pair} returns a new pair
@code{(@var{key} . @var{datum})} which is the @code{cons} of the
@var{index}th key and its datum.  The average and worst-case times
required by this operation are proportional to the logarithm of the
number of associations in the tree.

These operations signal an error if the tree is empty, if
@var{index}@code{<0}, or if @var{index} is greater than or equal to the
number of associations in the tree.

Indexing can be used to find the median and maximum keys in the tree as
follows:
@end deffn

@example
median:  (wt-tree/index @var{wt-tree} (quotient (wt-tree/size @var{wt-tree}) 2))

maximum: (wt-tree/index @var{wt-tree} (-1+ (wt-tree/size @var{wt-tree})))
@end example

@deffn {procedure+} wt-tree/rank wt-tree key
Determines the 0-based position of @var{key} in the sorted sequence of
the keys under the tree's ordering relation, or @code{#f} if the tree
has no association with for @var{key}.  This procedure returns either an
exact non-negative integer or @code{#f}.  The average and worst-case
times required by this operation are proportional to the logarithm of
the number of associations in the tree.
@end deffn

@deffn {procedure+} wt-tree/min wt-tree
@deffnx {procedure+} wt-tree/min-datum wt-tree
@deffnx {procedure+} wt-tree/min-pair wt-tree
Returns the association of @var{wt-tree} that has the least key under
the tree's ordering relation.  @code{wt-tree/min} returns the least key,
@code{wt-tree/min-datum} returns the datum associated with the least key
and @code{wt-tree/min-pair} returns a new pair @code{(key . datum)}
which is the @code{cons} of the minimum key and its datum.  The average
and worst-case times required by this operation are proportional to the
logarithm of the number of associations in the tree.

These operations signal an error if the tree is empty.
They could be written
@example
(define (wt-tree/min tree)        (wt-tree/index tree 0))
(define (wt-tree/min-datum tree)  (wt-tree/index-datum tree 0))
(define (wt-tree/min-pair tree)   (wt-tree/index-pair tree 0))
@end example
@end deffn

@deffn {procedure+} wt-tree/delete-min wt-tree
Returns a new tree containing all of the associations in @var{wt-tree}
except the association with the least key under the @var{wt-tree}'s
ordering relation.  An error is signalled if the tree is empty.  The
average and worst-case times required by this operation are proportional
to the logarithm of the number of associations in the tree.  This
operation is equivalent to

@example
(wt-tree/delete @var{wt-tree} (wt-tree/min @var{wt-tree}))
@end example
@end deffn


@deffn {procedure+} wt-tree/delete-min! wt-tree
Removes the association with the least key under the @var{wt-tree}'s
ordering relation.  An error is signalled if the tree is empty.  The
average and worst-case times required by this operation are proportional
to the logarithm of the number of associations in the tree.  This
operation is equivalent to

@example
(wt-tree/delete! @var{wt-tree} (wt-tree/min @var{wt-tree}))
@end example
@end deffn


@node Other Packages, About SLIB, Database Packages, Top
@chapter Other Packages

@menu
* Data Structures::             Various data structures.
* Sorting and Searching::       
* Procedures::                  Miscellaneous utility procedures.
* Standards Support::           Support for Scheme Standards.
* Session Support::             REPL and Debugging.
* System Interface::            'system, 'getenv, and other programs.
* Extra-SLIB Packages::         Outside the envelope.
@end menu


@node Data Structures, Sorting and Searching, Other Packages, Other Packages
@section Data Structures



@menu
* Arrays::                      'array
* Subarrays::                   'subarray
* Array Mapping::               'array-for-each
* Array Interpolation::         'array-interpolate
* Association Lists::           'alist
* Byte::                        'byte
* Byte/Number Conversions::     'byte-number
* MAT-File Format::             'matfile
* Portable Image Files::        'pnm
* Collections::                 'collect
* Dynamic Data Type::           'dynamic
* Hash Tables::                 'hash-table
* Object::                      'object
* Priority Queues::             'priority-queue
* Queues::                      'queue
* Records::                     'record
@end menu




@node Arrays, Subarrays, Data Structures, Data Structures
@subsection Arrays

@include array.txi


@node Subarrays, Array Mapping, Arrays, Data Structures
@subsection Subarrays

@include subarray.txi


@node Array Mapping, Array Interpolation, Subarrays, Data Structures
@subsection Array Mapping

@include arraymap.txi


@node Array Interpolation, Association Lists, Array Mapping, Data Structures
@subsection Array Interpolation

@include linterp.txi


@node Association Lists, Byte, Array Interpolation, Data Structures
@subsection Association Lists

@include alist.txi


@node Byte, Byte/Number Conversions, Association Lists, Data Structures
@subsection Byte

@include byte.txi


@node Byte/Number Conversions, MAT-File Format, Byte, Data Structures
@subsection Byte/Number Conversions

@include bytenumb.txi


@node MAT-File Format, Portable Image Files, Byte/Number Conversions, Data Structures
@subsection MAT-File Format

@include matfile.txi


@node Portable Image Files, Collections, MAT-File Format, Data Structures
@subsection Portable Image Files

@include pnm.txi


@node Collections, Dynamic Data Type, Portable Image Files, Data Structures
@subsection Collections

@c Much of the documentation in this section was written by Dave Love
@c (d.love@dl.ac.uk) -- don't blame Ken Dickey for its faults.
@c but we can blame him for not writing it!

@code{(require 'collect)}
@ftindex collect

@noindent
Routines for managing collections.  Collections are aggregate data
structures supporting iteration over their elements, similar to the
Dylan(TM) language, but with a different interface.  They have
@dfn{elements} indexed by corresponding @dfn{keys}, although the keys
may be implicit (as with lists).

@noindent
New types of collections may be defined as YASOS objects (@pxref{Yasos}).
They must support the following operations:

@itemize @bullet
@item
@code{(collection? @var{self})} (always returns @code{#t});

@item
@code{(size @var{self})} returns the number of elements in the collection;

@item
@code{(print @var{self} @var{port})} is a specialized print operation
for the collection which prints a suitable representation on the given
@var{port} or returns it as a string if @var{port} is @code{#t};

@item
@findex gen-elts
@code{(gen-elts @var{self})} returns a thunk which on successive
invocations yields elements of @var{self} in order or gives an error if
it is invoked more than @code{(size @var{self})} times;

@item
@findex gen-keys
@code{(gen-keys @var{self})} is like @code{gen-elts}, but yields the
collection's keys in order.
@end itemize

@noindent
They might support specialized @code{for-each-key} and
@code{for-each-elt} operations.



@defun collection? obj
A predicate, true initially of lists, vectors and strings.  New sorts of
collections must answer @code{#t} to @code{collection?}.
@end defun

@deffn {Procedure} map-elts proc collection1 @dots{}
@deffnx {Procedure} do-elts proc collection1 @dots{}
@var{proc} is a procedure taking as many arguments as there are
@var{collections} (at least one).  The @var{collections} are iterated
over in their natural order and @var{proc} is applied to the elements
yielded by each iteration in turn.  The order in which the arguments are
supplied corresponds to te order in which the @var{collections} appear.
@code{do-elts} is used when only side-effects of @var{proc} are of
interest and its return value is unspecified.  @code{map-elts} returns a
collection (actually a vector) of the results of the applications of
@var{proc}.

Example:
@lisp
(map-elts + (list 1 2 3) (vector 1 2 3))
   @result{} #(2 4 6)
@end lisp
@end deffn

@deffn {Procedure} map-keys proc collection1 @dots{}
@deffnx {Procedure} do-keys proc collection1 @dots{}
These are analogous to @code{map-elts} and @code{do-elts}, but each
iteration is over the @var{collections}' @emph{keys} rather than their
elements.

Example:
@lisp
(map-keys + (list 1 2 3) (vector 1 2 3))
   @result{} #(0 2 4)
@end lisp
@end deffn

@deffn {Procedure} for-each-key collection proc
@deffnx {Procedure} for-each-elt collection proc
These are like @code{do-keys} and @code{do-elts} but only for a single
collection; they are potentially more efficient.
@end deffn

@defun reduce proc seed collection1 @dots{}
A generalization of the list-based @code{reduce-init}
(@pxref{Lists as sequences}) to collections which will shadow the
list-based version if @code{(require 'collect)} follows
@ftindex collect
@code{(require 'common-list-functions)} (@pxref{Common List
Functions}).
@ftindex common-list-functions

Examples:
@lisp
(reduce + 0 (vector 1 2 3))
   @result{} 6
(reduce union '() '((a b c) (b c d) (d a)))
   @result{} (c b d a).
@end lisp
@end defun

@defun any? pred collection1 @dots{}
A generalization of the list-based @code{some} (@pxref{Lists as
sequences}) to collections.

Example:
@lisp
(any? odd? (list 2 3 4 5))
   @result{} #t
@end lisp
@end defun

@defun every? pred collection1 @dots{}
A generalization of the list-based @code{every}
(@pxref{Lists as sequences}) to collections.

Example:
@lisp
(every? collection? '((1 2) #(1 2)))
   @result{} #t
@end lisp
@end defun

@defun empty? collection
Returns @code{#t} iff there are no elements in @var{collection}.

@code{(empty? @var{collection}) @equiv{} (zero? (size @var{collection}))}
@end defun

@defun size collection
Returns the number of elements in @var{collection}.
@end defun

@defun Setter list-ref
See @ref{Setters} for a definition of @dfn{setter}.  N.B.
@code{(setter list-ref)} doesn't work properly for element 0 of a
list.
@end defun

Here is a sample collection: @code{simple-table} which is also a
@code{table}.
@lisp
(define-predicate TABLE?)
(define-operation (LOOKUP table key failure-object))
(define-operation (ASSOCIATE! table key value)) ;; returns key
(define-operation (REMOVE! table key))          ;; returns value

(define (MAKE-SIMPLE-TABLE)
  (let ( (table (list)) )
    (object
     ;; table behaviors
     ((TABLE? self) #t)
     ((SIZE self) (size table))
     ((PRINT self port) (format port "#<SIMPLE-TABLE>"))
     ((LOOKUP self key failure-object)
      (cond
       ((assq key table) => cdr)
       (else failure-object)
       ))
     ((ASSOCIATE! self key value)
      (cond
       ((assq key table)
        => (lambda (bucket) (set-cdr! bucket value) key))
       (else
        (set! table (cons (cons key value) table))
        key)
       ))
     ((REMOVE! self key);; returns old value
      (cond
       ((null? table) (slib:error "TABLE:REMOVE! Key not found: " key))
       ((eq? key (caar table))
        (let ( (value (cdar table)) )
          (set! table (cdr table))
          value)
        )
       (else
        (let loop ( (last table) (this (cdr table)) )
          (cond
           ((null? this)
            (slib:error "TABLE:REMOVE! Key not found: " key))
           ((eq? key (caar this))
            (let ( (value (cdar this)) )
              (set-cdr! last (cdr this))
              value)
            )
           (else
            (loop (cdr last) (cdr this)))
           ) ) )
       ))
@group
     ;; collection behaviors
     ((COLLECTION? self) #t)
     ((GEN-KEYS self) (collect:list-gen-elts (map car table)))
     ((GEN-ELTS self) (collect:list-gen-elts (map cdr table)))
     ((FOR-EACH-KEY self proc)
      (for-each (lambda (bucket) (proc (car bucket))) table)
      )
     ((FOR-EACH-ELT self proc)
      (for-each (lambda (bucket) (proc (cdr bucket))) table)
      ) ) ) )
@end group
@end lisp





@node Dynamic Data Type, Hash Tables, Collections, Data Structures
@subsection Dynamic Data Type

@code{(require 'dynamic)}
@ftindex dynamic

@defun make-dynamic obj
Create and returns a new @dfn{dynamic} whose global value is @var{obj}.
@end defun

@defun dynamic? obj
Returns true if and only if @var{obj} is a dynamic.  No object
satisfying @code{dynamic?} satisfies any of the other standard type
predicates.
@end defun

@defun dynamic-ref dyn
Return the value of the given dynamic in the current dynamic
environment.
@end defun

@deffn {Procedure} dynamic-set! dyn obj
Change the value of the given dynamic to @var{obj} in the current
dynamic environment.  The returned value is unspecified.
@end deffn

@defun call-with-dynamic-binding dyn obj thunk
Invoke and return the value of the given thunk in a new, nested dynamic
environment in which the given dynamic has been bound to a new location
whose initial contents are the value @var{obj}.  This dynamic
environment has precisely the same extent as the invocation of the thunk
and is thus captured by continuations created within that invocation and
re-established by those continuations when they are invoked.
@end defun

The @code{dynamic-bind} macro is not implemented.




@node Hash Tables, Object, Dynamic Data Type, Data Structures
@subsection Hash Tables

@include hashtab.txi



@node Object, Priority Queues, Hash Tables, Data Structures
@subsection Macroless Object System

@include object.texi


@node Priority Queues, Queues, Object, Data Structures
@subsection Priority Queues

@include priorque.txi


@node Queues, Records, Priority Queues, Data Structures
@subsection Queues

@include queue.txi



@node Records,  , Queues, Data Structures
@subsection Records

@code{(require 'record)}
@ftindex record

The Record package provides a facility for user to define their own
record data types.

@defun make-record-type type-name field-names
Returns a @dfn{record-type descriptor}, a value representing a new data
type disjoint from all others.  The @var{type-name} argument must be a
string, but is only used for debugging purposes (such as the printed
representation of a record of the new type).  The @var{field-names}
argument is a list of symbols naming the @dfn{fields} of a record of the
new type.  It is an error if the list contains any duplicates.  It is
unspecified how record-type descriptors are represented.
@end defun

@c @defun make-record-sub-type type-name field-names rtd
@c Returns a @dfn{record-type descriptor}, a value representing a new data
@c type, disjoint from all others.  The @var{type-name} argument must be a
@c string.  The @var{field-names} argument is a list of symbols naming the
@c additional @dfn{fields} to be appended to @var{field-names} of
@c @var{rtd}.  It is an error if the combined list contains any
@c duplicates.
@c
@c Record-modifiers and record-accessors for @var{rtd} work for the new
@c record-sub-type as well.  But record-modifiers and record-accessors for
@c the new record-sub-type will not neccessarily work for @var{rtd}.
@c @end defun

@defun record-constructor rtd [field-names]
Returns a procedure for constructing new members of the type represented
by @var{rtd}.  The returned procedure accepts exactly as many arguments
as there are symbols in the given list, @var{field-names}; these are
used, in order, as the initial values of those fields in a new record,
which is returned by the constructor procedure.  The values of any
fields not named in that list are unspecified.  The @var{field-names}
argument defaults to the list of field names in the call to
@code{make-record-type} that created the type represented by @var{rtd};
if the @var{field-names} argument is provided, it is an error if it
contains any duplicates or any symbols not in the default list.
@end defun

@defun record-predicate rtd
Returns a procedure for testing membership in the type represented by
@var{rtd}.  The returned procedure accepts exactly one argument and
returns a true value if the argument is a member of the indicated record
type; it returns a false value otherwise.
@end defun

@c @defun record-sub-predicate rtd
@c Returns a procedure for testing membership in the type represented by
@c @var{rtd} or its parents.  The returned procedure accepts exactly one
@c argument and returns a true value if the argument is a member of the
@c indicated record type or its parents; it returns a false value
@c otherwise.
@c @end defun

@defun record-accessor rtd field-name
Returns a procedure for reading the value of a particular field of a
member of the type represented by @var{rtd}.  The returned procedure
accepts exactly one argument which must be a record of the appropriate
type; it returns the current value of the field named by the symbol
@var{field-name} in that record.  The symbol @var{field-name} must be a
member of the list of field-names in the call to @code{make-record-type}
that created the type represented by @var{rtd}.
@end defun


@defun record-modifier rtd field-name
Returns a procedure for writing the value of a particular field of a
member of the type represented by @var{rtd}.  The returned procedure
accepts exactly two arguments: first, a record of the appropriate type,
and second, an arbitrary Scheme value; it modifies the field named by
the symbol @var{field-name} in that record to contain the given value.
The returned value of the modifier procedure is unspecified.  The symbol
@var{field-name} must be a member of the list of field-names in the call
to @code{make-record-type} that created the type represented by
@var{rtd}.
@end defun

In May of 1996, as a product of discussion on the @code{rrrs-authors}
mailing list, I rewrote @file{record.scm} to portably implement type
disjointness for record data types.

As long as an implementation's procedures are opaque and the
@code{record} code is loaded before other programs, this will give
disjoint record types which are unforgeable and incorruptible by R4RS
procedures.

As a consequence, the procedures @code{record?},
@code{record-type-descriptor}, @code{record-type-name}.and
@code{record-type-field-names} are no longer supported.

@ignore
@defun record? obj
Returns a true value if @var{obj} is a record of any type and a false
value otherwise.  Note that @code{record?} may be true of any Scheme
value; of course, if it returns true for some particular value, then
@code{record-type-descriptor} is applicable to that value and returns an
appropriate descriptor.
@end defun

@defun record-type-descriptor record
Returns a record-type descriptor representing the type of the given
record.  That is, for example, if the returned descriptor were passed to
@code{record-predicate}, the resulting predicate would return a true
value when passed the given record.  Note that it is not necessarily the
case that the returned descriptor is the one that was passed to
@code{record-constructor} in the call that created the constructor
procedure that created the given record.
@end defun

@defun record-type-name rtd
Returns the type-name associated with the type represented by rtd.  The
returned value is @code{eqv?} to the @var{type-name} argument given in
the call to @code{make-record-type} that created the type represented by
@var{rtd}.
@end defun

@defun record-type-field-names rtd
Returns a list of the symbols naming the fields in members of the type
represented by @var{rtd}.  The returned value is @code{equal?} to the
field-names argument given in the call to @code{make-record-type} that
created the type represented by @var{rtd}.
@end defun
@end ignore



@node Sorting and Searching, Procedures, Data Structures, Other Packages
@section Sorting and Searching

@menu
* Common List Functions::       'common-list-functions
* Tree Operations::             'tree
* Chapter Ordering::            'chapter-order
* Sorting::                     'sort
* Topological Sort::            Keep your socks on.
* Hashing::                     'hash
* Space-Filling Curves::        'hilbert and 'sierpinski
* Soundex::                     Dimension Reduction of Last Names
* String Search::               Also Search from a Port.
* Sequence Comparison::         'diff and longest-common-subsequence
@end menu



@node Common List Functions, Tree Operations, Sorting and Searching, Sorting and Searching
@subsection Common List Functions

@code{(require 'common-list-functions)}
@ftindex common-list-functions

The procedures below follow the Common LISP equivalents apart from
optional arguments in some cases.

@menu
* List construction::           
* Lists as sets::               
* Lists as sequences::          
* Destructive list operations::  
* Non-List functions::          
@end menu


@node List construction, Lists as sets, Common List Functions, Common List Functions
@subsubsection List construction

@defun make-list k
@defunx make-list k init
@code{make-list} creates and returns a list of @var{k} elements.  If
@var{init} is included, all elements in the list are initialized to
@var{init}.

Example:
@lisp
(make-list 3)
   @result{} (#<unspecified> #<unspecified> #<unspecified>)
(make-list 5 'foo)
   @result{} (foo foo foo foo foo)
@end lisp
@end defun


@defun list* obj1 obj2 @dots{}
Works like @code{list} except that the cdr of the last pair is the last
argument unless there is only one argument, when the result is just that
argument.  Sometimes called @code{cons*}.  E.g.:

@lisp
(list* 1)
   @result{} 1
(list* 1 2 3)
   @result{} (1 2 . 3)
(list* 1 2 '(3 4))
   @result{} (1 2 3 4)
(list* @var{args} '())
   @equiv{} (list @var{args})
@end lisp
@end defun

@defun copy-list lst
@code{copy-list} makes a copy of @var{lst} using new pairs and returns
it. Only the top level of the list is copied, i.e., pairs forming
elements of the copied list remain @code{eq?} to the corresponding
elements of the original; the copy is, however, not @code{eq?} to the
original, but is @code{equal?} to it.

Example:
@lisp
(copy-list '(foo foo foo))
   @result{} (foo foo foo)
(define q '(foo bar baz bang))
(define p q)
(eq? p q)
   @result{} #t
(define r (copy-list q))
(eq? q r)
   @result{} #f
(equal? q r)
   @result{} #t
(define bar '(bar))
(eq? bar (car (copy-list (list bar 'foo))))
@result{} #t
   @end lisp
@end defun






@node Lists as sets, Lists as sequences, List construction, Common List Functions
@subsubsection Lists as sets

@code{eqv?} is used to test for membership by procedures which treat
lists as sets.

@defun adjoin e l
@code{adjoin} returns the adjoint of the element @var{e} and the list
@var{l}.  That is, if @var{e} is in @var{l}, @code{adjoin} returns
@var{l}, otherwise, it returns @code{(cons @var{e} @var{l})}.

Example:
@lisp
(adjoin 'baz '(bar baz bang))
   @result{} (bar baz bang)
(adjoin 'foo '(bar baz bang))
   @result{} (foo bar baz bang)
@end lisp
@end defun

@defun union l1 l2
@code{union} returns a list of all elements that are in @var{l1} or
@var{l2}.  Duplicates between @var{l1} and @var{l2} are culled.
Duplicates within @var{l1} or within @var{l2} may or may not be
removed.

Example:
@lisp
(union '(1 2 3 4) '(5 6 7 8))
   @result{} (1 2 3 4 5 6 7 8)
(union '(0 1 2 3 4) '(3 4 5 6))
   @result{} (5 6 0 1 2 3 4)
@end lisp
@end defun

@defun intersection l1 l2
@code{intersection} returns a list of all elements that are in both
@var{l1} and @var{l2}.

Example:
@lisp
(intersection '(1 2 3 4) '(3 4 5 6))
   @result{} (3 4)
(intersection '(1 2 3 4) '(5 6 7 8))
   @result{} ()
@end lisp
@end defun

@defun set-difference l1 l2
@code{set-difference} returns a list of all elements that are in
@var{l1} but not in @var{l2}.

Example:
@lisp
(set-difference '(1 2 3 4) '(3 4 5 6))
   @result{} (1 2)
(set-difference '(1 2 3 4) '(1 2 3 4 5 6))
   @result{} ()
@end lisp
@end defun

@defun subset? list1 list2
Returns @code{#t} if every element of @var{list1} is @code{eqv?} an
element of @var{list2}; otherwise returns @code{#f}.

Example:
@lisp
(subset? '(1 2 3 4) '(3 4 5 6))
   @result{} #f
(subset? '(1 2 3 4) '(6 5 4 3 2 1 0))
   @result{} #t
@end lisp
@end defun

@defun member-if pred lst
@code{member-if} returns the list headed by the first element of
@var{lst} to satisfy @code{(@var{pred} @var{element})}.
@code{Member-if} returns @code{#f} if @var{pred} returns @code{#f} for
every @var{element} in @var{lst}.

Example:
@lisp
(member-if vector? '(a 2 b 4))
   @result{} #f
(member-if number? '(a 2 b 4))
   @result{} (2 b 4)
@end lisp
@end defun

@defun some pred lst1 lst2 @dots{}
@var{pred} is a boolean function of as many arguments as there are list
arguments to @code{some} i.e., @var{lst} plus any optional arguments.
@var{pred} is applied to successive elements of the list arguments in
order.  @code{some} returns @code{#t} as soon as one of these
applications returns @code{#t}, and is @code{#f} if none returns
@code{#t}.  All the lists should have the same length.


Example:
@lisp
(some odd? '(1 2 3 4))
   @result{} #t

(some odd? '(2 4 6 8))
   @result{} #f

(some > '(1 3) '(2 4))
   @result{} #f
@end lisp
@end defun

@defun every pred lst1 lst2 @dots{}
@code{every} is analogous to @code{some} except it returns @code{#t} if
every application of @var{pred} is @code{#t} and @code{#f}
otherwise.

Example:
@lisp
(every even? '(1 2 3 4))
   @result{} #f

(every even? '(2 4 6 8))
   @result{} #t

(every > '(2 3) '(1 4))
   @result{} #f
@end lisp
@end defun

@defun notany pred lst1 @dots{}
@code{notany} is analogous to @code{some} but returns @code{#t} if no
application of @var{pred} returns @code{#t} or @code{#f} as soon as any
one does.
@end defun

@defun notevery pred lst1 @dots{}
@code{notevery} is analogous to @code{some} but returns @code{#t} as soon
as an application of @var{pred} returns @code{#f}, and @code{#f}
otherwise.

Example:
@lisp
(notevery even? '(1 2 3 4))
   @result{} #t

(notevery even? '(2 4 6 8))
   @result{} #f
@end lisp
@end defun


@defun list-of?? predicate
Returns a predicate which returns true if its argument is a list every
element of which satisfies @var{predicate}.

@defunx list-of?? predicate low-bound high-bound
@var{low-bound} and @var{high-bound} are non-negative integers.
@code{list-of??} returns a predicate which returns true if its argument
is a list of length between @var{low-bound} and @var{high-bound}
(inclusive); every element of which satisfies @var{predicate}.

@defunx list-of?? predicate bound
@var{bound} is an integer.  If @var{bound} is negative, @code{list-of??}
returns a predicate which returns true if its argument is a list of
length greater than @code{(- @var{bound})}; every element of which
satisfies @var{predicate}.  Otherwise, @code{list-of??}  returns a
predicate which returns true if its argument is a list of length less
than or equal to @var{bound}; every element of which satisfies
@var{predicate}.
@end defun


@defun find-if pred lst
@code{find-if} searches for the first @var{element} in @var{lst} such
that @code{(@var{pred} @var{element})} returns @code{#t}.  If it finds
any such @var{element} in @var{lst}, @var{element} is returned.
Otherwise, @code{#f} is returned.

Example:
@lisp
(find-if number? '(foo 1 bar 2))
   @result{} 1

(find-if number? '(foo bar baz bang))
   @result{} #f

(find-if symbol? '(1 2 foo bar))
   @result{} foo
@end lisp
@end defun

@defun remove elt lst
@code{remove} removes all occurrences of @var{elt} from @var{lst} using
@code{eqv?} to test for equality and returns everything that's left.
N.B.: other implementations (Chez, Scheme->C and T, at least) use
@code{equal?} as the equality test.

Example:
@lisp
(remove 1 '(1 2 1 3 1 4 1 5))
   @result{} (2 3 4 5)

(remove 'foo '(bar baz bang))
   @result{} (bar baz bang)
@end lisp
@end defun

@defun remove-if pred lst
@code{remove-if} removes all @var{element}s from @var{lst} where
@code{(@var{pred} @var{element})} is @code{#t} and returns everything
that's left.

Example:
@lisp
(remove-if number? '(1 2 3 4))
   @result{} ()

(remove-if even? '(1 2 3 4 5 6 7 8))
   @result{} (1 3 5 7)
@end lisp
@end defun

@defun remove-if-not pred lst
@code{remove-if-not} removes all @var{element}s from @var{lst} for which
@code{(@var{pred} @var{element})} is @code{#f} and returns everything that's
left.

Example:
@lisp
(remove-if-not number? '(foo bar baz))
   @result{} ()
(remove-if-not odd? '(1 2 3 4 5 6 7 8))
   @result{} (1 3 5 7)
@end lisp
@end defun

@defun has-duplicates? lst
returns @code{#t} if 2 members of @var{lst} are @code{equal?}, @code{#f}
otherwise.

Example:
@lisp
(has-duplicates? '(1 2 3 4))
   @result{} #f

(has-duplicates? '(2 4 3 4))
   @result{} #t
@end lisp
@end defun

The procedure @code{remove-duplicates} uses @code{member} (rather than
@code{memv}).

@defun remove-duplicates lst
returns a copy of @var{lst} with its duplicate members removed.
Elements are considered duplicate if they are @code{equal?}.

Example:
@lisp
(remove-duplicates '(1 2 3 4))
   @result{} (1 2 3 4)

(remove-duplicates '(2 4 3 4))
   @result{} (2 4 3)
@end lisp
@end defun


@node Lists as sequences, Destructive list operations, Lists as sets, Common List Functions
@subsubsection Lists as sequences

@defun position obj lst
@code{position} returns the 0-based position of @var{obj} in @var{lst},
or @code{#f} if @var{obj} does not occur in @var{lst}.

Example:
@lisp
(position 'foo '(foo bar baz bang))
   @result{} 0
(position 'baz '(foo bar baz bang))
   @result{} 2
(position 'oops '(foo bar baz bang))
   @result{} #f
@end lisp
@end defun

@defun reduce p lst
@code{reduce} combines all the elements of a sequence using a binary
operation (the combination is left-associative).  For example, using
@code{+}, one can add up all the elements.  @code{reduce} allows you to
apply a function which accepts only two arguments to more than 2
objects.  Functional programmers usually refer to this as @dfn{foldl}.
@code{collect:reduce} (@pxref{Collections}) provides a version of
@code{collect} generalized to collections.

Example:
@lisp
(reduce + '(1 2 3 4))
   @result{} 10
(define (bad-sum . l) (reduce + l))
(bad-sum 1 2 3 4)
   @equiv{} (reduce + (1 2 3 4))
   @equiv{} (+ (+ (+ 1 2) 3) 4)
@result{} 10
(bad-sum)
   @equiv{} (reduce + ())
   @result{} ()
(reduce string-append '("hello" "cruel" "world"))
   @equiv{} (string-append (string-append "hello" "cruel") "world")
   @result{} "hellocruelworld"
(reduce anything '())
   @result{} ()
(reduce anything '(x))
   @result{} x
@end lisp

What follows is a rather non-standard implementation of @code{reverse}
in terms of @code{reduce} and a combinator elsewhere called
@dfn{C}.

@lisp
;;; Contributed by Jussi Piitulainen (jpiitula @@ ling.helsinki.fi)

(define commute
  (lambda (f)
    (lambda (x y)
      (f y x))))

(define reverse
  (lambda (args)
    (reduce-init (commute cons) '() args)))
@end lisp
@end defun

@defun reduce-init p init lst
@code{reduce-init} is the same as reduce, except that it implicitly
inserts @var{init} at the start of the list.  @code{reduce-init} is
preferred if you want to handle the null list, the one-element, and
lists with two or more elements consistently.  It is common to use the
operator's idempotent as the initializer.  Functional programmers
usually call this @dfn{foldl}.

Example:
@lisp
(define (sum . l) (reduce-init + 0 l))
(sum 1 2 3 4)
   @equiv{} (reduce-init + 0 (1 2 3 4))
   @equiv{} (+ (+ (+ (+ 0 1) 2) 3) 4)
   @result{} 10
(sum)
   @equiv{} (reduce-init + 0 '())
   @result{} 0

(reduce-init string-append "@@" '("hello" "cruel" "world"))
@equiv{}
(string-append (string-append (string-append "@@" "hello")
                               "cruel")
               "world")
@result{} "@@hellocruelworld"
@end lisp

Given a differentiation of 2 arguments, @code{diff}, the following will
differentiate by any number of variables.
@lisp
(define (diff* exp . vars)
  (reduce-init diff exp vars))
@end lisp

Example:
@lisp
;;; Real-world example:  Insertion sort using reduce-init.

(define (insert l item)
  (if (null? l)
      (list item)
      (if (< (car l) item)
          (cons (car l) (insert (cdr l) item))
          (cons item l))))
(define (insertion-sort l) (reduce-init insert '() l))

(insertion-sort '(3 1 4 1 5)
   @equiv{} (reduce-init insert () (3 1 4 1 5))
   @equiv{} (insert (insert (insert (insert (insert () 3) 1) 4) 1) 5)
   @equiv{} (insert (insert (insert (insert (3)) 1) 4) 1) 5)
   @equiv{} (insert (insert (insert (1 3) 4) 1) 5)
   @equiv{} (insert (insert (1 3 4) 1) 5)
   @equiv{} (insert (1 1 3 4) 5)
   @result{} (1 1 3 4 5)
   @end lisp
@end defun

@defun last lst n
@code{last} returns the last @var{n} elements of @var{lst}.  @var{n}
must be a non-negative integer.

Example:
@lisp
(last '(foo bar baz bang) 2)
   @result{} (baz bang)
(last '(1 2 3) 0)
   @result{} 0
@end lisp
@end defun

@defun butlast lst n
@code{butlast} returns all but the last @var{n} elements of
@var{lst}.

Example:
@lisp
(butlast '(a b c d) 3)
   @result{} (a)
(butlast '(a b c d) 4)
   @result{} ()
@end lisp
@end defun

@noindent
@code{last} and @code{butlast} split a list into two parts when given
identical arguments.
@example
(last '(a b c d e) 2)
   @result{} (d e)
(butlast '(a b c d e) 2)
   @result{} (a b c)
@end example

@defun nthcdr n lst
@code{nthcdr} takes @var{n} @code{cdr}s of @var{lst} and returns the
result.  Thus @code{(nthcdr 3 @var{lst})} @equiv{} @code{(cdddr
@var{lst})}

Example:
@lisp
(nthcdr 2 '(a b c d))
   @result{} (c d)
(nthcdr 0 '(a b c d))
   @result{} (a b c d)
@end lisp
@end defun

@defun butnthcdr n lst
@code{butnthcdr} returns all but the nthcdr @var{n} elements of
@var{lst}.

Example:
@lisp
(butnthcdr 3 '(a b c d))
   @result{} (a b c)
(butnthcdr 4 '(a b c d))
   @result{} (a b c d)
@end lisp
@end defun

@noindent
@code{nthcdr} and @code{butnthcdr} split a list into two parts when
given identical arguments.
@example
(nthcdr 2 '(a b c d e))
   @result{} (c d e)
(butnthcdr 2 '(a b c d e))
   @result{} (a b)
@end example



@node Destructive list operations, Non-List functions, Lists as sequences, Common List Functions
@subsubsection Destructive list operations

These procedures may mutate the list they operate on, but any such
mutation is undefined.

@deffn {Procedure} nconc args
@code{nconc} destructively concatenates its arguments.  (Compare this
with @code{append}, which copies arguments rather than destroying them.)
Sometimes called @code{append!} (@pxref{Rev2 Procedures}).

Example:  You want to find the subsets of a set.  Here's the obvious way:

@lisp
(define (subsets set)
  (if (null? set)
      '(())
      (append (map (lambda (sub) (cons (car set) sub))
                   (subsets (cdr set)))
              (subsets (cdr set)))))
@end lisp
But that does way more consing than you need.  Instead, you could
replace the @code{append} with @code{nconc}, since you don't have any
need for all the intermediate results.

Example:
@lisp
(define x '(a b c))
(define y '(d e f))
(nconc x y)
   @result{} (a b c d e f)
x
   @result{} (a b c d e f)
@end lisp

@code{nconc} is the same as @code{append!} in @file{sc2.scm}.
@end deffn

@deffn {Procedure} nreverse lst
@code{nreverse} reverses the order of elements in @var{lst} by mutating
@code{cdr}s of the list.  Sometimes called @code{reverse!}.

Example:
@lisp
(define foo '(a b c))
(nreverse foo)
   @result{} (c b a)
foo
   @result{} (a)
@end lisp

Some people have been confused about how to use @code{nreverse},
thinking that it doesn't return a value.  It needs to be pointed out
that

@lisp
(set! lst (nreverse lst))
@end lisp
@noindent
is the proper usage, not
@lisp
(nreverse lst)
@end lisp
The example should suffice to show why this is the case.
@end deffn

@deffn {Procedure} delete elt lst
@deffnx {Procedure} delete-if pred lst
@deffnx {Procedure} delete-if-not pred lst
Destructive versions of @code{remove} @code{remove-if}, and
@code{remove-if-not}.

Example:
@lisp
(define lst (list 'foo 'bar 'baz 'bang))
(delete 'foo lst)
   @result{} (bar baz bang)
lst
   @result{} (foo bar baz bang)

(define lst (list 1 2 3 4 5 6 7 8 9))
(delete-if odd? lst)
   @result{} (2 4 6 8)
lst
   @result{} (1 2 4 6 8)
@end lisp

Some people have been confused about how to use @code{delete},
@code{delete-if}, and @code{delete-if}, thinking that they don't return
a value.  It needs to be pointed out that

@lisp
(set! lst (delete el lst))
@end lisp
@noindent
is the proper usage, not
@lisp
(delete el lst)
@end lisp
The examples should suffice to show why this is the case.
@end deffn



@node Non-List functions,  , Destructive list operations, Common List Functions
@subsubsection Non-List functions

@defun and? arg1 @dots{}
@code{and?} checks to see if all its arguments are true.  If they are,
@code{and?} returns @code{#t}, otherwise, @code{#f}.  (In contrast to
@code{and}, this is a function, so all arguments are always evaluated
and in an unspecified order.)

Example:
@lisp
(and? 1 2 3)
   @result{} #t
(and #f 1 2)
   @result{} #f
@end lisp
@end defun

@defun or? arg1 @dots{}
@code{or?} checks to see if any of its arguments are true.  If any is
true, @code{or?} returns @code{#t}, and @code{#f} otherwise.  (To
@code{or} as @code{and?} is to @code{and}.)

Example:
@lisp
(or? 1 2 #f)
   @result{} #t
(or? #f #f #f)
   @result{} #f
@end lisp
@end defun

@defun atom? object
Returns @code{#t} if @var{object} is not a pair and @code{#f} if it is
pair.  (Called @code{atom} in Common LISP.)
@lisp
(atom? 1)
   @result{} #t
(atom? '(1 2))
   @result{} #f
(atom? #(1 2))   ; dubious!
   @result{} #t
@end lisp
@end defun


@node Tree Operations, Chapter Ordering, Common List Functions, Sorting and Searching
@subsection Tree operations

@include tree.txi


@node Chapter Ordering, Sorting, Tree Operations, Sorting and Searching
@subsection Chapter Ordering

@include chap.txi


@node Sorting, Topological Sort, Chapter Ordering, Sorting and Searching
@subsection Sorting

@code{(require 'sort)}
@ftindex sort

[by Richard A. O'Keefe, 1991]

Many Scheme systems provide some kind of sorting functions.  They do
not, however, always provide the @emph{same} sorting functions, and
those that I have had the opportunity to test provided inefficient ones
(a common blunder is to use quicksort which does not perform well).

Because @code{sort} and @code{sort!} are not in the standard, there is
very little agreement about what these functions look like.  For
example, Dybvig says that Chez Scheme provides
@lisp
(merge predicate list1 list2)
(merge! predicate list1 list2)
(sort predicate list)
(sort! predicate list)
@end lisp
@noindent
while MIT Scheme 7.1, following Common LISP, offers unstable
@lisp
(sort list predicate)
@end lisp
@noindent
TI PC Scheme offers
@lisp
(sort! list/vector predicate?)
@end lisp
@noindent
and Elk offers
@lisp
(sort list/vector predicate?)
(sort! list/vector predicate?)
@end lisp

Here is a comprehensive catalogue of the variations I have found.

@enumerate
@item
Both @code{sort} and @code{sort!} may be provided.
@item
@code{sort} may be provided without @code{sort!}.
@item
@code{sort!} may be provided without @code{sort}.
@item
Neither may be provided.
@item
The sequence argument may be either a list or a vector.
@item
The sequence argument may only be a list.
@item
The sequence argument may only be a vector.
@item
The comparison function may be expected to behave like @code{<}.
@item
The comparison function may be expected to behave like @code{<=}.
@item
The interface may be @code{(sort predicate? sequence)}.
@item
The interface may be @code{(sort sequence predicate?)}.
@item
The interface may be @code{(sort sequence &optional (predicate? <))}.
@item
The sort may be stable.
@item
The sort may be unstable.
@end enumerate

All of this variation really does not help anybody.  A nice simple merge
sort is both stable and fast (quite a lot faster than @emph{quick} sort).

I am providing this source code with no restrictions at all on its use
(but please retain D.H.D.Warren's credit for the original idea).  You
may have to rename some of these functions in order to use them in a
system which already provides incompatible or inferior sorts.  For each
of the functions, only the top-level define needs to be edited to do
that.

I could have given these functions names which would not clash with any
Scheme that I know of, but I would like to encourage implementors to
converge on a single interface, and this may serve as a hint.  The
argument order for all functions has been chosen to be as close to
Common LISP as made sense, in order to avoid NIH-itis.

The code of @code{merge} and @code{merge!} could have been quite a bit
simpler, but they have been coded to reduce the amount of work done per
iteration.  (For example, we only have one @code{null?} test per
iteration.)

I gave serious consideration to producing Common-LISP-compatible
functions.  However, Common LISP's @code{sort} is our @code{sort!}
(well, in fact Common LISP's @code{stable-sort} is our @code{sort!};
merge sort is @emph{fast} as well as stable!) so adapting CL code to
Scheme takes a bit of work anyway.  I did, however, appeal to CL to
determine the @emph{order} of the arguments.

Each of the five functions has a required @emph{last} parameter which is
a comparison function.  A comparison function @code{f} is a function of
2 arguments which acts like @code{<}.  For example,

@lisp
(not (f x x))
(and (f x y) (f y z)) @equiv{} (f x z)
@end lisp

The standard functions @code{<}, @code{>}, @code{char<?}, @code{char>?},
@code{char-ci<?}, @code{char-ci>?}, @code{string<?}, @code{string>?},
@code{string-ci<?}, and @code{string-ci>?} are suitable for use as
comparison functions.  Think of @code{(less? x y)} as saying when
@code{x} must @emph{not} precede @code{y}.

[Addendum by Aubrey Jaffer, 2006]

These procedures are stable when called with predicates which return
@code{#f} when applied to identical arguments.  These procedures have
asymptotic time and space needs no larger than @i{O(N*log(N))}, where
@i{N} is the sum of the lengths of the sequence arguments.

All five functions take an optional @var{key} argument corresponding
to a CL-style @samp{&key} argument.  A @var{less?}  predicate with a
@var{key} argument behaves like:

@lisp
(lambda (x y) (@var{less?} (@var{key} x) (@var{key} y)))
@end lisp

@c The @var{key} argument should be called at most one time for each
@c element.

The @samp{!} variants sort in place; @code{sort!} returns its
@var{sequence} argument.

@defun sorted? sequence less?
@defunx sorted? sequence less? key
Returns @code{#t} when the sequence argument is in non-decreasing
order according to @var{less?} (that is, there is no adjacent pair
@code{@dots{} x y @dots{}} for which @code{(less? y x)}).

Returns @code{#f} when the sequence contains at least one out-of-order
pair.  It is an error if the sequence is not a list or array
(including vectors and strings).
@end defun

@defun merge list1 list2 less?
@defunx merge list1 list2 less? key
Merges two sorted lists, returning a freshly allocated list as its
result.
@end defun

@defun merge! list1 list2 less?
@defunx merge! list1 list2 less? key
Merges two sorted lists, re-using the pairs of @var{list1} and
@var{list2} to build the result.  If @code{merge!} is compiled, then
no new pairs will be allocated.  The first pair of the result will be
either the first pair of @var{list1} or the first pair of @var{list2}.
@end defun

@defun sort sequence less?
@defunx sort sequence less? key
Accepts a list or array (including vectors and strings) for
@var{sequence}; and returns a completely new sequence which is sorted
according to @var{less?}.  The returned sequence is the same type as
the argument @var{sequence}.  Given valid arguments, it is always the
case that:

@lisp
(sorted? (sort @var{sequence} @var{less?}) @var{less?}) @result{} #t
@end lisp
@end defun

@defun sort! sequence less?
@defunx sort! sequence less? key
Returns @var{sequence} which has been mutated to order its elements
according to @var{less?}.  If the argument @var{sequence} is a list
and @code{sort!} is compiled, then no new pairs will be allocated.  If
the argument @var{sequence} is an array (including vectors and
strings), then the sorted elements are returned in the array
@var{sequence}.
@end defun


@node Topological Sort, Hashing, Sorting, Sorting and Searching
@subsection Topological Sort

@include tsort.txi


@node Hashing, Space-Filling Curves, Topological Sort, Sorting and Searching
@subsection Hashing

@code{(require 'hash)}
@ftindex hash

These hashing functions are for use in quickly classifying objects.
Hash tables use these functions.

@defun hashq obj k
@defunx hashv obj k
@defunx hash obj k
Returns an exact non-negative integer less than @var{k}.  For each
non-negative integer less than @var{k} there are arguments @var{obj} for
which the hashing functions applied to @var{obj} and @var{k} returns
that integer.

For @code{hashq}, @code{(eq? obj1 obj2)} implies @code{(= (hashq obj1 k)
(hashq obj2))}.

For @code{hashv}, @code{(eqv? obj1 obj2)} implies @code{(= (hashv obj1 k)
(hashv obj2))}.

For @code{hash}, @code{(equal? obj1 obj2)} implies @code{(= (hash obj1 k)
(hash obj2))}.

@code{hash}, @code{hashv}, and @code{hashq} return in time bounded by a
constant.  Notice that items having the same @code{hash} implies the
items have the same @code{hashv} implies the items have the same
@code{hashq}.
@end defun


@node Space-Filling Curves, Soundex, Hashing, Sorting and Searching
@subsection Space-Filling Curves

@menu
* Hilbert Space-Filling Curve::  Non-negative coordinates
* Peano Space-Filling Curve::   Integer coordinates
* Sierpinski Curve::            
@end menu

@node Hilbert Space-Filling Curve, Peano Space-Filling Curve, Space-Filling Curves, Space-Filling Curves
@subsubsection Hilbert Space-Filling Curve

@include phil-spc.txi


@node Peano Space-Filling Curve, Sierpinski Curve, Hilbert Space-Filling Curve, Space-Filling Curves
@subsubsection Peano Space-Filling Curve

@include peanosfc.txi


@node Sierpinski Curve,  , Peano Space-Filling Curve, Space-Filling Curves
@subsubsection Sierpinski Curve

@code{(require 'sierpinski)}
@ftindex sierpinski

@defun make-sierpinski-indexer max-coordinate
Returns a procedure (eg hash-function) of 2 numeric arguments which
preserves @emph{nearness} in its mapping from NxN to N.

@var{max-coordinate} is the maximum coordinate (a positive integer) of a
population of points.  The returned procedures is a function that takes
the x and y coordinates of a point, (non-negative integers) and returns
an integer corresponding to the relative position of that point along a
Sierpinski curve.  (You can think of this as computing a (pseudo-)
inverse of the Sierpinski spacefilling curve.)

Example use: Make an indexer (hash-function) for integer points lying in
square of integer grid points [0,99]x[0,99]:
@example
(define space-key (make-sierpinski-indexer 100))
@end example
Now let's compute the index of some points:
@example
(space-key 24 78)               @result{} 9206
(space-key 23 80)               @result{} 9172
@end example

Note that locations (24, 78) and (23, 80) are near in index and
therefore, because the Sierpinski spacefilling curve is continuous, we
know they must also be near in the plane.  Nearness in the plane does
not, however, necessarily correspond to nearness in index, although it
@emph{tends} to be so.

Example applications:
@itemize @bullet

@item
Sort points by Sierpinski index to get heuristic solution to
@emph{travelling salesman problem}.  For details of performance,
see L. Platzman and J. Bartholdi, "Spacefilling curves and the
Euclidean travelling salesman problem", JACM 36(4):719--737
(October 1989) and references therein.

@item
Use Sierpinski index as key by which to store 2-dimensional data
in a 1-dimensional data structure (such as a table).  Then
locations that are near each other in 2-d space will tend to
be near each other in 1-d data structure; and locations that
are near in 1-d data structure will be near in 2-d space.  This
can significantly speed retrieval from secondary storage because
contiguous regions in the plane will tend to correspond to
contiguous regions in secondary storage.  (This is a standard
technique for managing CAD/CAM or geographic data.)

@end itemize
@end defun


@node Soundex, String Search, Space-Filling Curves, Sorting and Searching
@subsection Soundex

@code{(require 'soundex)}
@ftindex soundex

@defun soundex name
Computes the @emph{soundex} hash of @var{name}.  Returns a string of an
initial letter and up to three digits between 0 and 6.  Soundex
supposedly has the property that names that sound similar in normal
English pronunciation tend to map to the same key.

Soundex was a classic algorithm used for manual filing of personal
records before the advent of computers.  It performs adequately for
English names but has trouble with other languages.

See Knuth, Vol. 3 @cite{Sorting and searching}, pp 391--2

To manage unusual inputs, @code{soundex} omits all non-alphabetic
characters.  Consequently, in this implementation:

@example
(soundex <string of blanks>)    @result{} ""
(soundex "")                    @result{} ""
@end example

Examples from Knuth:

@example
(map soundex '("Euler" "Gauss" "Hilbert" "Knuth"
                       "Lloyd" "Lukasiewicz"))
        @result{} ("E460" "G200" "H416" "K530" "L300" "L222")

(map soundex '("Ellery" "Ghosh" "Heilbronn" "Kant"
                        "Ladd" "Lissajous"))
        @result{} ("E460" "G200" "H416" "K530" "L300" "L222")
@end example

Some cases in which the algorithm fails (Knuth):

@example
(map soundex '("Rogers" "Rodgers"))     @result{} ("R262" "R326")

(map soundex '("Sinclair" "St. Clair")) @result{} ("S524" "S324")

(map soundex '("Tchebysheff" "Chebyshev")) @result{} ("T212" "C121")
@end example
@end defun


@node String Search, Sequence Comparison, Soundex, Sorting and Searching
@subsection String Search

@code{(require 'string-search)}
@ftindex string-search

@deffn {Procedure} string-index string char
@deffnx {Procedure} string-index-ci string char
Returns the index of the first occurence of @var{char} within
@var{string}, or @code{#f} if the @var{string} does not contain a
character @var{char}.
@end deffn

@deffn {Procedure} string-reverse-index string char
@deffnx {Procedure} string-reverse-index-ci string char
Returns the index of the last occurence of @var{char} within
@var{string}, or @code{#f} if the @var{string} does not contain a
character @var{char}.
@end deffn

@deffn {Procedure} substring? pattern string
@deffnx {Procedure} substring-ci? pattern string
Searches @var{string} to see if some substring of @var{string} is equal
to @var{pattern}.  @code{substring?} returns the index of the first
character of the first substring of @var{string} that is equal to
@var{pattern}; or @code{#f} if @var{string} does not contain
@var{pattern}.

@example
(substring? "rat" "pirate") @result{}  2
(substring? "rat" "outrage") @result{}  #f
(substring? "" any-string) @result{}  0
@end example
@end deffn

@deffn {Procedure} find-string-from-port? str in-port max-no-chars
Looks for a string @var{str} within the first @var{max-no-chars} chars
of the input port @var{in-port}.

@deffnx {Procedure} find-string-from-port? str in-port
When called with two arguments, the search span is limited by the end of
the input stream.

@deffnx {Procedure} find-string-from-port? str in-port char
Searches up to the first occurrence of character @var{char} in
@var{str}.

@deffnx {Procedure} find-string-from-port? str in-port proc
Searches up to the first occurrence of the procedure @var{proc}
returning non-false when called with a character (from @var{in-port})
argument.

When the @var{str} is found, @code{find-string-from-port?} returns the
number of characters it has read from the port, and the port is set to
read the first char after that (that is, after the @var{str}) The
function returns @code{#f} when the @var{str} isn't found.

@code{find-string-from-port?} reads the port @emph{strictly}
sequentially, and does not perform any buffering.  So
@code{find-string-from-port?} can be used even if the @var{in-port} is
open to a pipe or other communication channel.
@end deffn

@defun string-subst txt old1 new1 @dots{}
Returns a copy of string @var{txt} with all occurrences of string
@var{old1} in @var{txt} replaced with @var{new1}; then @var{old2}
replaced with @var{new2} @dots{}.  Matches are found from the left.
Matches do not overlap.
@end defun

@defun count-newlines str
Returns the number of @samp{#\newline} characters in string @var{str}.
@end defun


@node Sequence Comparison,  , String Search, Sorting and Searching
@subsection Sequence Comparison

@code{(require 'diff)}
@ftindex diff
@cindex Sequence Comparison

@include differ.txi


@node Procedures, Standards Support, Sorting and Searching, Other Packages
@section Procedures

Anything that doesn't fall neatly into any of the other categories winds
up here.

@menu
* Type Coercion::               'coerce
* String-Case::                 'string-case
* String Ports::                'string-port
* Line I/O::                    'line-i/o
* Multi-Processing::            'process
* Metric Units::                Portable manifest types for numeric values.
@end menu


@node Type Coercion, String-Case, Procedures, Procedures
@subsection Type Coercion
@code{(require 'coerce)}
@ftindex coerce

@include coerce.txi


@node String-Case, String Ports, Type Coercion, Procedures
@subsection String-Case

@code{(require 'string-case)}
@ftindex string-case

@deffn {Procedure} string-upcase str
@deffnx {Procedure} string-downcase str
@deffnx {Procedure} string-capitalize str
The obvious string conversion routines.  These are non-destructive.
@end deffn

@defun string-upcase! str
@defunx string-downcase! str
@defunx string-capitalize! str
The destructive versions of the functions above.
@end defun

@defun string-ci->symbol str
Converts string @var{str} to a symbol having the same case as if the
symbol had been @code{read}.
@end defun

@defun symbol-append obj1 @dots{}
Converts @var{obj1} @dots{} to strings, appends them, and converts to a
symbol which is returned.  Strings and numbers are converted to read's
symbol case; the case of symbol characters is not changed.  #f is
converted to the empty string (symbol).
@end defun

@defun StudlyCapsExpand str delimiter
@defunx StudlyCapsExpand str
@var{delimiter} must be a string or character.  If absent,
@var{delimiter} defaults to @samp{-}.  @code{StudlyCapsExpand} returns a
copy of @var{str} where @var{delimiter} is inserted between each
lower-case character immediately followed by an upper-case character;
and between two upper-case characters immediately followed by a
lower-case character.

@example
(StudlyCapsExpand "aX" " ")   @result{} "a X"
(StudlyCapsExpand "aX" "..")  @result{} "a..X"
(StudlyCapsExpand "AX")       @result{} "AX"
(StudlyCapsExpand "Ax")       @result{} "Ax"
(StudlyCapsExpand "AXLE")     @result{} "AXLE"
(StudlyCapsExpand "aAXACz")   @result{} "a-AXA-Cz"
(StudlyCapsExpand "AaXACz")   @result{} "Aa-XA-Cz"
(StudlyCapsExpand "AAaXACz")  @result{} "A-Aa-XA-Cz"
(StudlyCapsExpand "AAaXAC")   @result{} "A-Aa-XAC"
@end example

@end defun



@node String Ports, Line I/O, String-Case, Procedures
@subsection String Ports

@code{(require 'string-port)}
@ftindex string-port

@deffn {Procedure} call-with-output-string proc
@var{proc} must be a procedure of one argument.  This procedure calls
@var{proc} with one argument: a (newly created) output port.  When the
function returns, the string composed of the characters written into the
port is returned.
@end deffn

@deffn {Procedure} call-with-input-string string proc
@var{proc} must be a procedure of one argument.  This procedure calls
@var{proc} with one argument: an (newly created) input port from which
@var{string}'s contents may be read.  When @var{proc} returns, the port
is closed and the value yielded by the procedure @var{proc} is
returned.
@end deffn


@node Line I/O, Multi-Processing, String Ports, Procedures
@subsection Line I/O

@code{(require 'line-i/o)}
@ftindex line-i

@include lineio.txi


@node Multi-Processing, Metric Units, Line I/O, Procedures
@subsection Multi-Processing

@code{(require 'process)}
@ftindex process

This module implements asynchronous (non-polled) time-sliced
multi-processing in the SCM Scheme implementation using procedures
@code{alarm} and @code{alarm-interrupt}.
@cindex alarm
@cindex alarm-interrupt
Until this is ported to another implementation, consider it an example
of writing schedulers in Scheme.

@deffn {Procedure} add-process! proc
Adds proc, which must be a procedure (or continuation) capable of
accepting accepting one argument, to the @code{process:queue}.  The
value returned is unspecified.  The argument to @var{proc} should be
ignored.  If @var{proc} returns, the process is killed.
@end deffn

@deffn {Procedure} process:schedule!
Saves the current process on @code{process:queue} and runs the next
process from @code{process:queue}.  The value returned is
unspecified.
@end deffn

@deffn {Procedure} kill-process!
Kills the current process and runs the next process from
@code{process:queue}.  If there are no more processes on
@code{process:queue}, @code{(slib:exit)} is called (@pxref{System}).
@end deffn


@node Metric Units,  , Multi-Processing, Procedures
@subsection Metric Units

@code{(require 'metric-units)}
@ftindex metric-units

@url{http://swiss.csail.mit.edu/~jaffer/MIXF}

@dfn{Metric Interchange Format} is a character string encoding for
numerical values and units which:

@itemize @bullet
@item
is unambiguous in all locales;

@item
uses only [TOG] "Portable Character Set" characters matching "Basic
Latin" characters in Plane 0 of the Universal Character Set [UCS];

@item
is transparent to [UTF-7] and [UTF-8] UCS transformation formats;

@item
is human readable and writable;

@item
is machine readable and writable;

@item
incorporates SI prefixes and units;

@item
incorporates [ISO 6093] numbers; and

@item
incorporates [IEC 60027-2] binary prefixes.
@end itemize

In the expression for the value of a quantity, the unit symbol is placed
after the numerical value.  A dot (PERIOD, @samp{.}) is placed between
the numerical value and the unit symbol.

Within a compound unit, each of the base and derived symbols can
optionally have an attached SI prefix.

Unit symbols formed from other unit symbols by multiplication are
indicated by means of a dot (PERIOD, @samp{.}) placed between them.

Unit symbols formed from other unit symbols by division are indicated by
means of a SOLIDUS (@samp{/}) or negative exponents.  The SOLIDUS must
not be repeated in the same compound unit unless contained within a
parenthesized subexpression.

The grouping formed by a prefix symbol attached to a unit symbol
constitutes a new inseparable symbol (forming a multiple or submultiple
of the unit concerned) which can be raised to a positive or negative
power and which can be combined with other unit symbols to form compound
unit symbols.

The grouping formed by surrounding compound unit symbols with
parentheses (@samp{(} and @samp{)}) constitutes a new inseparable symbol
which can be raised to a positive or negative power and which can be
combined with other unit symbols to form compound unit symbols.

Compound prefix symbols, that is, prefix symbols formed by the
juxtaposition of two or more prefix symbols, are not permitted.

Prefix symbols are not used with the time-related unit symbols min
(minute), h (hour), d (day).  No prefix symbol may be used with dB
(decibel).  Only submultiple prefix symbols may be used with the unit
symbols L (liter), Np (neper), o (degree), oC (degree Celsius), rad
(radian), and sr (steradian).  Submultiple prefix symbols may not be
used with the unit symbols t (metric ton), r (revolution), or Bd (baud).

A unit exponent follows the unit, separated by a CIRCUMFLEX (@samp{^}).
Exponents may be positive or negative.  Fractional exponents must be
parenthesized.

@subsubsection SI Prefixes
@example
       Factor     Name    Symbol  |  Factor     Name    Symbol
       ======     ====    ======  |  ======     ====    ======
        1e24      yotta      Y    |   1e-1      deci       d
        1e21      zetta      Z    |   1e-2      centi      c
        1e18      exa        E    |   1e-3      milli      m
        1e15      peta       P    |   1e-6      micro      u
        1e12      tera       T    |   1e-9      nano       n
        1e9       giga       G    |   1e-12     pico       p
        1e6       mega       M    |   1e-15     femto      f
        1e3       kilo       k    |   1e-18     atto       a
        1e2       hecto      h    |   1e-21     zepto      z
        1e1       deka       da   |   1e-24     yocto      y
@end example

@subsubsection Binary Prefixes

These binary prefixes are valid only with the units B (byte) and bit.
However, decimal prefixes can also be used with bit; and decimal
multiple (not submultiple) prefixes can also be used with B (byte).

@example
                Factor       (power-of-2)  Name  Symbol
                ======       ============  ====  ======
       1.152921504606846976e18  (2^60)     exbi    Ei
          1.125899906842624e15  (2^50)     pebi    Pi
             1.099511627776e12  (2^40)     tebi    Ti
                1.073741824e9   (2^30)     gibi    Gi
                   1.048576e6   (2^20)     mebi    Mi
                      1.024e3   (2^10)     kibi    Ki
@end example

@subsubsection Unit Symbols

@example
    Type of Quantity      Name          Symbol   Equivalent
    ================      ====          ======   ==========
time                      second           s
time                      minute           min = 60.s
time                      hour             h   = 60.min
time                      day              d   = 24.h
frequency                 hertz            Hz    s^-1
signaling rate            baud             Bd    s^-1
length                    meter            m
volume                    liter            L     dm^3
plane angle               radian           rad
solid angle               steradian        sr    rad^2
plane angle               revolution     * r   = 6.283185307179586.rad
plane angle               degree         * o   = 2.777777777777778e-3.r
information capacity      bit              bit
information capacity      byte, octet      B   = 8.bit
mass                      gram             g
mass                      ton              t     Mg
mass              unified atomic mass unit u   = 1.66053873e-27.kg
amount of substance       mole             mol
catalytic activity        katal            kat   mol/s
thermodynamic temperature kelvin           K
centigrade temperature    degree Celsius   oC
luminous intensity        candela          cd
luminous flux             lumen            lm    cd.sr
illuminance               lux              lx    lm/m^2
force                     newton           N     m.kg.s^-2
pressure, stress          pascal           Pa    N/m^2
energy, work, heat        joule            J     N.m
energy                    electronvolt     eV  = 1.602176462e-19.J
power, radiant flux       watt             W     J/s
logarithm of power ratio  neper            Np
logarithm of power ratio  decibel        * dB  = 0.1151293.Np
electric current          ampere           A
electric charge           coulomb          C     s.A
electric potential, EMF   volt             V     W/A
capacitance               farad            F     C/V
electric resistance       ohm              Ohm   V/A
electric conductance      siemens          S     A/V
magnetic flux             weber            Wb    V.s
magnetic flux density     tesla            T     Wb/m^2
inductance                henry            H     Wb/A
radionuclide activity     becquerel        Bq    s^-1
absorbed dose energy      gray             Gy    m^2.s^-2
dose equivalent           sievert          Sv    m^2.s^-2
@end example

* The formulas are:

@itemize @bullet
@item
r/rad = 8 * atan(1)
@item
o/r = 1 / 360
@item
db/Np = ln(10) / 20
@end itemize

@defun si:conversion-factor to-unit from-unit
If the strings @var{from-unit} and @var{to-unit} express valid unit
expressions for quantities of the same unit-dimensions, then the value
returned by @code{si:conversion-factor} will be such that multiplying a
numerical value expressed in @var{from-unit}s by the returned conversion
factor yields the numerical value expressed in @var{to-unit}s.

Otherwise, @code{si:conversion-factor} returns:

@table @asis
@item -3
if neither @var{from-unit} nor @var{to-unit} is a syntactically valid
unit.
@item -2
if @var{from-unit} is not a syntactically valid unit.
@item -1
if @var{to-unit} is not a syntactically valid unit.
@item 0
if linear conversion (by a factor) is not possible.
@end table

@end defun

@example
(si:conversion-factor "km/s" "m/s" ) @result{} 0.001     
(si:conversion-factor "N"    "m/s" ) @result{} 0         
(si:conversion-factor "moC"  "oC"  ) @result{} 1000      
(si:conversion-factor "mK"   "oC"  ) @result{} 0         
(si:conversion-factor "rad"  "o"   ) @result{} 0.0174533 
(si:conversion-factor "K"    "o"   ) @result{} 0         
(si:conversion-factor "K"    "K"   ) @result{} 1         
(si:conversion-factor "oK"   "oK"  ) @result{} -3        
(si:conversion-factor ""     "s/s" ) @result{} 1         
(si:conversion-factor "km/h" "mph" ) @result{} -2        
@end example


@node Standards Support, Session Support, Procedures, Other Packages
@section Standards Support



@menu
* RnRS::                        Revised Reports on Scheme
* With-File::                   'with-file
* Transcripts::                 'transcript
* Rev2 Procedures::             'rev2-procedures
* Rev4 Optional Procedures::    'rev4-optional-procedures
* Multi-argument / and -::      'multiarg/and-
* Multi-argument Apply::        'multiarg-apply
* Rationalize::                 'rationalize
* Promises::                    'delay
* Dynamic-Wind::                'dynamic-wind
* Eval::                        'eval
* Values::                      'values
* SRFI::                        'http://srfi.schemers.org/srfi-0/srfi-0.html
@end menu

@node RnRS, With-File, Standards Support, Standards Support
@subsection RnRS

@noindent
The @code{r2rs}, @code{r3rs}, @code{r4rs}, and @code{r5rs} features
attempt to provide procedures and macros to bring a Scheme
implementation to the desired version of Scheme.

@deftp {Feature} r2rs
@ftindex r2rs
Requires features implementing procedures and optional procedures
specified by @cite{Revised^2 Report on the Algorithmic Language Scheme};
namely @code{rev3-procedures} and @code{rev2-procedures}.
@end deftp

@deftp {Feature} r3rs
@ftindex r3rs
Requires features implementing procedures and optional procedures
specified by @cite{Revised^3 Report on the Algorithmic Language Scheme};
namely @code{rev3-procedures}.

@emph{Note:} SLIB already mandates the @code{r3rs} procedures which can
be portably implemented in @code{r4rs} implementations.
@end deftp

@deftp {Feature} r4rs
@ftindex r4rs
Requires features implementing procedures and optional procedures
specified by @cite{Revised^4 Report on the Algorithmic Language Scheme};
namely @code{rev4-optional-procedures}.
@end deftp

@deftp {Feature} r5rs
@ftindex r5rs
Requires features implementing procedures and optional procedures
specified by @cite{Revised^5 Report on the Algorithmic Language Scheme};
namely @code{values}, @code{macro}, and @code{eval}.
@end deftp


@node With-File, Transcripts, RnRS, Standards Support
@subsection With-File

@code{(require 'with-file)}
@ftindex with-file

@defun with-input-from-file file thunk
@defunx with-output-to-file file thunk
Description found in R4RS.
@end defun

@node Transcripts, Rev2 Procedures, With-File, Standards Support
@subsection Transcripts

@code{(require 'transcript)}
@ftindex transcript

@defun transcript-on filename
@defunx transcript-off filename
Redefines @code{read-char}, @code{read}, @code{write-char},
@code{write}, @code{display}, and @code{newline}.
@end defun





@node Rev2 Procedures, Rev4 Optional Procedures, Transcripts, Standards Support
@subsection Rev2 Procedures

@code{(require 'rev2-procedures)}
@ftindex rev2-procedures

The procedures below were specified in the @cite{Revised^2 Report on
Scheme}.  @strong{N.B.}: The symbols @code{1+} and @code{-1+} are not
@cite{R4RS} syntax.  Scheme->C, for instance, chokes on this
module.

@deffn {Procedure} substring-move-left! string1 start1 end1 string2 start2
@deffnx {Procedure} substring-move-right! string1 start1 end1 string2 start2
@var{string1} and @var{string2} must be a strings, and @var{start1},
@var{start2} and @var{end1} must be exact integers satisfying

@display
0 <= @var{start1} <= @var{end1} <= (string-length @var{string1})
0 <= @var{start2} <= @var{end1} - @var{start1} + @var{start2} <= (string-length @var{string2})
@end display

@code{substring-move-left!} and @code{substring-move-right!} store
characters of @var{string1} beginning with index @var{start1}
(inclusive) and ending with index @var{end1} (exclusive) into
@var{string2} beginning with index @var{start2} (inclusive).

@code{substring-move-left!} stores characters in time order of
increasing indices.  @code{substring-move-right!} stores characters in
time order of increasing indeces.
@end deffn

@deffn {Procedure} substring-fill! string start end char
Fills the elements @var{start}--@var{end} of @var{string} with the
character @var{char}.
@end deffn

@defun string-null? str
@equiv{} @code{(= 0 (string-length @var{str}))}
@end defun

@deffn {Procedure} append! pair1 @dots{}
Destructively appends its arguments.  Equivalent to @code{nconc}.
@end deffn

@defun 1+ n
Adds 1 to @var{n}.
@end defun

@defun -1+ n
Subtracts 1 from @var{n}.
@end defun

@defun <?
@defunx <=?
@defunx =?
@defunx >?
@defunx >=?
These are equivalent to the procedures of the same name but without the
trailing @samp{?}.
@end defun



@node Rev4 Optional Procedures, Multi-argument / and -, Rev2 Procedures, Standards Support
@subsection Rev4 Optional Procedures

@code{(require 'rev4-optional-procedures)}
@ftindex rev4-optional-procedures

For the specification of these optional procedures,
@xref{Standard procedures, , ,r4rs, Revised(4) Scheme}.

@defun list-tail l p
@end defun

@defun string-copy
@end defun

@deffn {Procedure} string-fill! s obj
@end deffn

@deffn {Procedure} vector-fill! s obj
@end deffn





@node Multi-argument / and -, Multi-argument Apply, Rev4 Optional Procedures, Standards Support
@subsection Multi-argument / and -

@code{(require 'multiarg/and-)}
@ftindex multiarg

For the specification of these optional forms, @xref{Numerical
operations, , ,r4rs, Revised(4) Scheme}.

@defun / dividend divisor1 @dots{}
@end defun

@defun - minuend subtrahend1 @dots{}
@end defun





@node Multi-argument Apply, Rationalize, Multi-argument / and -, Standards Support
@subsection Multi-argument Apply

@code{(require 'multiarg-apply)}
@ftindex multiarg-apply

@noindent
For the specification of this optional form,
@xref{Control features, , ,r4rs, Revised(4) Scheme}.

@defun apply proc arg1 @dots{}
@end defun



@node Rationalize, Promises, Multi-argument Apply, Standards Support
@subsection Rationalize

@include ratize.txi



@node Promises, Dynamic-Wind, Rationalize, Standards Support
@subsection Promises

@code{(require 'promise)}
@ftindex promise

@defun make-promise proc
@end defun

@defun force promise
@end defun

@code{(require 'delay)} provides @code{force} and @code{delay}:

@defmac delay obj
Change occurrences of @code{(delay @var{expression})} to

@example
(make-promise (lambda () @var{expression}))
@end example

@end defmac

(@pxref{Control features, , ,r4rs, Revised(4) Scheme}).


@node Dynamic-Wind, Eval, Promises, Standards Support
@subsection Dynamic-Wind

@code{(require 'dynamic-wind)}
@ftindex dynamic-wind

This facility is a generalization of Common LISP @code{unwind-protect},
designed to take into account the fact that continuations produced by
@code{call-with-current-continuation} may be reentered.

@deffn {Procedure} dynamic-wind thunk1 thunk2 thunk3
The arguments @var{thunk1}, @var{thunk2}, and @var{thunk3} must all be
procedures of no arguments (thunks).

@code{dynamic-wind} calls @var{thunk1}, @var{thunk2}, and then
@var{thunk3}.  The value returned by @var{thunk2} is returned as the
result of @code{dynamic-wind}.  @var{thunk3} is also called just before
control leaves the dynamic context of @var{thunk2} by calling a
continuation created outside that context.  Furthermore, @var{thunk1} is
called before reentering the dynamic context of @var{thunk2} by calling
a continuation created inside that context.  (Control is inside the
context of @var{thunk2} if @var{thunk2} is on the current return stack).

@strong{Warning:} There is no provision for dealing with errors or
interrupts.  If an error or interrupt occurs while using
@code{dynamic-wind}, the dynamic environment will be that in effect at
the time of the error or interrupt.
@end deffn


@node Eval, Values, Dynamic-Wind, Standards Support
@subsection Eval

@code{(require 'eval)}
@ftindex eval

@defun eval expression environment-specifier

Evaluates @var{expression} in the specified environment and returns its
value.  @var{Expression} must be a valid Scheme expression represented
as data, and @var{environment-specifier} must be a value returned by one
of the three procedures described below.  Implementations may extend
@code{eval} to allow non-expression programs (definitions) as the first
argument and to allow other values as environments, with the restriction
that @code{eval} is not allowed to create new bindings in the
environments associated with @code{null-environment} or
@code{scheme-report-environment}.

@lisp
(eval '(* 7 3) (scheme-report-environment 5))
                                                   @result{}  21

(let ((f (eval '(lambda (f x) (f x x))
               (null-environment))))
  (f + 10))
                                                   @result{}  20
@end lisp
@end defun

@defun scheme-report-environment version
@defunx null-environment version
@defunx null-environment

@var{Version} must be an exact non-negative integer @var{n}
corresponding to a version of one of the Revised^@var{n} Reports on
Scheme.  @code{Scheme-report-environment} returns a specifier for an
environment that contains the set of bindings specified in the
corresponding report that the implementation supports.
@code{Null-environment} returns a specifier for an environment that
contains only the (syntactic) bindings for all the syntactic keywords
defined in the given version of the report.

Not all versions may be available in all implementations at all times.
However, an implementation that conforms to version @var{n} of the
Revised^@var{n} Reports on Scheme must accept version @var{n}.  An error
is signalled if the specified version is not available.

The effect of assigning (through the use of @code{eval}) a variable
bound in a @code{scheme-report-environment} (for example @code{car}) is
unspecified. Thus the environments specified by
@code{scheme-report-environment} may be immutable.

@end defun

@defun interaction-environment

This optional procedure returns a specifier for the environment that
contains implementation-defined bindings, typically a superset of those
listed in the report.  The intent is that this procedure will return the
environment in which the implementation would evaluate expressions
dynamically typed by the user.
@end defun

@noindent
Here are some more @code{eval} examples:

@example
(require 'eval)
@result{} #<unspecified>
(define car 'volvo)
@result{} #<unspecified>
car
@result{} volvo
(eval 'car (interaction-environment))
@result{} volvo
(eval 'car (scheme-report-environment 5))
@result{} #<primitive-procedure car>
(eval '(eval 'car (interaction-environment))
      (scheme-report-environment 5))
@result{} volvo
(eval '(eval '(set! car 'buick) (interaction-environment))
      (scheme-report-environment 5))
@result{} #<unspecified>
car
@result{} buick
(eval 'car (scheme-report-environment 5))
@result{} #<primitive-procedure car>
(eval '(eval 'car (interaction-environment))
      (scheme-report-environment 5))
@result{} buick
@end example


@node Values, SRFI, Eval, Standards Support
@subsection Values

@code{(require 'values)}
@ftindex values

@defun values obj @dots{}
@code{values} takes any number of arguments, and passes (returns) them
to its continuation.
@end defun


@defun call-with-values thunk proc
@var{thunk} must be a procedure of no arguments, and @var{proc} must be
a procedure.  @code{call-with-values} calls @var{thunk} with a
continuation that, when passed some values, calls @var{proc} with those
values as arguments.

Except for continuations created by the @code{call-with-values}
procedure, all continuations take exactly one value, as now; the effect
of passing no value or more than one value to continuations that were
not created by the @code{call-with-values} procedure is
unspecified.
@end defun

@node SRFI,  , Values, Standards Support
@subsection SRFI

@include srfi.txi

@menu
* SRFI-1::                      list-processing
@end menu

@itemize @bullet
@ftindex srfi-2
@item SRFI-2 @ref{Guarded LET* special form}
@ftindex srfi-8
@item SRFI-8 @ref{Binding to multiple values}
@ftindex srfi-9
@item SRFI-9 @ref{Define-Record-Type}
@ftindex srfi-23
@item SRFI-23 @code{(define error slib:error)}
@ftindex srfi-47
@item SRFI-47 @ref{Arrays}
@ftindex srfi-63
@item SRFI-63 @ref{Arrays}
@ftindex srfi-59
@item SRFI-59 @ref{Vicinity}
@ftindex srfi-60
@item SRFI-60 @ref{Bit-Twiddling}
@ftindex srfi-61
@item SRFI-61 @ref{Guarded COND Clause}
@end itemize

@node SRFI-1,  , SRFI, SRFI
@subsubsection SRFI-1

@include srfi-1.txi



@node Session Support, System Interface, Standards Support, Other Packages
@section Session Support

@noindent
If @code{(provided? 'abort)}:

@defun abort
Resumes the top level Read-Eval-Print loop.  If provided, @code{abort}
is used by the @code{break} and @code{debug} packages.
@end defun

@menu
* Repl::                        Macros at top-level
* Quick Print::                 Loop-safe Output
* Debug::                       To err is human ...
* Breakpoints::                 Pause execution
* Trace::                       'trace
@end menu


@node Repl, Quick Print, Session Support, Session Support
@subsection Repl

@code{(require 'repl)}
@ftindex repl

Here is a read-eval-print-loop which, given an eval, evaluates forms.

@deffn {Procedure} repl:top-level repl:eval
@code{read}s, @code{repl:eval}s and @code{write}s expressions from
@code{(current-input-port)} to @code{(current-output-port)} until an
end-of-file is encountered.  @code{load}, @code{slib:eval},
@code{slib:error}, and @code{repl:quit} dynamically bound during
@code{repl:top-level}.
@end deffn

@deffn {Procedure} repl:quit
Exits from the invocation of @code{repl:top-level}.
@end deffn

The @code{repl:} procedures establish, as much as is possible to do
portably, a top level environment supporting macros.
@code{repl:top-level} uses @code{dynamic-wind} to catch error conditions
and interrupts.  If your implementation supports this you are all set.

Otherwise, if there is some way your implementation can catch error
conditions and interrupts, then have them call @code{slib:error}.  It
will display its arguments and reenter @code{repl:top-level}.
@code{slib:error} dynamically bound by @code{repl:top-level}.

To have your top level loop always use macros, add any interrupt
catching lines and the following lines to your Scheme init file:
@lisp
(require 'macro)
@ftindex macro
(require 'repl)
@ftindex repl
(repl:top-level macro:eval)
@end lisp

@node Quick Print, Debug, Repl, Session Support
@subsection Quick Print

@code{(require 'qp)}
@ftindex qp

@noindent
When displaying error messages and warnings, it is paramount that the
output generated for circular lists and large data structures be
limited.  This section supplies a procedure to do this.  It could be
much improved.

@quotation
Notice that the neccessity for truncating output eliminates
Common-Lisp's @ref{Format} from consideration; even when variables
@code{*print-level*} and @code{*print-level*} are set, huge strings and
bit-vectors are @emph{not} limited.
@end quotation

@deffn {Procedure} qp arg1 @dots{}
@deffnx {Procedure} qpn arg1 @dots{}
@deffnx {Procedure} qpr arg1 @dots{}
@code{qp} writes its arguments, separated by spaces, to
@code{(current-output-port)}.  @code{qp} compresses printing by
substituting @samp{...} for substructure it does not have sufficient
room to print.  @code{qpn} is like @code{qp} but outputs a newline
before returning.  @code{qpr} is like @code{qpn} except that it returns
its last argument.
@end deffn

@defvar *qp-width*
@var{*qp-width*} is the largest number of characters that @code{qp}
should use.  If @var{*qp-width*} is #f, then all items will be
@code{write}n.  If @var{*qp-width*} is 0, then all items except
procedures will be @code{write}n; procedures will be indicated by
@samp{#[proc]}.
@end defvar

@node Debug, Breakpoints, Quick Print, Session Support
@subsection Debug

@code{(require 'debug)}
@ftindex debug

@noindent
Requiring @code{debug} automatically requires @code{trace} and
@code{break}.

@noindent
An application with its own datatypes may want to substitute its own
printer for @code{qp}.  This example shows how to do this:

@example
(define qpn (lambda args) @dots{})
(provide 'qp)
(require 'debug)
@ftindex debug
@end example

@deffn {Procedure} trace-all file @dots{}
Traces (@pxref{Trace}) all procedures @code{define}d at top-level in
@file{file} @dots{}.

@deffnx {Procedure} track-all file @dots{}
Tracks (@pxref{Trace}) all procedures @code{define}d at top-level in
@file{file} @dots{}.

@deffnx {Procedure} stack-all file @dots{}
Stacks (@pxref{Trace}) all procedures @code{define}d at top-level in
@file{file} @dots{}.
@end deffn

@deffn {Procedure} break-all file @dots{}
Breakpoints (@pxref{Breakpoints}) all procedures @code{define}d at
top-level in @file{file} @dots{}.
@end deffn

@node Breakpoints, Trace, Debug, Session Support
@subsection Breakpoints

@code{(require 'break)}
@ftindex break

@defun init-debug
If your Scheme implementation does not support @code{break} or
@code{abort}, a message will appear when you @code{(require 'break)} or
@ftindex break
@code{(require 'debug)} telling you to type @code{(init-debug)}.  This
@ftindex debug
is in order to establish a top-level continuation.  Typing
@code{(init-debug)} at top level sets up a continuation for
@code{break}.
@end defun

@defun breakpoint arg1 @dots{}
Returns from the top level continuation and pushes the continuation from
which it was called on a continuation stack.
@end defun

@defun continue
Pops the topmost continuation off of the continuation stack and returns
an unspecified value to it.

@defunx continue arg1 @dots{}
Pops the topmost continuation off of the continuation stack and returns
@var{arg1} @dots{} to it.
@end defun

@defmac break proc1 @dots{}
Redefines the top-level named procedures given as arguments so that
@code{breakpoint} is called before calling @var{proc1} @dots{}.
@defmacx break
With no arguments, makes sure that all the currently broken identifiers
are broken (even if those identifiers have been redefined) and returns a
list of the broken identifiers.
@end defmac

@defmac unbreak proc1 @dots{}
Turns breakpoints off for its arguments.
@defmacx unbreak
With no arguments, unbreaks all currently broken identifiers and returns
a list of these formerly broken identifiers.
@end defmac

These are @emph{procedures} for breaking.  If defmacros are not natively
supported by your implementation, these might be more convenient to use.

@defun breakf proc
@defunx breakf proc name
To break, type
@lisp
(set! @var{symbol} (breakf @var{symbol}))
@end lisp
@noindent
or
@lisp
(set! @var{symbol} (breakf @var{symbol} '@var{symbol}))
@end lisp
@noindent
or
@lisp
(define @var{symbol} (breakf @var{function}))
@end lisp
@noindent
or
@lisp
(define @var{symbol} (breakf @var{function} '@var{symbol}))
@end lisp
@end defun

@defun unbreakf proc
To unbreak, type
@lisp
(set! @var{symbol} (unbreakf @var{symbol}))
@end lisp
@end defun

@node Trace,  , Breakpoints, Session Support
@subsection Tracing

@code{(require 'trace)}
@ftindex trace

@noindent
This feature provides three ways to monitor procedure invocations:

@table @asis
@item stack
Pushes the procedure-name when the procedure is called; pops when it
returns.
@item track
Pushes the procedure-name and arguments when the procedure is called;
pops when it returns.
@item trace
Pushes the procedure-name and prints @samp{CALL @var{procedure-name}
@var{arg1} @dots{}} when the procdure is called; pops and prints
@samp{RETN @var{procedure-name} @var{value}} when the procedure returns.
@end table

@defvar debug:max-count
If a traced procedure calls itself or untraced procedures which call it,
stack, track, and trace will limit the number of stack pushes to
@var{debug:max-count}.
@end defvar

@defun print-call-stack
@defunx print-call-stack port
Prints the call-stack to @var{port} or the current-error-port.
@end defun


@defmac trace proc1 @dots{}
Traces the top-level named procedures given as arguments.
@defmacx trace
With no arguments, makes sure that all the currently traced identifiers
are traced (even if those identifiers have been redefined) and returns a
list of the traced identifiers.
@end defmac

@defmac track proc1 @dots{}
Traces the top-level named procedures given as arguments.
@defmacx track
With no arguments, makes sure that all the currently tracked identifiers
are tracked (even if those identifiers have been redefined) and returns
a list of the tracked identifiers.
@end defmac

@defmac stack proc1 @dots{}
Traces the top-level named procedures given as arguments.
@defmacx stack
With no arguments, makes sure that all the currently stacked identifiers
are stacked (even if those identifiers have been redefined) and returns
a list of the stacked identifiers.
@end defmac

@defmac untrace proc1 @dots{}
Turns tracing, tracking, and  off for its arguments.
@defmacx untrace
With no arguments, untraces all currently traced identifiers and returns
a list of these formerly traced identifiers.
@end defmac

@defmac untrack proc1 @dots{}
Turns tracing, tracking, and  off for its arguments.
@defmacx untrack
With no arguments, untracks all currently tracked identifiers and returns
a list of these formerly tracked identifiers.
@end defmac

@defmac unstack proc1 @dots{}
Turns tracing, stacking, and  off for its arguments.
@defmacx unstack
With no arguments, unstacks all currently stacked identifiers and returns
a list of these formerly stacked identifiers.
@end defmac

These are @emph{procedures} for tracing.  If defmacros are not natively
supported by your implementation, these might be more convenient to use.

@defun tracef proc
@defunx tracef proc name
@defunx trackf proc
@defunx trackf proc name
@defunx stackf proc
@defunx stackf proc name
To trace, type
@lisp
(set! @var{symbol} (tracef @var{symbol}))
@end lisp
@noindent
or
@lisp
(set! @var{symbol} (tracef @var{symbol} '@var{symbol}))
@end lisp
@noindent
or
@lisp
(define @var{symbol} (tracef @var{function}))
@end lisp
@noindent
or
@lisp
(define @var{symbol} (tracef @var{function} '@var{symbol}))
@end lisp
@end defun

@defun untracef proc
Removes tracing, tracking, or stacking for @var{proc}.
To untrace, type
@lisp
(set! @var{symbol} (untracef @var{symbol}))
@end lisp
@end defun


@node System Interface, Extra-SLIB Packages, Session Support, Other Packages
@section System Interface

@noindent
If @code{(provided? 'getenv)}:

@defun getenv name
Looks up @var{name}, a string, in the program environment.  If @var{name} is
found a string of its value is returned.  Otherwise, @code{#f} is returned.
@end defun

@noindent
If @code{(provided? 'system)}:

@defun system command-string
Executes the @var{command-string} on the computer and returns the
integer status code.
@end defun


@menu
* Directories::                 
* Transactions::                
* CVS::                         
@end menu

@node Directories, Transactions, System Interface, System Interface
@subsection Directories

@include dirs.txi


@node Transactions, CVS, Directories, System Interface
@subsection Transactions

@noindent
If @code{system} is provided by the Scheme implementation, the
@dfn{transact} package provides functions for file-locking and
file-replacement transactions.

@code{(require 'transact)}
@ftindex transact

@include transact.txi


@node CVS,  , Transactions, System Interface
@subsection CVS

@code{(require 'cvs)}
@ftindex cvs

@include cvs.txi


@node Extra-SLIB Packages,  , System Interface, Other Packages
@section Extra-SLIB Packages

Several Scheme packages have been written using SLIB.  There are several
reasons why a package might not be included in the SLIB distribution:
@itemize @bullet
@item
Because it requires special hardware or software which is not universal.
@item
Because it is large and of limited interest to most Scheme users.
@item
Because it has copying terms different enough from the other SLIB
packages that its inclusion would cause confusion.
@item
Because it is an application program, rather than a library module.
@item
Because I have been too busy to integrate it.
@end itemize

Once an optional package is installed (and an entry added to
@code{*catalog*}, the @code{require} mechanism allows it to be called up
and used as easily as any other SLIB package.  Some optional packages
(for which @code{*catalog*} already has entries) available from SLIB
sites are:

@table @asis
@item SLIB-PSD
@cindex PSD
is a portable debugger for Scheme (requires emacs editor).

@ifset html
<A HREF="http://swiss.csail.mit.edu/ftpdir/scm/slib-psd1-3.tar.gz">
@end ifset
http://swiss.csail.mit.edu/ftpdir/scm/slib-psd1-3.tar.gz
@ifset html
</A>
@end ifset

swiss.csail.mit.edu:/pub/scm/slib-psd1-3.tar.gz

ftp.maths.tcd.ie:pub/bosullvn/jacal/slib-psd1-3.tar.gz

ftp.cs.indiana.edu:/pub/scheme-repository/utl/slib-psd1-3.tar.gz
@sp 1

With PSD, you can run a Scheme program in an Emacs buffer, set
breakpoints, single step evaluation and access and modify the program's
variables. It works by instrumenting the original source code, so it
should run with any R4RS compliant Scheme. It has been tested with SCM,
Elk 1.5, and the sci interpreter in the Scheme->C system, but should
work with other Schemes with a minimal amount of porting, if at
all. Includes documentation and user's manual.  Written by Pertti
Kellom\"aki, pk @@ cs.tut.fi.  The Lisp Pointers article describing PSD
(Lisp Pointers VI(1):15-23, January-March 1993) is available as
@ifset html
<A HREF="http://www.cs.tut.fi/staff/pk/scheme/psd/article/article.html">
@end ifset
http://www.cs.tut.fi/staff/pk/scheme/psd/article/article.html
@ifset html
</A>
@end ifset
@sp 1

@item SCHELOG
@cindex SCHELOG
@cindex Prolog
is an embedding of Prolog in Scheme.@*
@ifset html
<A HREF="http://www.ccs.neu.edu/~dorai/schelog/schelog.html">
@end ifset
http://www.ccs.neu.edu/~dorai/schelog/schelog.html
@ifset html
</A>
@end ifset
@sp 1

@item JFILTER
@cindex JFILTER
@cindex Japanese
@cindex JIS
@cindex EUC
is a Scheme program which converts text among the JIS, EUC, and
Shift-JIS Japanese character sets.@*
@ifset html
<A HREF="http://www.sci.toyama-u.ac.jp/~iwao/Scheme/Jfilter/index.html">
@end ifset
http://www.sci.toyama-u.ac.jp/~iwao/Scheme/Jfilter/index.html
@ifset html
</A>
@end ifset
@end table


@node About SLIB, Index, Other Packages, Top
@chapter About SLIB

@noindent
More people than I can name have contributed to SLIB.  Thanks to all of
you!

@quotation
SLIB @value{SLIBVERSION}, released @value{SLIBDATE}.@*
Aubrey Jaffer <agj @@ alum.mit.edu>@*
@c @i{Hyperactive Software} -- The Maniac Inside!@*
@end quotation

Current information about SLIB can be found on SLIB's @dfn{WWW} home
page:

@center @url{http://swiss.csail.mit.edu/~jaffer/SLIB}

@menu
* Installation::                How to install SLIB on your system.
* The SLIB script::             Run interactive SLIB sessions.
* Porting::                     SLIB to new platforms.
* Coding Guidelines::           How to write modules for SLIB.
* Copyrights::                  Intellectual propery issues.
* About this manual::           
@end menu


@node Installation, The SLIB script, About SLIB, About SLIB
@section Installation

@ifset html
<A NAME="Installation">
@end ifset
@ifset html
</A>
@end ifset

@cindex install
@cindex installation
There are five parts to installation:

@itemize @bullet
@item
Unpack the SLIB distribution.
@item
Install documentation and @code{slib} script.
@item
Configure the Scheme implementation(s) to locate the SLIB directory.
@item
Arrange for Scheme implementation to load its SLIB initialization file.
@item
Build the SLIB catalog for the Scheme implementation.
@end itemize

@subsection Unpacking the SLIB Distribution

If the SLIB distribution is a Linux RPM, it will create the SLIB
directory @file{/usr/share/slib}.

If the SLIB distribution is a ZIP file, unzip the distribution to create
the SLIB directory.  Locate this @file{slib} directory either in your
home directory (if only you will use this SLIB installation); or put it
in a location where libraries reside on your system.  On unix systems
this might be @file{/usr/share/slib}, @file{/usr/local/lib/slib}, or
@file{/usr/lib/slib}.  If you know where SLIB should go on other
platforms, please inform agj @@ alum.mit.edu.

@subsection Install documentation and slib script

@cindex slib
@cindex script
@example
make infoz
make install
@end example

@subsection Configure Scheme Implementation to Locate SLIB

If the Scheme implementation supports @code{getenv}, then the value of
the shell environment variable @var{SCHEME_LIBRARY_PATH} will be used
for @code{(library-vicinity)} if it is defined.  Currently, Chez, Elk,
MITScheme, scheme->c, VSCM, and SCM support @code{getenv}.  Scheme48
supports @code{getenv} but does not use it for determining
@code{library-vicinity}.  (That is done from the Makefile.)

The @code{(library-vicinity)} can also be specified from the SLIB
initialization file or by implementation-specific means.

@subsection Loading SLIB Initialization File

Check the manifest in @file{README} to find a configuration file for
your Scheme implementation.  Initialization files for most IEEE P1178
compliant Scheme Implementations are included with this distribution.

You should check the definitions of @code{software-type},
@code{scheme-implementation-version},
@iftex
@*
@end iftex
@code{implementation-vicinity},
and @code{library-vicinity} in the initialization file.  There are
comments in the file for how to configure it.

Once this is done, modify the startup file for your Scheme
implementation to @code{load} this initialization file.

@subsection Build New SLIB Catalog for Implementation

When SLIB is first used from an implementation, a file named
@file{slibcat} is written to the @code{implementation-vicinity} for that
implementation.  Because users may lack permission to write in
@code{implementation-vicinity}, it is good practice to build the new
catalog when installing SLIB.

To build (or rebuild) the catalog, start the Scheme implementation (with
SLIB), then:

@example
(require 'new-catalog)
@end example

The catalog also supports color-name dictionaries.  With an
SLIB-installed scheme implementation, type:
@example
(require 'color-names)
(make-slib-color-name-db)
(require 'new-catalog)
(slib:exit)
@end example

@subsection Implementation-specific Instructions

Multiple implementations of Scheme can all use the same SLIB directory.
Simply configure each implementation's initialization file as outlined
above.

@deftp Implementation SCM
The SCM implementation does not require any initialization file as SLIB
support is already built into SCM.  See the documentation with SCM for
installation instructions.
@end deftp

@deftp Implementation {PLT Scheme}
@deftpx Implementation {DrScheme}
@deftpx Implementation {MzScheme}

The @file{init.ss} file in the _slibinit_ collection is an SLIB
initialization file.

To use SLIB in MzScheme, set the @var{SCHEME_LIBRARY_PATH} environment
variable to the installed SLIB location; then invoke MzScheme thus:

@code{mzscheme -f $@{SCHEME_LIBRARY_PATH@}DrScheme.init}
@end deftp

@deftp Implementation {MIT Scheme}
@code{scheme -load $@{SCHEME_LIBRARY_PATH@}mitscheme.init}
@end deftp

@deftp Implementation Gambit-C 3.0

@code{$command -:s $@{SCHEME_LIBRARY_PATH@}gambit.init -}
@end deftp

@deftp Implementation {Guile}
Guile versions 1.6 and earlier link to an archaic SLIB version.  In
RedHat or Fedora installations:

@example
rm /usr/share/guile/slib
ln -s $@{SCHEME_LIBRARY_PATH@} /usr/share/guile/slib
@end example

In Debian installations:

@example
rm /usr/share/guile/1.6/slib
ln -s $@{SCHEME_LIBRARY_PATH@} /usr/share/guile/1.6/slib
@end example

@code{$@{SCHEME_LIBRARY_PATH@}} is where SLIB gets installed.

Guile with SLIB can then be started thus:

@code{guile -l $@{SCHEME_LIBRARY_PATH@}guile.init}
@end deftp

@deftp Implementation Scheme48
To make a Scheme48 image for an installation under @code{<prefix>},

@enumerate
@item
@code{cd} to the SLIB directory
@item
type @code{make prefix=<prefix> slib48}.
@item
To install the image, type @code{make prefix=<prefix> install48}.  This
will also create a shell script with the name @code{slib48} which will
invoke the saved image.
@end enumerate
@end deftp

@deftp Implementation VSCM
@format
From: Matthias Blume <blume @@ cs.Princeton.EDU>
Date: Tue, 1 Mar 1994 11:42:31 -0500
@end format

Disclaimer: The code below is only a quick hack.  If I find some time to
spare I might get around to make some more things work.

You have to provide @file{vscm.init} as an explicit command line
argument.  Since this is not very nice I would recommend the following
installation procedure:

@enumerate
@item
run scheme
@item
@code{(load "vscm.init")}
@item
@code{(slib:dump "dumpfile")}
@item
mv dumpfile place-where-vscm-standard-bootfile-resides
e.g. mv dumpfile /usr/local/vscm/lib/scheme-boot
(In this case vscm should have been compiled with flag
-DDEFAULT_BOOTFILE='"/usr/local/vscm/lib/scheme-boot"'.  See Makefile
(definition of DDP) for details.)
@end enumerate

@end deftp


@node The SLIB script, Porting, Installation, About SLIB
@section The SLIB script

SLIB comes with shell script for Unix platforms.

@example
@exdent @b{ slib } [ scm | gsi | mzscheme | guile | slib48 | scheme48 | scmlit ]
@end example

@noindent
Starts an interactive Scheme-with-SLIB session.

@noindent
The optional argument to the @code{slib} script is the Scheme
implementation to run.  Absent the argument, it searches for
implementations in the above order.



@node Porting, Coding Guidelines, The SLIB script, About SLIB
@section Porting

If there is no initialization file for your Scheme implementation, you
will have to create one.  Your Scheme implementation must be largely
compliant with
@lisp
@cite{IEEE Std 1178-1990},
@cite{Revised^4 Report on the Algorithmic Language Scheme}, or
@cite{Revised^5 Report on the Algorithmic Language Scheme}
@end lisp
@noindent
in order to support SLIB.  @footnote{If you are porting a
@cite{Revised^3 Report on the Algorithmic Language Scheme}
implementation, then you will need to finish writing @file{sc4sc3.scm}
and @code{load} it from your initialization file.}

@file{Template.scm} is an example configuration file.  The comments
inside will direct you on how to customize it to reflect your system.
Give your new initialization file the implementation's name with
@file{.init} appended.  For instance, if you were porting
@code{foo-scheme} then the initialization file might be called
@file{foo.init}.

Your customized version should then be loaded as part of your scheme
implementation's initialization.  It will load @file{require.scm} from
the library; this will allow the use of @code{provide},
@code{provided?}, and @code{require} along with the @dfn{vicinity}
functions (these functions are documented in the sections
@ref{Feature} and @ref{Require}).  The rest of the library will then
be accessible in a system independent fashion.

Please mail new working configuration files to @code{agj @@ alum.mit.edu}
so that they can be included in the SLIB distribution.


@node Coding Guidelines, Copyrights, Porting, About SLIB
@section Coding Guidelines

All library packages are written in IEEE P1178 Scheme and assume that a
configuration file and @file{require.scm} package have already been
loaded.  Other versions of Scheme can be supported in library packages
as well by using, for example, @code{(provided? 'r3rs)} or
@code{(require 'r3rs)} (@pxref{Require}).
@ftindex r3rs

If a procedure defined in a module is called by other procedures in
that module, then those procedures should instead call an alias
defined in that module:

@lisp
(define module-name:foo foo)
@end lisp

The module name and @samp{:} should prefix that symbol for the
internal name.  Do not export internal aliases.

A procedure is exported from a module by putting Schmooz-style
comments (@pxref{Schmooz}) or @samp{;@@} at the beginning of the line
immediately preceding the definition (@code{define},
@code{define-syntax}, or @code{defmacro}).  Modules, exports and other
relevant issues are discussed in @ref{Compiling Scheme}.

Code submitted for inclusion in SLIB should not duplicate (more than
one) routines already in SLIB files.  Use @code{require} to force
those library routines to be used by your package.

Documentation should be provided in Emacs Texinfo format if possible,
but documentation must be provided.

Your package will be released sooner with SLIB if you send me a file
which tests your code.  Please run this test @emph{before} you send me
the code!

@subsection Modifications

Please document your changes.  A line or two for @file{ChangeLog} is
sufficient for simple fixes or extensions.  Look at the format of
@file{ChangeLog} to see what information is desired.  Please send me
@code{diff} files from the latest SLIB distribution (remember to send
@code{diff}s of @file{slib.texi} and @file{ChangeLog}).  This makes for
less email traffic and makes it easier for me to integrate when more
than one person is changing a file (this happens a lot with
@file{slib.texi} and @samp{*.init} files).

If someone else wrote a package you want to significantly modify, please
try to contact the author, who may be working on a new version.  This
will insure against wasting effort on obsolete versions.

Please @emph{do not} reformat the source code with your favorite
beautifier, make 10 fixes, and send me the resulting source code.  I do
not have the time to fish through 10000 diffs to find your 10 real fixes.

@node Copyrights, About this manual, Coding Guidelines, About SLIB
@section Copyrights

@ifset html
<A NAME="Copyrights">
@end ifset
@ifset html
</A>
@end ifset

This section has instructions for SLIB authors regarding copyrights.
@cindex copyright

Each package in SLIB must either be in the public domain, or come with a
statement of terms permitting users to copy, redistribute and modify it.
The comments at the beginning of @file{require.scm} and
@file{macwork.scm} illustrate copyright and appropriate terms.

If your code or changes amount to less than about 10 lines, you do not
need to add your copyright or send a disclaimer.

@subsection Putting code into the Public Domain

In order to put code in the public domain you should sign a copyright
disclaimer and send it to the SLIB maintainer.  Contact
agj @@ alum.mit.edu for the address to mail the disclaimer to.

@need 1000
@quotation
I, @var{<my-name>}, hereby affirm that I have placed the software
package @var{<name>} in the public domain.

I affirm that I am the sole author and sole copyright holder for the
software package, that I have the right to place this software package
in the public domain, and that I will do nothing to undermine this
status in the future.
@flushright
                                        @var{signature and date}
@end flushright
@end quotation

This wording assumes that you are the sole author.  If you are not the
sole author, the wording needs to be different.  If you don't want to
be bothered with sending a letter every time you release or modify a
module, make your letter say that it also applies to your future
revisions of that module.

Make sure no employer has any claim to the copyright on the work you
are submitting.  If there is any doubt, create a copyright disclaimer
and have your employer sign it.  Mail the signed disclaimer to the
SLIB maintainer.  Contact agj @@ alum.mit.edu for the address to mail
the disclaimer to.  An example disclaimer follows.

@subsection Explicit copying terms

@noindent
If you submit more than about 10 lines of code which you are not
placing into the Public Domain (by sending me a disclaimer) you need
to:

@itemize @bullet
@item
Arrange that your name appears in a copyright line for the appropriate
year.  Multiple copyright lines are acceptable.
@item
With your copyright line, specify any terms you require to be
different from those already in the file.
@item
Make sure no employer has any claim to the copyright on the work you
are submitting.  If there is any doubt, create a copyright disclaimer
and have your employer sign it.  Mail the signed disclaim to the SLIB
maintainer.  Contact agj @@ alum.mit.edu for the address to mail the
disclaimer to.
@end itemize

@subsection Example: Company Copyright Disclaimer

This disclaimer should be signed by a vice president or general
manager of the company.  If you can't get at them, anyone else
authorized to license out software produced there will do.  Here is a
sample wording:

@quotation
@var{<employer>} Corporation hereby disclaims all copyright
interest in the program @var{<program>} written by @var{<name>}.

@var{<employer>} Corporation affirms that it has no other intellectual
property interest that would undermine this release, and will do
nothing to undermine it in the future.

@flushleft
@var{<signature and date>},
@var{<name>}, @var{<title>}, @var{<employer>} Corporation
@end flushleft
@end quotation

@node About this manual,  , Copyrights, About SLIB
@section About this manual

@menu
* Copying This Manual::         
* How to use this License for your documents::  
@end menu

@itemize @bullet
@item
Entries that are labeled as Functions are called for their return
values.  Entries that are labeled as Procedures are called primarily for
their side effects.

@item
Examples in this text were produced using the @code{scm} Scheme
implementation.

@item
At the beginning of each section, there is a line that looks like
@ftindex feature
@code{(require 'feature)}.  Include this line in your code prior to
using the package.
@end itemize

@include fdl.texi

@ifinfo
@node Index,  , About SLIB, Top
@unnumbered Index
@end ifinfo

@include indexes.texi
@bye