aboutsummaryrefslogtreecommitdiffstats
path: root/slib.info
blob: d4c570a8371a7ee5253b5b9c8536cd336bafee46 (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
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
15516
15517
15518
15519
15520
15521
15522
15523
15524
15525
15526
15527
15528
15529
15530
15531
15532
15533
15534
15535
15536
15537
15538
15539
15540
15541
15542
15543
15544
15545
15546
15547
15548
15549
15550
15551
15552
15553
15554
15555
15556
15557
15558
15559
15560
15561
15562
15563
15564
15565
15566
15567
15568
15569
15570
15571
15572
15573
15574
15575
15576
15577
15578
15579
15580
15581
15582
15583
15584
15585
15586
15587
15588
15589
15590
15591
15592
15593
15594
15595
15596
15597
15598
15599
15600
15601
15602
15603
15604
15605
15606
15607
15608
15609
15610
15611
15612
15613
15614
15615
15616
15617
15618
15619
15620
15621
15622
15623
15624
15625
15626
15627
15628
15629
15630
15631
15632
15633
15634
15635
15636
15637
15638
15639
15640
15641
15642
15643
15644
15645
15646
15647
15648
15649
15650
15651
15652
15653
15654
15655
15656
15657
15658
15659
15660
15661
15662
15663
15664
15665
15666
15667
15668
15669
15670
15671
15672
15673
15674
15675
15676
15677
15678
15679
15680
15681
15682
15683
15684
15685
15686
15687
15688
15689
15690
15691
15692
15693
15694
15695
15696
15697
15698
15699
15700
15701
15702
15703
15704
15705
15706
15707
15708
15709
15710
15711
15712
15713
15714
15715
15716
15717
15718
15719
15720
15721
15722
15723
15724
15725
15726
15727
15728
15729
15730
15731
15732
15733
15734
15735
15736
15737
15738
15739
15740
15741
15742
15743
15744
15745
15746
15747
15748
15749
15750
15751
15752
15753
15754
15755
15756
15757
15758
15759
15760
15761
15762
15763
15764
15765
15766
15767
15768
15769
15770
15771
15772
15773
15774
15775
15776
15777
15778
15779
15780
15781
15782
15783
15784
15785
15786
15787
15788
15789
15790
15791
15792
15793
15794
15795
15796
15797
15798
15799
15800
15801
15802
15803
15804
15805
15806
15807
15808
15809
15810
15811
15812
15813
15814
15815
15816
15817
15818
15819
15820
15821
15822
15823
15824
15825
15826
15827
15828
15829
15830
15831
15832
15833
15834
15835
15836
15837
15838
15839
15840
15841
15842
15843
15844
15845
15846
15847
15848
15849
15850
15851
15852
15853
15854
15855
15856
15857
15858
15859
15860
15861
15862
15863
15864
15865
15866
15867
15868
15869
15870
15871
15872
15873
15874
15875
15876
15877
15878
15879
15880
15881
15882
15883
15884
15885
15886
15887
15888
15889
15890
15891
15892
15893
15894
15895
15896
15897
15898
15899
15900
15901
15902
15903
15904
15905
15906
15907
15908
15909
15910
15911
15912
15913
15914
15915
15916
15917
15918
15919
15920
15921
15922
15923
15924
15925
15926
15927
15928
15929
15930
15931
15932
15933
15934
15935
15936
15937
15938
15939
15940
15941
15942
15943
15944
15945
15946
15947
15948
15949
15950
15951
15952
15953
15954
15955
15956
15957
15958
15959
15960
15961
15962
15963
15964
15965
15966
15967
15968
15969
15970
15971
15972
15973
15974
15975
15976
15977
15978
15979
15980
15981
15982
15983
15984
15985
15986
15987
15988
15989
15990
15991
15992
15993
15994
15995
15996
15997
15998
15999
16000
16001
16002
16003
16004
16005
16006
16007
16008
16009
16010
16011
16012
16013
16014
16015
16016
16017
16018
16019
16020
16021
16022
16023
16024
16025
16026
16027
16028
16029
16030
16031
16032
16033
16034
16035
16036
16037
16038
16039
16040
16041
16042
16043
16044
16045
16046
16047
16048
16049
16050
16051
16052
16053
16054
16055
16056
16057
16058
16059
16060
16061
16062
16063
16064
16065
16066
16067
16068
16069
16070
16071
16072
16073
16074
16075
16076
16077
16078
16079
16080
16081
16082
16083
16084
16085
16086
16087
16088
16089
16090
16091
16092
16093
16094
16095
16096
16097
16098
16099
16100
16101
16102
16103
16104
16105
16106
16107
16108
16109
16110
16111
16112
16113
16114
16115
16116
16117
16118
16119
16120
16121
16122
16123
16124
16125
16126
16127
16128
16129
16130
16131
16132
16133
16134
16135
16136
16137
16138
16139
16140
16141
16142
16143
16144
16145
16146
16147
16148
16149
16150
16151
16152
16153
16154
16155
16156
16157
16158
16159
16160
16161
16162
16163
16164
16165
16166
16167
16168
16169
16170
16171
16172
16173
16174
16175
16176
16177
16178
16179
16180
16181
16182
16183
16184
16185
16186
16187
16188
16189
16190
16191
16192
16193
16194
16195
16196
16197
16198
16199
16200
16201
16202
16203
16204
16205
16206
16207
16208
16209
16210
16211
16212
16213
16214
16215
16216
16217
16218
16219
16220
16221
16222
16223
16224
16225
16226
16227
16228
16229
16230
16231
16232
16233
16234
16235
16236
16237
16238
16239
16240
16241
16242
16243
16244
16245
16246
16247
16248
16249
16250
16251
16252
16253
16254
16255
16256
16257
16258
16259
16260
16261
16262
16263
16264
16265
16266
16267
16268
16269
16270
16271
16272
16273
16274
16275
16276
16277
16278
16279
16280
16281
16282
16283
16284
16285
16286
16287
16288
16289
16290
16291
16292
16293
16294
16295
16296
16297
16298
16299
16300
16301
16302
16303
16304
16305
16306
16307
16308
16309
16310
16311
16312
16313
16314
16315
16316
16317
16318
16319
16320
16321
16322
16323
16324
16325
16326
16327
16328
16329
16330
16331
16332
16333
16334
16335
16336
16337
16338
16339
16340
16341
16342
16343
16344
16345
16346
16347
16348
16349
16350
16351
16352
16353
16354
16355
16356
16357
16358
16359
16360
16361
16362
16363
16364
16365
16366
16367
16368
16369
16370
16371
16372
16373
16374
16375
16376
16377
16378
16379
16380
16381
16382
16383
16384
16385
16386
16387
16388
16389
16390
16391
16392
16393
16394
16395
16396
16397
16398
16399
16400
16401
16402
16403
16404
16405
16406
16407
16408
16409
16410
16411
16412
16413
16414
16415
16416
16417
16418
16419
16420
16421
16422
16423
16424
16425
16426
16427
16428
16429
16430
16431
16432
16433
16434
16435
16436
16437
16438
16439
16440
16441
16442
16443
16444
16445
16446
16447
16448
16449
16450
16451
16452
16453
16454
16455
16456
16457
16458
16459
16460
16461
16462
16463
16464
16465
16466
16467
16468
16469
16470
16471
16472
16473
16474
16475
16476
16477
16478
16479
16480
16481
16482
16483
16484
16485
16486
16487
16488
16489
16490
16491
16492
16493
16494
16495
16496
16497
16498
16499
16500
16501
16502
16503
16504
16505
16506
16507
16508
16509
16510
16511
16512
16513
16514
16515
16516
16517
16518
16519
16520
16521
16522
16523
16524
16525
16526
16527
16528
16529
16530
16531
16532
16533
16534
16535
16536
16537
16538
16539
16540
16541
16542
16543
16544
16545
16546
16547
16548
16549
16550
16551
16552
16553
16554
16555
16556
16557
16558
16559
16560
16561
16562
16563
16564
16565
16566
16567
16568
16569
16570
16571
16572
16573
16574
16575
16576
16577
16578
16579
16580
16581
16582
16583
16584
16585
16586
16587
16588
16589
16590
16591
16592
16593
16594
16595
16596
16597
16598
16599
16600
16601
16602
16603
16604
16605
16606
16607
16608
16609
16610
16611
16612
16613
16614
16615
16616
16617
16618
16619
16620
16621
16622
16623
16624
16625
16626
16627
16628
16629
16630
16631
16632
16633
16634
16635
16636
16637
16638
16639
16640
16641
16642
16643
16644
16645
16646
16647
16648
16649
16650
16651
16652
16653
16654
16655
16656
16657
16658
16659
16660
16661
16662
16663
16664
16665
16666
16667
16668
16669
16670
16671
16672
16673
16674
16675
16676
16677
16678
16679
16680
16681
16682
16683
16684
16685
16686
16687
16688
16689
16690
16691
16692
16693
16694
16695
16696
16697
16698
16699
16700
16701
16702
16703
16704
16705
16706
16707
16708
16709
16710
16711
16712
16713
16714
16715
16716
16717
16718
16719
16720
16721
16722
16723
16724
16725
16726
16727
16728
16729
16730
16731
16732
16733
16734
16735
16736
16737
16738
16739
16740
16741
16742
16743
16744
16745
16746
16747
16748
16749
16750
16751
16752
16753
16754
16755
16756
16757
16758
16759
16760
16761
16762
16763
16764
16765
16766
16767
16768
16769
16770
16771
16772
16773
16774
16775
16776
16777
16778
16779
16780
16781
16782
16783
16784
16785
16786
16787
16788
16789
16790
16791
16792
16793
16794
16795
16796
16797
16798
16799
16800
16801
16802
16803
16804
16805
16806
16807
16808
16809
16810
16811
16812
16813
16814
16815
16816
16817
16818
16819
16820
16821
16822
16823
16824
16825
16826
16827
16828
16829
16830
16831
16832
16833
16834
16835
16836
16837
16838
16839
16840
16841
16842
16843
16844
16845
16846
16847
16848
16849
16850
16851
16852
16853
16854
16855
16856
16857
16858
16859
16860
16861
16862
16863
16864
16865
16866
16867
16868
16869
16870
16871
16872
16873
16874
16875
16876
16877
16878
16879
16880
16881
16882
16883
16884
16885
16886
16887
16888
16889
16890
16891
16892
16893
16894
16895
16896
16897
16898
16899
16900
16901
16902
16903
16904
16905
16906
16907
16908
16909
16910
16911
16912
16913
16914
16915
16916
16917
16918
16919
16920
16921
16922
16923
16924
16925
16926
16927
16928
16929
16930
16931
16932
16933
16934
16935
16936
16937
16938
16939
16940
16941
16942
16943
16944
16945
16946
16947
16948
16949
16950
16951
16952
16953
16954
16955
16956
16957
16958
16959
16960
16961
16962
16963
16964
16965
16966
16967
16968
16969
16970
16971
16972
16973
16974
16975
16976
16977
16978
16979
16980
16981
16982
16983
16984
16985
16986
16987
16988
16989
16990
16991
16992
16993
16994
16995
16996
16997
16998
16999
17000
17001
17002
17003
17004
17005
17006
17007
17008
17009
17010
17011
17012
17013
17014
17015
17016
17017
17018
17019
17020
17021
17022
17023
17024
17025
17026
17027
17028
17029
17030
17031
17032
17033
17034
17035
17036
17037
17038
17039
17040
17041
17042
17043
17044
17045
17046
17047
17048
17049
17050
17051
17052
17053
17054
17055
17056
17057
17058
17059
17060
17061
17062
17063
17064
17065
17066
17067
17068
17069
17070
17071
17072
17073
17074
17075
17076
17077
17078
17079
17080
17081
17082
17083
17084
17085
17086
17087
17088
17089
17090
17091
17092
17093
17094
17095
17096
17097
17098
17099
17100
17101
17102
17103
17104
17105
17106
17107
17108
17109
17110
17111
17112
17113
17114
17115
17116
17117
17118
17119
17120
17121
17122
17123
17124
17125
17126
17127
17128
17129
17130
17131
17132
17133
17134
17135
17136
17137
17138
17139
17140
17141
17142
17143
17144
17145
17146
17147
17148
17149
17150
17151
17152
17153
17154
17155
17156
17157
17158
17159
17160
17161
17162
17163
17164
17165
17166
17167
17168
17169
17170
17171
17172
17173
17174
17175
17176
17177
17178
17179
17180
17181
17182
17183
17184
17185
17186
17187
17188
17189
17190
17191
17192
17193
17194
17195
17196
17197
17198
17199
17200
17201
17202
17203
17204
17205
17206
17207
17208
17209
17210
17211
17212
17213
17214
17215
17216
17217
17218
17219
17220
17221
17222
17223
17224
17225
17226
17227
17228
17229
17230
17231
17232
17233
17234
17235
17236
17237
17238
17239
17240
17241
17242
17243
17244
17245
17246
17247
17248
17249
17250
17251
17252
17253
17254
17255
17256
17257
17258
17259
17260
17261
17262
17263
17264
17265
17266
17267
17268
17269
17270
17271
17272
17273
17274
17275
17276
17277
17278
17279
17280
17281
17282
17283
17284
17285
17286
17287
17288
17289
17290
17291
17292
17293
17294
17295
17296
17297
17298
17299
17300
17301
17302
17303
17304
17305
17306
17307
17308
17309
17310
17311
17312
17313
17314
17315
17316
17317
17318
17319
17320
17321
17322
17323
17324
17325
17326
17327
17328
17329
17330
17331
17332
17333
17334
17335
17336
17337
17338
17339
17340
17341
17342
17343
17344
17345
17346
17347
17348
17349
17350
17351
17352
17353
17354
17355
17356
17357
17358
17359
17360
17361
17362
17363
17364
17365
17366
17367
17368
17369
17370
17371
17372
17373
17374
17375
17376
17377
17378
17379
17380
17381
17382
17383
17384
17385
17386
17387
17388
17389
17390
17391
17392
17393
17394
17395
17396
17397
17398
17399
17400
17401
17402
17403
17404
17405
17406
17407
17408
17409
17410
17411
17412
17413
17414
17415
17416
17417
17418
17419
17420
17421
17422
17423
17424
17425
17426
17427
17428
17429
17430
17431
17432
17433
17434
17435
17436
17437
17438
17439
17440
17441
17442
17443
17444
17445
17446
17447
17448
17449
17450
17451
17452
17453
17454
17455
17456
17457
17458
17459
17460
17461
17462
17463
17464
17465
17466
17467
17468
17469
17470
17471
17472
17473
17474
17475
17476
17477
17478
17479
17480
17481
17482
17483
17484
17485
17486
17487
17488
17489
17490
17491
17492
17493
17494
17495
17496
17497
17498
17499
17500
17501
17502
17503
17504
17505
17506
17507
17508
17509
17510
17511
17512
17513
17514
17515
17516
17517
17518
17519
17520
17521
17522
17523
17524
17525
17526
17527
17528
17529
17530
17531
17532
17533
17534
17535
17536
17537
17538
17539
17540
17541
17542
17543
17544
17545
17546
17547
17548
17549
17550
17551
17552
17553
17554
17555
17556
17557
17558
17559
17560
17561
17562
17563
17564
17565
17566
17567
17568
17569
17570
17571
17572
17573
17574
17575
17576
17577
17578
17579
17580
17581
17582
17583
17584
17585
17586
17587
17588
17589
17590
17591
17592
17593
17594
17595
17596
17597
17598
17599
17600
17601
17602
17603
17604
17605
17606
17607
17608
17609
17610
17611
17612
17613
17614
17615
17616
17617
17618
17619
17620
17621
17622
17623
17624
17625
17626
17627
17628
17629
17630
17631
17632
17633
17634
17635
17636
17637
17638
17639
17640
17641
17642
17643
17644
17645
17646
17647
17648
17649
17650
17651
17652
17653
17654
17655
17656
17657
17658
17659
17660
17661
17662
17663
17664
17665
17666
17667
17668
17669
17670
17671
17672
17673
17674
17675
17676
17677
17678
17679
17680
17681
17682
17683
17684
17685
17686
17687
17688
17689
17690
17691
17692
17693
17694
17695
17696
17697
17698
17699
17700
17701
17702
17703
17704
17705
17706
17707
17708
17709
17710
17711
17712
17713
17714
17715
17716
17717
17718
17719
17720
17721
17722
17723
17724
17725
17726
17727
17728
17729
17730
17731
17732
17733
17734
17735
17736
17737
17738
17739
17740
17741
17742
17743
17744
17745
17746
17747
17748
17749
17750
17751
17752
17753
17754
17755
17756
17757
17758
17759
17760
17761
17762
17763
17764
17765
17766
17767
17768
17769
17770
17771
17772
17773
17774
17775
17776
17777
17778
17779
17780
17781
17782
17783
17784
17785
17786
17787
17788
17789
17790
17791
17792
17793
17794
17795
17796
17797
17798
17799
17800
17801
17802
17803
17804
17805
17806
17807
17808
17809
17810
17811
17812
17813
17814
17815
17816
17817
17818
17819
17820
17821
17822
17823
17824
17825
17826
17827
17828
17829
17830
17831
17832
17833
17834
17835
17836
17837
17838
17839
17840
17841
17842
17843
17844
17845
17846
17847
17848
17849
17850
17851
17852
17853
17854
17855
17856
17857
17858
17859
17860
17861
17862
17863
17864
17865
17866
17867
17868
17869
17870
17871
17872
17873
17874
17875
17876
17877
17878
17879
17880
17881
17882
17883
17884
17885
17886
17887
17888
17889
17890
17891
17892
17893
17894
17895
17896
17897
17898
17899
17900
17901
17902
17903
17904
17905
17906
17907
17908
17909
17910
17911
17912
17913
17914
17915
17916
17917
17918
17919
17920
17921
17922
17923
17924
17925
17926
17927
17928
17929
17930
17931
17932
17933
17934
17935
17936
17937
17938
17939
17940
17941
17942
17943
17944
17945
17946
17947
17948
17949
17950
17951
17952
17953
17954
17955
17956
17957
17958
17959
17960
17961
17962
17963
17964
17965
17966
17967
17968
17969
17970
17971
17972
17973
17974
17975
17976
17977
17978
17979
17980
17981
17982
17983
17984
17985
17986
17987
17988
17989
17990
17991
17992
17993
17994
17995
17996
17997
17998
17999
18000
18001
18002
18003
18004
18005
18006
18007
18008
18009
18010
18011
18012
18013
18014
18015
18016
18017
18018
18019
18020
18021
18022
18023
18024
18025
18026
18027
18028
18029
18030
18031
18032
18033
18034
18035
18036
18037
18038
18039
18040
18041
18042
18043
18044
18045
18046
18047
18048
18049
18050
18051
18052
18053
18054
18055
18056
18057
18058
18059
18060
18061
18062
18063
18064
18065
18066
18067
18068
18069
18070
18071
18072
18073
18074
18075
18076
18077
18078
18079
18080
18081
18082
18083
18084
18085
18086
18087
18088
18089
18090
18091
18092
18093
18094
18095
18096
18097
18098
18099
18100
18101
18102
18103
18104
18105
18106
18107
18108
18109
18110
18111
18112
18113
18114
18115
18116
18117
18118
18119
18120
18121
18122
18123
18124
18125
18126
18127
18128
18129
18130
18131
18132
18133
18134
18135
18136
18137
18138
18139
18140
18141
18142
18143
18144
18145
18146
18147
18148
18149
18150
18151
18152
18153
18154
18155
18156
18157
18158
18159
18160
18161
18162
18163
18164
18165
18166
18167
18168
18169
18170
18171
18172
18173
18174
18175
18176
18177
18178
18179
18180
18181
18182
18183
18184
18185
18186
18187
18188
18189
18190
18191
18192
18193
18194
18195
18196
18197
18198
18199
18200
18201
18202
18203
18204
18205
18206
18207
18208
18209
18210
18211
18212
18213
18214
18215
18216
18217
18218
18219
18220
18221
18222
18223
18224
18225
18226
18227
18228
18229
18230
18231
18232
18233
18234
18235
18236
18237
18238
18239
18240
18241
18242
18243
18244
18245
18246
18247
18248
18249
18250
18251
18252
18253
18254
18255
18256
18257
18258
18259
18260
18261
18262
18263
18264
18265
18266
18267
18268
18269
18270
18271
18272
18273
18274
18275
18276
18277
18278
18279
18280
18281
18282
18283
18284
18285
18286
18287
18288
18289
18290
18291
18292
18293
18294
18295
18296
18297
18298
18299
18300
18301
18302
18303
18304
18305
18306
18307
18308
18309
18310
18311
18312
18313
18314
18315
18316
18317
18318
18319
18320
18321
18322
18323
18324
18325
18326
18327
18328
18329
18330
18331
18332
18333
18334
18335
18336
18337
18338
18339
18340
18341
18342
18343
18344
18345
18346
18347
18348
18349
18350
18351
18352
18353
18354
18355
18356
18357
18358
18359
18360
18361
18362
18363
18364
18365
18366
18367
18368
18369
18370
18371
18372
18373
18374
18375
18376
18377
18378
18379
18380
18381
18382
18383
18384
18385
18386
18387
18388
18389
18390
18391
18392
18393
18394
18395
18396
18397
18398
18399
18400
18401
18402
18403
18404
18405
18406
18407
18408
18409
18410
18411
18412
18413
18414
18415
18416
18417
18418
18419
18420
18421
18422
18423
18424
18425
18426
18427
18428
18429
18430
18431
18432
18433
18434
18435
18436
18437
18438
18439
18440
18441
18442
18443
18444
18445
18446
18447
18448
18449
18450
18451
18452
18453
18454
18455
18456
18457
18458
18459
18460
18461
18462
18463
18464
18465
18466
18467
18468
18469
18470
18471
18472
18473
18474
18475
18476
18477
18478
18479
18480
18481
18482
18483
18484
18485
18486
18487
18488
18489
18490
18491
18492
18493
18494
18495
18496
18497
18498
18499
18500
18501
18502
18503
18504
18505
18506
18507
18508
18509
18510
18511
18512
18513
18514
18515
18516
18517
18518
18519
18520
18521
18522
18523
18524
18525
18526
18527
18528
18529
18530
18531
18532
18533
18534
18535
18536
18537
18538
18539
18540
18541
18542
18543
18544
18545
18546
18547
18548
18549
18550
18551
18552
18553
18554
18555
18556
18557
18558
18559
18560
18561
18562
18563
18564
18565
18566
18567
18568
18569
18570
18571
18572
18573
18574
18575
18576
18577
18578
18579
18580
18581
18582
18583
18584
18585
18586
18587
18588
18589
18590
18591
18592
18593
18594
18595
18596
18597
18598
18599
18600
18601
18602
18603
18604
18605
18606
18607
18608
18609
18610
18611
18612
18613
18614
18615
18616
18617
18618
18619
18620
18621
18622
18623
18624
18625
18626
18627
18628
18629
18630
18631
18632
18633
18634
18635
18636
18637
18638
18639
18640
18641
18642
18643
18644
18645
18646
18647
18648
18649
18650
18651
18652
18653
18654
18655
18656
18657
18658
18659
18660
18661
18662
18663
18664
18665
18666
18667
18668
18669
18670
18671
18672
18673
18674
18675
18676
18677
18678
18679
18680
18681
18682
18683
18684
18685
18686
18687
18688
18689
18690
18691
18692
18693
18694
18695
18696
18697
18698
18699
18700
18701
18702
18703
18704
18705
18706
18707
18708
18709
18710
18711
18712
18713
18714
18715
18716
18717
18718
18719
18720
18721
18722
18723
18724
18725
18726
18727
18728
18729
18730
18731
18732
18733
18734
18735
18736
18737
18738
18739
18740
18741
18742
18743
18744
18745
18746
18747
18748
18749
18750
18751
18752
18753
18754
18755
18756
18757
18758
18759
18760
18761
18762
18763
18764
18765
18766
18767
18768
18769
18770
18771
18772
18773
18774
18775
18776
18777
18778
18779
18780
18781
18782
18783
18784
18785
18786
18787
18788
18789
18790
18791
18792
18793
18794
18795
18796
18797
18798
18799
18800
18801
18802
18803
18804
18805
18806
18807
18808
18809
18810
18811
18812
18813
18814
18815
18816
18817
18818
18819
18820
18821
18822
18823
18824
18825
18826
18827
18828
18829
18830
18831
18832
18833
18834
18835
18836
18837
18838
18839
18840
18841
18842
18843
18844
18845
18846
18847
18848
18849
18850
18851
18852
18853
18854
18855
18856
18857
18858
18859
18860
18861
18862
18863
18864
18865
18866
18867
18868
18869
18870
18871
18872
18873
18874
18875
18876
18877
18878
18879
18880
18881
18882
18883
18884
18885
18886
18887
18888
18889
18890
18891
18892
18893
18894
18895
18896
18897
18898
18899
18900
18901
18902
18903
18904
18905
18906
18907
18908
18909
18910
18911
18912
18913
18914
18915
18916
18917
18918
18919
18920
18921
18922
18923
18924
18925
18926
18927
18928
18929
18930
18931
18932
18933
18934
18935
18936
18937
18938
18939
18940
18941
18942
18943
18944
18945
18946
18947
18948
18949
18950
18951
18952
18953
18954
18955
18956
18957
18958
18959
18960
18961
18962
18963
18964
18965
18966
18967
18968
18969
18970
18971
18972
18973
18974
18975
18976
18977
18978
18979
18980
18981
18982
18983
18984
18985
18986
18987
18988
18989
18990
18991
18992
18993
18994
18995
18996
18997
18998
18999
19000
19001
19002
19003
19004
19005
19006
19007
19008
19009
19010
19011
19012
19013
19014
19015
19016
19017
19018
19019
19020
19021
19022
19023
19024
19025
19026
19027
19028
19029
19030
19031
19032
19033
19034
19035
19036
19037
19038
19039
19040
19041
19042
19043
19044
19045
19046
19047
19048
19049
19050
19051
19052
19053
19054
19055
19056
19057
19058
19059
19060
19061
19062
19063
19064
19065
19066
19067
19068
19069
19070
19071
19072
19073
19074
19075
19076
19077
19078
19079
19080
19081
19082
19083
19084
19085
19086
19087
19088
19089
19090
19091
19092
19093
19094
19095
19096
19097
19098
19099
19100
19101
19102
19103
19104
19105
19106
19107
19108
19109
19110
19111
19112
19113
19114
19115
19116
19117
19118
19119
19120
19121
19122
19123
19124
19125
19126
19127
19128
19129
19130
19131
19132
19133
19134
19135
19136
19137
19138
19139
19140
19141
19142
19143
19144
19145
19146
19147
19148
19149
19150
19151
19152
19153
19154
19155
19156
19157
19158
19159
19160
19161
19162
19163
19164
19165
19166
19167
19168
19169
19170
19171
19172
19173
19174
19175
19176
19177
19178
19179
19180
19181
19182
19183
19184
19185
19186
19187
19188
19189
19190
19191
19192
19193
19194
19195
19196
19197
19198
19199
19200
19201
19202
19203
19204
19205
19206
19207
19208
19209
19210
19211
19212
19213
19214
19215
19216
19217
19218
19219
19220
19221
19222
19223
19224
19225
19226
19227
19228
19229
19230
19231
19232
19233
19234
19235
19236
19237
19238
19239
19240
19241
19242
19243
19244
19245
19246
19247
19248
19249
19250
19251
19252
19253
19254
19255
19256
19257
19258
19259
19260
19261
19262
19263
19264
19265
19266
19267
19268
19269
19270
19271
19272
19273
19274
19275
19276
19277
19278
19279
19280
19281
19282
19283
19284
19285
19286
19287
19288
19289
19290
19291
19292
19293
19294
19295
19296
19297
19298
19299
19300
19301
19302
19303
19304
19305
19306
19307
19308
19309
19310
19311
19312
19313
19314
19315
19316
19317
19318
19319
19320
19321
19322
19323
19324
19325
19326
19327
19328
19329
19330
19331
19332
19333
19334
19335
19336
19337
19338
19339
19340
19341
19342
19343
19344
19345
19346
19347
19348
19349
19350
19351
19352
19353
19354
19355
19356
19357
19358
19359
19360
19361
19362
19363
19364
19365
19366
19367
19368
19369
19370
19371
19372
19373
19374
19375
19376
19377
19378
19379
19380
19381
19382
19383
19384
19385
19386
19387
19388
19389
19390
19391
19392
19393
19394
19395
19396
19397
19398
19399
19400
19401
19402
19403
19404
19405
19406
19407
19408
19409
19410
19411
19412
19413
19414
19415
19416
19417
19418
19419
19420
19421
19422
19423
19424
19425
19426
19427
19428
19429
19430
19431
19432
19433
19434
19435
19436
19437
19438
19439
19440
19441
19442
19443
19444
19445
19446
19447
19448
19449
19450
19451
19452
19453
19454
19455
19456
19457
19458
19459
19460
19461
19462
19463
19464
19465
19466
19467
19468
19469
19470
19471
19472
19473
19474
19475
19476
19477
19478
19479
19480
19481
19482
19483
19484
19485
19486
19487
19488
19489
19490
19491
19492
19493
19494
19495
19496
19497
19498
19499
19500
19501
19502
19503
19504
19505
19506
19507
19508
19509
19510
19511
19512
19513
19514
19515
19516
19517
19518
19519
19520
19521
19522
19523
19524
19525
19526
19527
19528
19529
19530
19531
19532
19533
19534
19535
19536
19537
19538
19539
19540
19541
19542
19543
19544
19545
19546
19547
19548
19549
19550
19551
19552
19553
19554
19555
19556
19557
19558
19559
19560
19561
19562
19563
19564
19565
19566
19567
19568
19569
19570
19571
19572
19573
19574
19575
19576
19577
19578
19579
19580
19581
19582
19583
19584
19585
19586
19587
19588
19589
19590
19591
19592
19593
19594
19595
19596
19597
19598
19599
19600
19601
19602
19603
19604
19605
19606
19607
This is slib.info, produced by makeinfo version 4.8 from slib.texi.

This manual is for SLIB (version 3b1, February 2008), the portable            |
Scheme library.

Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
2002, 2003, 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.       |

     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, no Front-Cover Texts, and
     no Back-Cover Texts.  A copy of the license is included in the
     section entitled "GNU Free Documentation License."

INFO-DIR-SECTION The Algorithmic Language Scheme
START-INFO-DIR-ENTRY
* SLIB: (slib).         Scheme Library
END-INFO-DIR-ENTRY


File: slib.info,  Node: Top,  Next: The Library System,  Prev: (dir),  Up: (dir)

SLIB
****

This manual is for SLIB (version 3b1, February 2008), the portable            |
Scheme library.

Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
2002, 2003, 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.       |

     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, no Front-Cover Texts, and
     no Back-Cover Texts.  A copy of the license is included in the
     section entitled "GNU Free Documentation License."

* 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::


File: slib.info,  Node: The Library System,  Next: Universal SLIB Procedures,  Prev: Top,  Up: Top

1 The Library System
********************

"SLIB" is a portable library for the programming language "Scheme".  It
provides a platform independent framework for using "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::


File: slib.info,  Node: Feature,  Next: Require,  Prev: The Library System,  Up: The Library System

1.1 Feature
===========

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

   * 'inexact

   * 'rational

   * 'real

   * 'complex

   * 'bignum

SLIB initialization (in `require.scm') tests and "provide"s any of
these numeric features which are appropriate.

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

 -- Function: provided? feature
     Returns `#t' if FEATURE is present in the current Scheme session;
     otherwise `#f'.  More specifically, `provided?' returns `#t' if
     the symbol FEATURE is the `software-type', the
     `scheme-implementation-type' (1), or if FEATURE has been provided
     by a module already loaded; and `#f' otherwise.

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

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

     The FEATURE argument can also be an expression calling `and',
     `or', and `not' of features.  The boolean result of the logical
     question asked by FEATURE is returned.

The generalization of `provided?' for arbitrary features and catalog is
`feature-eval':

 -- Function: feature-eval expression provided?
     Evaluates `and', `or', and `not' forms in EXPRESSION, using the
     values returned by calling PROVIDED?  on the leaf symbols.
     `feature-eval' returns the boolean result of the logical
     combinations.

 -- Procedure: provide feature
     Informs SLIB that FEATURE is supported in this session.

     (provided? 'foo)    => #f
     (provide 'foo)
     (provided? 'foo)    => #t

  ---------- Footnotes ----------

  (1) scheme-implementation-type is the name symbol of the running
Scheme implementation (RScheme, |STk|, Bigloo, chez, Elk, gambit,
guile, JScheme, kawa, MacScheme, MITScheme, Pocket-Scheme, Scheme48,
Scheme->C, Scheme48, Scsh, SISC, T, umb-scheme, or Vscm).  Dependence on
scheme-implementation-type is almost always the wrong way to do things.


File: slib.info,  Node: Require,  Next: Library Catalogs,  Prev: Feature,  Up: The Library System

1.2 Require
===========

SLIB creates and maintains a "catalog" mapping features to locations of
files introducing procedures and syntax denoted by those features.

 -- Variable: *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, `source', `compiled', or one of the other
     cases described in *Note Library Catalogs::.  The cdr of the
     pathname should be either a string or a list.

At the beginning of each section of this manual, there is a line like
`(require 'FEATURE)'.  The Scheme files comprising SLIB are cataloged
so that these feature names map to the corresponding files.

SLIB provides a form, `require', which loads the files providing the
requested feature.

 -- Procedure: require feature
        * If `(provided? FEATURE)' is true, then `require' just returns.

        * Otherwise, if FEATURE is found in the catalog, then the
          corresponding files will be loaded and `(provided?  FEATURE)'
          will henceforth return `#t'.  That FEATURE is thereafter
          `provided'.

        * Otherwise (FEATURE not found in the catalog), an error is
          signaled.

There is a related form `require-if', used primarily for enabling
compilers to statically include modules which would be dynamically
loaded by interpreters.

 -- Procedure: require-if condition feature
     Requires FEATURE if CONDITION is true.

The `random' module uses `require-if' to flag `object->string' as a
(dynamic) required module.

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

The `batch' module uses `require-if' to flag `posix-time' as a module
to load if the implementation supports large precision exact integers.

     (require-if '(and bignum compiling) 'posix-time)

The catalog can also be queried using `slib:in-catalog?'.

 -- Function: slib:in-catalog? feature
     Returns a `CDR' of the catalog entry if one was found for the
     symbol FEATURE in the alist `*catalog*' (and transitively through
     any symbol aliases encountered).  Otherwise, returns `#f'.  The
     format of catalog entries is explained in *Note Library Catalogs::.


File: slib.info,  Node: Library Catalogs,  Next: Catalog Creation,  Prev: Require,  Up: The Library System

1.3 Library Catalogs
====================

Catalog files consist of one or more "association list"s.  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:

`(FEATURE . <symbol>)'
     Redirects to the feature named <symbol>.

`(FEATURE . "<path>")'
     Loads file <path>.

`(FEATURE source "<path>")'
     `slib:load's the Scheme source file <path>.

`(FEATURE compiled "<path>" ...)'
     `slib:load-compiled's the files <path> ....

`(FEATURE aggregate <symbol> ...)'
     `require's the features <symbol> ....

The various macro styles first `require' the named macro package, then
just load <path> or load-and-macro-expand <path> as appropriate for the
implementation.

`(FEATURE defmacro "<path>")'
     `defmacro:load's the Scheme source file <path>.

`(FEATURE macro-by-example "<path>")'
     `defmacro:load's the Scheme source file <path>.

`(FEATURE macro "<path>")'
     `macro:load's the Scheme source file <path>.

`(FEATURE macros-that-work "<path>")'
     `macro:load's the Scheme source file <path>.

`(FEATURE syntax-case "<path>")'
     `macro:load's the Scheme source file <path>.

`(FEATURE syntactic-closures "<path>")'
     `macro:load's the Scheme source file <path>.


File: slib.info,  Node: Catalog Creation,  Next: Catalog Vicinities,  Prev: Library Catalogs,  Up: The Library System

1.4 Catalog Creation
====================

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

   * standard SLIB packages.

   * additional packages of interest to this site.

   * packages specifically for the variety of Scheme which this session
     is running.

   * packages this user wants to always have available.  This catalog
     is the file `homecat' in the user's "HOME" directory.  

   * packages germane to working in this (current working) directory.
     This catalog is the file `usercat' in the directory to which it
     applies.  One would typically `cd' to this directory before
     starting the Scheme session.

   * packages which are part of an application program.

SLIB combines the catalog information which doesn't vary per user into
the file `slibcat' in the implementation-vicinity.  Therefore `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.

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

The compilation scripts of Scheme implementations which work with SLIB
can automatically trigger catalog compilation by deleting `slibcat' or
by invoking `require' of a special feature:

 -- Procedure: require 'new-catalog
     This will load `mklibcat', which compiles and writes a new
     `slibcat'.

Another special feature of `require' erases SLIB's catalog, forcing it
to be reloaded the next time the catalog is queried.

 -- Procedure: require #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.


File: slib.info,  Node: Catalog Vicinities,  Next: Compiling Scheme,  Prev: Catalog Creation,  Up: The Library System

1.5 Catalog Vicinities
======================

Each file in the table below is descibed in terms of its file-system
independent "vicinity" (*note Vicinity::).  The entries of a catalog in
the table override those of catalogs above it in the table.

`implementation-vicinity' `slibcat'
     This file contains the associations for the packages comprising
     SLIB, the `implcat' and the `sitecat's.  The associations in the
     other catalogs override those of the standard catalog.

`library-vicinity' `mklibcat.scm'
     creates `slibcat'.

`library-vicinity' `sitecat'
     This file contains the associations specific to an SLIB
     installation.

`implementation-vicinity' `implcat'
     This file contains the associations specific to an implementation
     of Scheme.  Different implementations of Scheme should have
     different `implementation-vicinity'.

`implementation-vicinity' `mkimpcat.scm'
     if present, creates `implcat'.

`implementation-vicinity' `sitecat'
     This file contains the associations specific to a Scheme
     implementation installation.

`home-vicinity' `homecat'
     This file contains the associations specific to an SLIB user.

`user-vicinity' `usercat'
     This file contains associations affecting only those sessions whose
     "working directory" is `user-vicinity'.


Here is an example of a `usercat' catalog.  A program in this directory
can invoke the `run' feature with `(require 'run)'.

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

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

 -- Procedure: catalog:read vicinity catalog
     Reads file named by string CATALOG in VICINITY, resolving all
     paths relative to VICINITY, and adds those feature associations to
     *CATALOG*.

     `catalog:read' would typically be used by an application program
     having dynamically loadable modules.  For instance, to register
     factoring and other modules in *CATALOG*, JACAL does:

          (catalog:read (program-vicinity) "jacalcat")


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

   * in a `usercat' file in the directory where the program runs; or

   * in an `implcat' file in the `implementation-vicinity'; or

   * in an application program directory; loaded by calling
     `catalog:read'.


File: slib.info,  Node: Compiling Scheme,  Prev: Catalog Vicinities,  Up: The Library System

1.6 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::


File: slib.info,  Node: Module Conventions,  Next: Module Manifests,  Prev: Compiling Scheme,  Up: Compiling Scheme

1.6.1 Module Conventions
------------------------

   * All the top-level `require' commands have one quoted argument and
     are positioned before other Scheme definitions and expressions in
     the file.

   * Any conditionally `require'd SLIB modules (1) also appear at the
     beginning of their files conditioned on the feature `compiling'
     using `require-if' (*note require-if: Require.).

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

   * Schmooz-style comments preceding a definition, identify that
     definition as an exported identifier (*note Schmooz::).  For
     non-schmooz files, putting `;@' at the beginning of the line
     immediately preceding the definition (`define', `define-syntax',
     or `defmacro') suffices.

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

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

   * 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:

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


  ---------- Footnotes ----------

  (1) There are some functions with internal `require' calls to delay
loading modules until they are needed.  While this reduces startup
latency for interpreters, it can produce headaches for compilers.


File: slib.info,  Node: Module Manifests,  Next: Module Semantics,  Prev: Module Conventions,  Up: Compiling Scheme

1.6.2 Module Manifests
----------------------

`(require 'manifest)' 

In some of these examples, SLIB:CATALOG is the SLIB part of the
catalog; it is free of compiled and implementation-specific entries.
It would be defined by:

     (define slib:catalog (cdr (member (assq 'null *catalog*) *catalog*)))

 -- Function: file->requires file provided? catalog
     Returns a list of the features `require'd by FILE assuming the
     predicate PROVIDED? and association-list CATALOG.

     (define (provided+? . features)
       (lambda (feature)
         (or (memq feature features) (provided? feature))))

     (file->requires "obj2str.scm" (provided+? 'compiling) '())
             => (string-port generic-write)

     (file->requires "obj2str.scm" provided? '())
             => (string-port)

 -- Function: feature->requires feature provided? catalog
     Returns a list of the features `require'd by FEATURE assuming the
     predicate PROVIDED? and association-list CATALOG.

     (feature->requires 'batch (provided+? 'compiling) *catalog*)
             => (tree line-i/o databases parameters string-port
                        pretty-print common-list-functions posix-time)

     (feature->requires 'batch provided? *catalog*)
             => (tree line-i/o databases parameters string-port
                        pretty-print common-list-functions)

     (feature->requires 'batch provided? '((batch . "batch")))
             => (tree line-i/o databases parameters string-port
                        pretty-print common-list-functions)

 -- Function: feature->requires* feature provided? catalog
     Returns a list of the features transitively `require'd by FEATURE
     assuming the predicate PROVIDED? and association-list CATALOG.

 -- Function: file->requires* file provided? catalog
     Returns a list of the features transitively `require'd by FILE
     assuming the predicate PROVIDED? and association-list CATALOG.

 -- Function: file->loads file
     Returns a list of strings naming existing files loaded (load
     slib:load slib:load-source macro:load defmacro:load syncase:load
     synclo:load macwork:load) by FILE or any of the files it loads.

     (file->loads (in-vicinity (library-vicinity) "scainit.scm"))
             => ("/usr/local/lib/slib/scaexpp.scm"
                 "/usr/local/lib/slib/scaglob.scm"
                 "/usr/local/lib/slib/scaoutp.scm")

 -- Function: load->path exp
     Given a `(load '<expr>)', where <expr> is a string or vicinity
     stuff), `(load->path <expr>)' figures a path to the file.
     `load->path' returns that path if it names an existing file;
     otherwise #f.

     (load->path '(in-vicinity (library-vicinity) "mklibcat"))
             => "/usr/local/lib/slib/mklibcat.scm"

 -- Function: file->definitions file definer ...
     Returns a list of the identifier symbols defined by SLIB (or
     SLIB-style) file FILE.  The optional arguments DEFINERS should be
     symbols signifying a defining form.  If none are supplied, then
     the symbols `define-operation', `define', `define-syntax', and
     `defmacro' are captured.

     (file->definitions "random.scm")
             => (*random-state* make-random-state
                seed->random-state copy-random-state random
                random:chunk)

 -- Function: file->exports file definer ...
     Returns a list of the identifier symbols exported (advertised) by
     SLIB (or SLIB-style) file FILE.  The optional arguments DEFINERS
     should be symbols signifying a defining form.  If none are
     supplied, then the symbols `define-operation', `define',
     `define-syntax', and `defmacro' are captured.

     (file->exports "random.scm")
             => (make-random-state seed->random-state
                 copy-random-state random)

     (file->exports "randinex.scm")
             => (random:solid-sphere! random:hollow-sphere!
                 random:normal-vector! random:normal
                 random:exp random:uniform)

 -- Function: feature->export-alist feature catalog
     Returns a list of lists; each sublist holding the name of the file
     implementing FEATURE, and the identifier symbols exported
     (advertised) by SLIB (or SLIB-style) feature FEATURE, in CATALOG.

 -- Function: feature->exports feature catalog
     Returns a list of all exports of FEATURE.

In the case of `aggregate' features, more than one file may have export
lists to report:

     (feature->export-alist 'r5rs slib:catalog))
             => (("/usr/local/lib/slib/values.scm"
                  call-with-values values)
                 ("/usr/local/lib/slib/mbe.scm"
                  define-syntax macro:expand
                  macro:load macro:eval)
                 ("/usr/local/lib/slib/eval.scm"
                  eval scheme-report-environment
                  null-environment interaction-environment))

     (feature->export-alist 'stdio *catalog*)
             => (("/usr/local/lib/slib/scanf.scm"
                  fscanf sscanf scanf scanf-read-list)
                 ("/usr/local/lib/slib/printf.scm"
                  sprintf printf fprintf)
                 ("/usr/local/lib/slib/stdio.scm"
                  stderr stdout stdin))

     (feature->exports 'stdio slib:catalog)
             => (fscanf sscanf scanf scanf-read-list
                  sprintf printf fprintf stderr stdout stdin)


File: slib.info,  Node: Module Semantics,  Next: Top-level Variable References,  Prev: Module Manifests,  Up: Compiling Scheme

1.6.3 Module Semantics
----------------------

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

  Top-level occurrences of `require-if' make defined the exports from
the module named by the second argument _if_ the FEATURE-EXPRESSION
first argument is true in the target environment.  The target feature
`compiling' should be provided during this phase of compilation.

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

  Note that aggregate catalog entries import more than one module.
Implementations of `require' may or may _not_ be transitive; code which
uses module exports without requiring the providing module is in error.

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

  In all cases these `provided?' tests can be evaluated at compile-time
using `feature-eval' (*note feature-eval: Feature.).  The simplest way
to compile these constructs may be to treat `provided?' as a macro.


File: slib.info,  Node: Top-level Variable References,  Next: Module Analysis,  Prev: Module Semantics,  Up: Compiling Scheme

1.6.4 Top-level Variable References
-----------------------------------

`(require 'top-refs)' 

These procedures complement those in *Note Module Manifests:: by
finding the top-level variable references in Scheme source code.  They
work by traversing expressions and definitions, keeping track of
bindings encountered.  It is certainly possible to foil these
functions, but they return useful information about SLIB source code.

 -- Function: top-refs obj
     Returns a list of the top-level variables referenced by the Scheme
     expression OBJ.

 -- Function: top-refs<-file filename
     FILENAME should be a string naming an existing file containing
     Scheme source code.  `top-refs<-file' returns a list of the
     top-level variable references made by expressions in the file
     named by FILENAME.

     Code in modules which FILENAME `require's is not traversed.  Code
     in files loaded from top-level _is_ traversed if the expression
     argument to `load', `slib:load', `slib:load-source', `macro:load',
     `defmacro:load', `synclo:load', `syncase:load', or `macwork:load'
     is a literal string constant or composed of combinations of
     vicinity functions and string literal constants; and the resulting
     file exists (possibly with ".scm" appended).

The following function parses an "Info" Index.  (1)

 -- Function: exports<-info-index file n ...
     N ... must be an increasing series of positive integers.
     `exports<-info-index' returns a list of all the identifiers
     appearing in the Nth ... (info) indexes of FILE.  The identifiers
     have the case that the implementation's `read' uses for symbols.
     Identifiers containing spaces (eg. `close-base on base-table') are
     _not_ included.  #f is returned if the index is not found.

     Each info index is headed by a `* Menu:' line.  To list the
     symbols in the first and third info indexes do:

          (exports<-info-index "slib.info" 1 3)

  ---------- Footnotes ----------

  (1) Although it will work on large info files, feeding it an excerpt
is much faster; and has less chance of being confused by unusual text
in the info file.  This command excerpts the SLIB index into
`slib-index.info':

     info -f slib2d6.info -n "Index" -o slib-index.info


File: slib.info,  Node: Module Analysis,  Prev: Top-level Variable References,  Up: Compiling Scheme

1.6.5 Module Analysis
---------------------

`(require 'vet)' 

 -- Function: vet-slib file1 ...
     Using the procedures in the `top-refs' and `manifest' modules,
     `vet-slib' analyzes each SLIB module and FILE1, ..., reporting
     about any procedure or macro defined whether it is:

    orphaned
          defined, not called, not exported;

    missing
          called, not defined, and not exported by its `require'd
          modules;

    undocumented-export
          Exported by module, but no index entry in `slib.info';


     And for the library as a whole:

    documented-unexport
          Index entry in `slib.info', but no module exports it.


     This straightforward analysis caught three full days worth of
     never-executed branches, transitive require assumptions, spelling
     errors, undocumented procedures, missing procedures, and cyclic
     dependencies in SLIB.

     The optional arguments FILE1, ... provide a simple way to vet
     prospective SLIB modules.


File: slib.info,  Node: Universal SLIB Procedures,  Next: Scheme Syntax Extension Packages,  Prev: The Library System,  Up: Top

2 Universal SLIB Procedures
***************************

The procedures described in these sections are supported by all
implementations as part of the `*.init' files or by `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::


File: slib.info,  Node: Vicinity,  Next: Configuration,  Prev: Universal SLIB Procedures,  Up: Universal SLIB Procedures

2.1 Vicinity
============

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 "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 _in_dependent.

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

 -- Function: make-vicinity dirpath
     Returns DIRPATH as a vicinity for use as first argument to
     `in-vicinity'.

 -- Function: pathname->vicinity path
     Returns the vicinity containing PATH.
          (pathname->vicinity "/usr/local/lib/scm/Link.scm")
                              => "/usr/local/lib/scm/"

 -- Function: 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.  *Warning:*
     `program-vicinity' can return incorrect values if your program
     escapes back into a `load' continuation.

 -- Function: library-vicinity
     Returns the vicinity of the shared Scheme library.

 -- Function: implementation-vicinity
     Returns the vicinity of the underlying Scheme implementation.  This
     vicinity will likely contain startup code and messages and a
     compiler.

 -- Function: user-vicinity
     Returns the vicinity of the current directory of the user.  On most
     systems this is `""' (the empty string).

 -- Function: home-vicinity
     Returns the vicinity of the user's "HOME" directory, the directory 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
     `home-vicinity' returns `#f'.

 -- Function: vicinity:suffix? chr
     Returns the `#t' if CHR is a vicinity suffix character; and `#f'
     otherwise.  Typical vicinity suffixes are `/', `:', and `\',

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

 -- Function: sub-vicinity vicinity name
     Returns the vicinity of VICINITY restricted to NAME.  This is used
     for large systems where names of files in subsystems could
     conflict.  On systems with directory structure `sub-vicinity' will
     return a pathname of the subdirectory NAME of VICINITY.

 -- Function: with-load-pathname path thunk
     PATH should be a string naming a file being read or loaded.
     `with-load-pathname' evaluates THUNK in a dynamic scope where an
     internal variable is bound to PATH; the internal variable is used
     for messages and `program-vicinity'.  `with-load-pathname' returns
     the value returned by THUNK.


File: slib.info,  Node: Configuration,  Next: Input/Output,  Prev: Vicinity,  Up: Universal SLIB Procedures

2.2 Configuration
=================

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

 -- Constant: char-code-limit
     An integer 1 larger that the largest value which can be returned by
     `char->integer'.

 -- Constant: most-positive-fixnum
     In implementations which support integers of practically unlimited
     size, 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, MOST-POSITIVE-FIXNUM is the largest exact integer
     that may result from computing the length of a list, vector, or
     string.

 -- Constant: slib:tab
     The tab character.

 -- Constant: slib:form-feed
     The form-feed character.

 -- Function: software-type
     Returns a symbol denoting the generic operating system type.  For
     instance, `unix', `vms', `macos', `amiga', or `ms-dos'.

 -- Function: 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.

          (slib:report-version) => slib "3b1" on scm "5b1" on unix            |

 -- Function: slib:report
     Displays the information of `(slib:report-version)' followed by
     almost all the information neccessary for submitting a problem
     report.  An unspecified value is returned.

 -- Function: slib:report #t
     provides a more verbose listing.

 -- Function: slib:report filename
     Writes the report to file `filename'.

          (slib:report)
          =>
          slib "3b1" 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")
                  ...


File: slib.info,  Node: Input/Output,  Next: System,  Prev: Configuration,  Up: Universal SLIB Procedures

2.3 Input/Output
================

These procedures are provided by all implementations.

 -- Function: file-exists? filename
     Returns `#t' if the specified file exists.  Otherwise, returns
     `#f'.  If the underlying implementation does not support this
     feature then `#f' is always returned.

 -- Function: delete-file filename
     Deletes the file specified by FILENAME.  If FILENAME can not be
     deleted, `#f' is returned.  Otherwise, `#t' is returned.

 -- Function: open-file filename modes
     FILENAME should be a string naming a file.  `open-file' returns a
     port depending on the symbol MODES:

    r
          an input port capable of delivering characters from the file.

    rb
          a _binary_ input port capable of delivering characters from
          the file.

    w
          an output port capable of writing characters to a new file by
          that name.

    wb
          a _binary_ output port capable of writing characters to a new
          file by that name.

     If an implementation does not distinguish between binary and
     non-binary files, then it must treat rb as r and wb as 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.

 -- Function: port? obj
     Returns #t if OBJ is an input or output port, otherwise returns #f.

 -- Procedure: close-port port
     Closes the file associated with PORT, rendering the PORT incapable
     of delivering or accepting characters.

     `close-file' has no effect if the file has already been closed.
     The value returned is unspecified.

 -- Function: call-with-open-ports proc ports ...
 -- Function: call-with-open-ports ports ... proc
     PROC should be a procedure that accepts as many arguments as there
     are PORTS passed to `call-with-open-ports'.
     `call-with-open-ports' calls PROC with PORTS ....  If PROC
     returns, then the ports are closed automatically and the value
     yielded by the PROC is returned.  If 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.

 -- Function: tmpnam
     Returns a pathname for a file which will likely not be used by any
     other process.  Successive calls to `(tmpnam)' will return
     different pathnames.

 -- Function: current-error-port
     Returns the current port to which diagnostic and error output is
     directed.

 -- Procedure: force-output
 -- Procedure: force-output port
     Forces any pending output on PORT to be delivered to the output
     device and returns an unspecified value.  The PORT argument may be
     omitted, in which case it defaults to the value returned by
     `(current-output-port)'.

 -- Function: file-position port
 -- Function: file-position port #f
     PORT must be open to a file.  `file-position' returns the current
     position of the character in PORT which will next be read or
     written.  If the implementation does not support file-position,
     then `#f' is returned.

 -- Function: file-position port k
     PORT must be open to a file.  `file-position' sets the current
     position in PORT which will next be read or written.  If
     successful, `#f' is returned; otherwise `file-position' returns
     `#f'.

 -- Function: output-port-width
 -- Function: output-port-width port
     Returns the width of PORT, which defaults to
     `(current-output-port)' if absent.  If the width cannot be
     determined 79 is returned.

 -- Function: output-port-height
 -- Function: output-port-height port
     Returns the height of PORT, which defaults to
     `(current-output-port)' if absent.  If the height cannot be
     determined 24 is returned.


File: slib.info,  Node: System,  Next: Miscellany,  Prev: Input/Output,  Up: Universal SLIB Procedures

2.4 System
==========

These procedures are provided by all implementations.

 -- Procedure: slib:load-source name
     Loads a file of Scheme source code from NAME with the default
     filename extension used in SLIB.  For instance if the filename
     extension used in SLIB is `.scm' then `(slib:load-source "foo")'
     will load from file `foo.scm'.

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

 -- Procedure: slib:load name
     Loads a file of Scheme source or compiled code from 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
     `slib:load' will be identical to `slib:load-source'.

 -- Procedure: slib:eval obj
     `eval' returns the value of OBJ evaluated in the current top level
     environment.  *Note Eval:: provides a more general evaluation
     facility.

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

 -- Procedure: slib:warn arg1 arg2 ...
     Outputs a warning message containing the arguments.

 -- Procedure: slib:error arg1 arg2 ...
     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.

 -- Procedure: slib:exit n
 -- Procedure: slib:exit
     Exits from the Scheme session returning status N to the system.
     If N is omitted or `#t', a success status is returned to the
     system (if possible).  If N is `#f' a failure is returned to the
     system (if possible).  If N is an integer, then N is returned to
     the system (if possible).  If the Scheme session cannot exit, then
     an unspecified value is returned from `slib:exit'.

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

     If a browser is running, `browse-url' causes the browser to
     display the page specified by string URL and returns `#t'.

     If the browser is not running, `browse-url' starts a browser
     displaying the argument URL.  If the browser starts as a
     background job, `browse-url' returns `#t' immediately; if the
     browser starts as a foreground job, then `browse-url' returns `#t'
     when the browser exits; otherwise (if no browser) it returns `#f'.


File: slib.info,  Node: Miscellany,  Prev: System,  Up: Universal SLIB Procedures

2.5 Miscellany
==============

These procedures are provided by all implementations.

 -- Function: identity x
     IDENTITY returns its argument.

     Example:
          (identity 3)
             => 3
          (identity '(foo bar))
             => (foo bar)
          (map identity LST)
             == (copy-list LST)

2.5.1 Mutual Exclusion
----------------------

An "exchanger" is a procedure of one argument regulating mutually 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.

 -- Function: make-exchanger obj
     Returns a new exchanger with the argument OBJ as its initial
     content.

          (define queue (make-exchanger (list a)))

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

          (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)         => a

          (pop queue)         => #f

2.5.2 Legacy
------------

The following procedures were present in Scheme until R4RS (*note
Language changes: (r4rs)Notes.).  They are provided by all SLIB
implementations.

 -- Constant: t
     Defined as `#t'.

 -- Constant: nil
     Defined as `#f'.

 -- Function: last-pair l
     Returns the last pair in the list L.  Example:
          (last-pair (cons 1 2))
             => (1 . 2)
          (last-pair '(1 2))
             => (2)
              == (cons 2 '())


File: slib.info,  Node: Scheme Syntax Extension Packages,  Next: Textual Conversion Packages,  Prev: Universal SLIB Procedures,  Up: Top

3 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


File: slib.info,  Node: Defmacro,  Next: R4RS Macros,  Prev: Scheme Syntax Extension Packages,  Up: Scheme Syntax Extension Packages

3.1 Defmacro
============

Defmacros are supported by all implementations.

 -- Function: gentemp
     Returns a new (interned) symbol each time it is called.  The symbol
     names are implementation-dependent
          (gentemp) => scm:G0
          (gentemp) => scm:G1

 -- Function: defmacro:eval e
     Returns the `slib:eval' of expanding all defmacros in scheme
     expression E.

 -- Function: defmacro:load filename
     FILENAME should be a string.  If filename names an existing file,
     the `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 `macro:load' procedure does not affect the values
     returned by `current-input-port' and `current-output-port'.

 -- Function: defmacro? sym
     Returns `#t' if SYM has been defined by `defmacro', `#f' otherwise.

 -- Function: macroexpand-1 form
 -- Function: macroexpand form
     If FORM is a macro call, `macroexpand-1' will expand the macro
     call once and return it.  A FORM is considered to be a macro call
     only if it is a cons whose `car' is a symbol for which a
     `defmacro' has been defined.

     `macroexpand' is similar to `macroexpand-1', but repeatedly
     expands FORM until it is no longer a macro call.

 -- Macro: defmacro name lambda-list form ...
     When encountered by `defmacro:eval', `defmacro:macroexpand*', or
     `defmacro:load' defines a new macro which will henceforth be
     expanded when encountered by `defmacro:eval',
     `defmacro:macroexpand*', or `defmacro:load'.

3.1.1 Defmacroexpand
--------------------

`(require 'defmacroexpand)' 

 -- Function: defmacro:expand* e
     Returns the result of expanding all defmacros in scheme expression
     E.


File: slib.info,  Node: R4RS Macros,  Next: Macro by Example,  Prev: Defmacro,  Up: Scheme Syntax Extension Packages

3.2 R4RS Macros
===============

`(require 'macro)' is the appropriate call if you want R4RS 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:

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

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

 -- Procedure: macro:load filename
     FILENAME should be a string.  If filename names an existing file,
     the `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 `macro:load' procedure does not affect the
     values returned by `current-input-port' and `current-output-port'.


File: slib.info,  Node: Macro by Example,  Next: Macros That Work,  Prev: R4RS Macros,  Up: Scheme Syntax Extension Packages

3.3 Macro by Example
====================

`(require 'macro-by-example)' 

  A vanilla implementation of `Macro by Example' (Eugene Kohlbecker,
R4RS) by Dorai Sitaram, (dorai @ cs.rice.edu) using `defmacro'.

   * generating hygienic global `define-syntax' Macro-by-Example macros
     *cheaply*.

   * can define macros which use `...'.

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

   * don't suffer the overhead of redefining the repl if `defmacro'
     natively supported (most implementations)


3.3.1 Caveat
------------

These macros are not referentially transparent (*note Macros:
(r4rs)Macros.).  Lexically scoped macros (i.e., `let-syntax' and
`letrec-syntax') are not supported.  In any case, the problem of
referential transparency gains poignancy only when `let-syntax' and
`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 `r4rs' macro functionality, look to the more
featureful (but also more expensive) versions of syntax-rules available
in slib *Note Macros That Work::, *Note Syntactic Closures::, and *Note
Syntax-Case Macros::.

 -- Macro: define-syntax keyword transformer-spec
     The KEYWORD is an identifier, and the TRANSFORMER-SPEC should be
     an instance of `syntax-rules'.

     The top-level syntactic environment is extended by binding the
     KEYWORD to the specified transformer.

          (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 ...)))))

 -- Macro: syntax-rules literals syntax-rule ...
     LITERALS is a list of identifiers, and each SYNTAX-RULE should be
     of the form

     `(PATTERN TEMPLATE)'

     where the PATTERN and  TEMPLATE are as in the grammar above.

     An instance of `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
     `syntax-rules' is matched against the patterns contained in the
     SYNTAX-RULEs, beginning with the leftmost 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.


File: slib.info,  Node: Macros That Work,  Next: Syntactic Closures,  Prev: Macro by Example,  Up: Scheme Syntax Extension Packages

3.4 Macros That Work
====================

`(require 'macros-that-work)' 

  `Macros That Work' differs from the other R4RS macro implementations
in that it does not expand derived expression types to primitive
expression types.

 -- Function: macro:expand expression
 -- Function: macwork:expand expression
     Takes an R4RS expression, macro-expands it, and returns the result
     of the macro expansion.

 -- Function: macro:eval expression
 -- Function: macwork:eval expression
     `macro:eval' returns the value of EXPRESSION in the current top
     level environment.  EXPRESSION can contain macro definitions.
     Side effects of EXPRESSION will affect the top level environment.

 -- Procedure: macro:load filename
 -- Procedure: macwork:load filename
     FILENAME should be a string.  If filename names an existing file,
     the `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 `macro:load' procedure does not affect the
     values returned by `current-input-port' and `current-output-port'.

  References:

  The `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.

            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.

     transformer spec  ==>  (syntax-rules literals rules)

     rules  ==>  ()
              |  (rule . rules)

     rule  ==>  (pattern template)

     pattern  ==>  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  ==>  pattern_var
                 |  symbol
                 |  ()
                 |  (template2 . template2)
                 |  #(template*)                   ; extends R4RS
                 |  pattern_datum

     template2  ==>  template
                  |  ellipsis_template

     pattern_datum  ==>  string                    ; no vector
                      |  character
                      |  boolean
                      |  number

     ellipsis_pattern  ==> pattern ...

     ellipsis_template  ==>  template ...

     pattern_var  ==>  symbol   ; not in literals

     literals  ==>  ()
                 |  (symbol . literals)

3.4.1 Definitions
-----------------

Scope of an ellipsis
     Within a pattern or template, the scope of an ellipsis (`...') is
     the pattern or template that appears to its left.

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

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

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.

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

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

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.


3.4.2 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 RULE is

     rule  ==>  (pattern template inserted)

     pattern  ==>  pattern_var
                |  symbol
                |  ()
                |  (pattern . pattern)
                |  ellipsis_pattern
                |  #(pattern)
                |  pattern_datum

     template  ==>  pattern_var
                 |  symbol
                 |  ()
                 |  (template2 . template2)
                 |  #(pattern)
                 |  pattern_datum

     template2  ==>  template
                  |  ellipsis_template

     pattern_datum  ==>  string
                      |  character
                      |  boolean
                      |  number

     pattern_var  ==>  #(V symbol rank)

     ellipsis_pattern  ==>  #(E pattern pattern_vars)

     ellipsis_template  ==>  #(E template pattern_vars)

     inserted  ==>  ()
                 |  (symbol . inserted)

     pattern_vars  ==>  ()
                     |  (pattern_var . pattern_vars)

     rank  ==>  exact non-negative integer

  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.


File: slib.info,  Node: Syntactic Closures,  Next: Syntax-Case Macros,  Prev: Macros That Work,  Up: Scheme Syntax Extension Packages

3.5 Syntactic Closures
======================

`(require 'syntactic-closures)' 

 -- Function: macro:expand expression
 -- Function: synclo:expand expression
     Returns scheme code with the macros and derived expression types of
     EXPRESSION expanded to primitive expression types.

 -- Function: macro:eval expression
 -- Function: synclo:eval expression
     `macro:eval' returns the value of EXPRESSION in the current top
     level environment.  EXPRESSION can contain macro definitions.
     Side effects of EXPRESSION will affect the top level environment.

 -- Procedure: macro:load filename
 -- Procedure: synclo:load filename
     FILENAME should be a string.  If filename names an existing file,
     the `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 `macro:load' procedure does not affect the
     values returned by `current-input-port' and `current-output-port'.

3.5.1 Syntactic Closure Macro Facility
--------------------------------------

                  A Syntactic Closures Macro Facility
                            by Chris Hanson
                            9 November 1991

  This document describes "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 `Revised^4
Report on Scheme.' This document is an addendum to that report.

  The syntactic closures facility extends the BNF rule for TRANSFORMER
SPEC to allow a new keyword that introduces a low-level macro
transformer:

     TRANSFORMER SPEC := (transformer EXPRESSION)

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

  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
"identifiers", which extend the syntactic closure mechanism to be
compatible with `syntax-rules'.

3.5.1.1 Terminology
...................

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

   * "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 `set!' special form is also a
     form.  Examples of forms:

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

   * An "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 `symbol?'.  Macro transformers rarely distinguish
     symbols from aliases, referring to both as identifiers.

   * A "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.

   * A "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.


3.5.1.2 Transformer Definition
..............................

This section describes the `transformer' special form and the
procedures `make-syntactic-closure' and `capture-syntactic-environment'.

 -- Syntax: transformer expression
     Syntax: It is an error if this syntax occurs except as a
     TRANSFORMER SPEC.

     Semantics: The 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 `transformer' expression appears (for example,
     `let-syntax').

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

     For example, here is a definition of a push macro using
     `syntax-rules':

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

     Here is an equivalent definition using `transformer':
          (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))))))

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

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

          (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))))))))

     To assign meanings to the identifiers in a form, use
     `make-syntactic-closure' to close the form in a syntactic
     environment.

 -- Function: make-syntactic-closure environment free-names form
     ENVIRONMENT must be a syntactic environment, FREE-NAMES must be a
     list of identifiers, and FORM must be a form.
     `make-syntactic-closure' constructs and returns a syntactic closure
     of FORM in ENVIRONMENT, which can be used anywhere that FORM could
     have been used.  All the identifiers used in FORM, except those
     explicitly excepted by FREE-NAMES, obtain their meanings from
     ENVIRONMENT.

     Here is an example where FREE-NAMES is something other than the
     empty list.  It is instructive to compare the use of FREE-NAMES in
     this example with its use in the `loop' example above: the examples
     are similar except for the source of the identifier being left
     free.
          (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))))))

     `let1' is a simplified version of `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
     `let1' must be left free, so that it can be properly captured by
     the `lambda' in the output form.

     To obtain a syntactic environment other than the usage
     environment, use `capture-syntactic-environment'.

 -- Function: capture-syntactic-environment procedure
     `capture-syntactic-environment' returns a form that will, when
     transformed, call PROCEDURE on the current syntactic environment.
     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 `loop-until' keyword equivalent to

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

     The following attempt at defining `loop-until' has a subtle bug:
          (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 '())))))))

     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 `id' identifier free in the `test', `return', and
     `step' expressions, so that it will be captured by the binding
     introduced by the `lambda' expression.  Unfortunately it uses the
     identifiers `if' and `loop' within that `lambda' expression, so if
     the user of `loop-until' just happens to use, say, `if' for the
     identifier, it will be inadvertently captured.

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

          (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 '())))))))

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

     A common use of `capture-syntactic-environment' is to get the
     transformer environment of a macro transformer:

          (transformer
           (lambda (exp env)
             (capture-syntactic-environment
              (lambda (transformer-env)
                ...))))

3.5.1.3 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 `syntax-rules' facility.

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

     (make-syntactic-closure env '() 'a)
        => an "alias"

  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 `lambda' or
`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
`syntax-rules'.  A macro transformer created by `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.

 -- Function: identifier? object
     Returns `#t' if OBJECT is an identifier, otherwise returns `#f'.
     Examples:

          (identifier? 'a)
             => #t
          (identifier? (make-syntactic-closure env '() 'a))
             => #t
          (identifier? "a")
             => #f
          (identifier? #\a)
             => #f
          (identifier? 97)
             => #f
          (identifier? #f)
             => #f
          (identifier? '(a))
             => #f
          (identifier? '#(a))
             => #f

     The predicate `eq?' is used to determine if two identifers are
     "the same".  Thus `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 `cond' macro uses the symbol `else' to identify the
     final clause in the conditional.  A macro transformer for `cond'
     cannot just look for the symbol `else', because the `cond' form
     might be the output of another macro transformer that replaced the
     symbol `else' with an alias.  Instead the transformer must look
     for an identifier that "means the same thing" in the usage
     environment as the symbol `else' means in the transformer
     environment.

 -- Function: identifier=? environment1 identifier1 environment2
          identifier2
     ENVIRONMENT1 and ENVIRONMENT2 must be syntactic environments, and
     IDENTIFIER1 and IDENTIFIER2 must be identifiers.  `identifier=?'
     returns `#t' if the meaning of IDENTIFIER1 in ENVIRONMENT1 is the
     same as that of IDENTIFIER2 in ENVIRONMENT2, otherwise it returns
     `#f'.  Examples:

          (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))))
             => (#t #f)

          (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))))
             => (#f #t)

3.5.1.4 Acknowledgements
........................

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


File: slib.info,  Node: Syntax-Case Macros,  Next: Define-Structure,  Prev: Syntactic Closures,  Up: Scheme Syntax Extension Packages

3.6 Syntax-Case Macros
======================

`(require 'syntax-case)' 

 -- Function: macro:expand expression
 -- Function: syncase:expand expression
     Returns scheme code with the macros and derived expression types of
     EXPRESSION expanded to primitive expression types.

 -- Function: macro:eval expression
 -- Function: syncase:eval expression
     `macro:eval' returns the value of EXPRESSION in the current top
     level environment.  EXPRESSION can contain macro definitions.
     Side effects of EXPRESSION will affect the top level environment.

 -- Procedure: macro:load filename
 -- Procedure: syncase:load filename
     FILENAME should be a string.  If filename names an existing file,
     the `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 `macro:load' procedure does not affect the
     values returned by `current-input-port' and `current-output-port'.

  This is version 2.1 of `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:

   * Removing white space from `expand.pp' to save space in the
     distribution.  This file is not meant for human readers anyway...

   * Removed a couple of Chez scheme dependencies.

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

   * Adding an SLIB-specific initialization file.

   * Removing a couple extra files, most notably the documentation (but
     see below).

  If you wish, you can see exactly what changes were done by reading the
shell script in the 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 `syntax-case',
however, you should get these files and print them out on a PostScript
printer.  They are available with the original `syntax-case'
distribution by anonymous FTP in
`cs.indiana.edu:/pub/scheme/syntax-case'.

  In order to use syntax-case from an interactive top level, execute:
     (require 'syntax-case)
     (require 'repl)
     (repl:top-level macro:eval)
  See the section Repl (*note Repl::) for more information.

  To check operation of syntax-case get
`cs.indiana.edu:/pub/scheme/syntax-case', and type
     (require 'syntax-case)
     (syncase:sanity-check)

  Beware that `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).

3.6.1 Notes
-----------

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

  `syntax-rules' and `with-syntax' (described in `TR356') are defined.

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

  Several other top-level bindings not documented in TR356 are created:
   * the "hooks" in `hooks.ss'

   * the `build-' procedures in `output.ss'

   * `expand-syntax' (the expander)

  The syntax of define has been extended to allow `(define ID)', which
assigns ID to some unspecified value.

  We have attempted to maintain R4RS compatibility where possible.  The
incompatibilities should be confined to `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).


File: slib.info,  Node: Define-Structure,  Next: Define-Record-Type,  Prev: Syntax-Case Macros,  Up: Scheme Syntax Extension Packages

3.7 Define-Structure
====================

`(require 'structure)'

Included with the `syntax-case' files was `structure.scm' which defines
a macro `define-structure'.  Here is its documentation from Gambit 4.0:

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

        * `make-NAME' - A K argument procedure which constructs a new
          record from the value of its K fields.

        * `NAME?' - A procedure which tests if its single argument is
          of the given record type.

        * `NAME-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.

        * `NAME-FIELD-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.


     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:

          > (define-structure point x y color)
          > (define p (make-point 3 5 'red))
          > p
          #<point #3 x: 3 y: 5 color: red>
          > (point-x p)
          3
          > (point-color p)
          red
          > (point-color-set! p 'black)
          > p
          #<point #3 x: 3 y: 5 color: black>



File: slib.info,  Node: Define-Record-Type,  Next: Fluid-Let,  Prev: Define-Structure,  Up: Scheme Syntax Extension Packages

3.8 Define-Record-Type
======================

`(require 'define-record-type)' or `(require 'srfi-9)' 

  `http://srfi.schemers.org/srfi-9/srfi-9.html'

 -- Special Form: define-record-type <type-name> (<constructor-name>
          <field-tag> ...) <predicate-name> <field-spec> ...
     Where
          <field-spec> == (<field-tag> <accessor-name>)
                       == (<field-tag> <accessor-name> <modifier-name>)

     `define-record-type' is a syntax wrapper for the SLIB `record'
     module.


File: slib.info,  Node: Fluid-Let,  Next: Binding to multiple values,  Prev: Define-Record-Type,  Up: Scheme Syntax Extension Packages

3.9 Fluid-Let
=============

`(require 'fluid-let)' 

 -- Syntax: fluid-let `(BINDINGS ...)' FORMS...

     (fluid-let ((VARIABLE INIT) ...)
        EXPRESSION EXPRESSION ...)

  The INITs are evaluated in the current environment (in some
unspecified order), the current values of the VARIABLEs are saved, the
results are assigned to the VARIABLEs, the EXPRESSIONs are evaluated
sequentially in the current environment, the VARIABLEs are restored to
their original values, and the value of the last EXPRESSION is returned.

  The syntax of this special form is similar to that of `let', but
`fluid-let' temporarily rebinds existing VARIABLEs.  Unlike `let',
`fluid-let' creates no new bindings; instead it _assigns_ the values of
each INIT to the binding (determined by the rules of lexical scoping)
of its corresponding VARIABLE.


File: slib.info,  Node: Binding to multiple values,  Next: Guarded LET* special form,  Prev: Fluid-Let,  Up: Scheme Syntax Extension Packages

3.10 Binding to multiple values
===============================

`(require 'receive)' or `(require 'srfi-8)' 

 -- Special Form: receive formals expression body ...
     `http://srfi.schemers.org/srfi-8/srfi-8.html'

  `(require 'let-values)' or `(require 'srfi-11)' 

 -- Special Form: let-values ((formals expression) ...) body ...
 -- Special Form: let-values* ((formals expression) ...) body ...
     `http://srfi.schemers.org/srfi-11/srfi-11.html'


File: slib.info,  Node: Guarded LET* special form,  Next: Guarded COND Clause,  Prev: Binding to multiple values,  Up: Scheme Syntax Extension Packages

3.11 Guarded LET* special form
==============================

`(require 'and-let*)' or `(require 'srfi-2)' 

 -- Macro: and-let* claws body ...
     `http://srfi.schemers.org/srfi-2/srfi-2.html'


File: slib.info,  Node: Guarded COND Clause,  Next: Yasos,  Prev: Guarded LET* special form,  Up: Scheme Syntax Extension Packages

3.12 Guarded COND Clause
========================

`(require 'guarded-cond-clause)' or `(require 'srfi-61)' 

  `http://srfi.schemers.org/srfi-61/srfi-61.html'

 -- library syntax: cond <clause1> <clause2> ...
     _Syntax:_ Each <clause> should be of the form

     (<test> <expression1> ...)

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

     (<test> => <expression>)

     The <clause> production in the formal syntax of Scheme as written
     by R5RS in section 7.1.3 is extended with a new option: 

     <clause> => (<generator> <guard> => <receiver>)

     where <generator>, <guard>, & <receiver> are all <expression>s.

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

     The last <clause> may be an "else clause," which has the form

     (else <expression1> <expression2> ...).

This `port->char-list' procedure accepts an input port and returns a
list of all the characters it produces until the end.

     (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)


File: slib.info,  Node: Yasos,  Prev: Guarded COND Clause,  Up: Scheme Syntax Extension Packages

3.13 Yasos
==========

`(require 'oop)' or `(require 'yasos)' 

  `Yet Another Scheme Object System' is a simple object system for
Scheme based on the paper by Norman Adams and Jonathan Rees: `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.  Scheming with Objects `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.


File: slib.info,  Node: Yasos terms,  Next: Yasos interface,  Prev: Yasos,  Up: Yasos

3.13.1 Terms
------------

"Object"
     Any Scheme data object.

"Instance"
     An instance of the OO system; an "object".

"Operation"
     A METHOD.

_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
     `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 "classes" and no meta-ANYTHING.  Method
     dispatch is by a procedure call a la CLOS rather than by `send'
     syntax a la Smalltalk.

_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.


File: slib.info,  Node: Yasos interface,  Next: Setters,  Prev: Yasos terms,  Up: Yasos

3.13.2 Interface
----------------

 -- Syntax: define-operation `('opname self arg ...`)' DEFAULT-BODY
     Defines a default behavior for data objects which don't handle the
     operation OPNAME.  The default behavior (for an empty
     DEFAULT-BODY) is to generate an error.

 -- Syntax: define-predicate opname?
     Defines a predicate OPNAME?, usually used for determining the
     "type" of an object, such that `(OPNAME? OBJECT)' returns `#t' if
     OBJECT has an operation OPNAME? and `#f' otherwise.

 -- Syntax: object `((NAME SELF ARG ...) BODY)' ...
     Returns an object (an instance of the object system) with
     operations.  Invoking `(NAME OBJECT ARG ...' executes the BODY of
     the OBJECT with SELF bound to OBJECT and with argument(s) ARG....

 -- Syntax: object-with-ancestors `(('ancestor1 init1`)' ...`)'
          operation ...
     A `let'-like form of `object' for multiple inheritance.  It
     returns an object inheriting the behaviour of 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.

 -- Syntax: operate-as component operation self arg ...
     Used in an operation definition (of SELF) to invoke the OPERATION
     in an ancestor COMPONENT but maintain the object's identity.  Also
     known as "send-to-super".

 -- Procedure: print obj port
     A default `print' operation is provided which is just `(format
     PORT OBJ)' (*note Format::) for non-instances and prints OBJ
     preceded by `#<INSTANCE>' for instances.

 -- Function: size obj
     The default method returns the number of elements in OBJ if it is
     a vector, string or list, `2' for a pair, `1' for a character and
     by default id an error otherwise.  Objects such as collections
     (*note Collections::) may override the default in an obvious way.


File: slib.info,  Node: Setters,  Next: Yasos examples,  Prev: Yasos interface,  Up: Yasos

3.13.3 Setters
--------------

"Setters" implement "generalized locations" for objects associated with
some sort of mutable state.  A "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 (*note Yasos::).  Several setters
are predefined, corresponding to getters `car', `cdr', `string-ref' and
`vector-ref' e.g., `(setter car)' is equivalent to `set-car!'.

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

 -- Function: setter getter
     Returns the setter for the procedure GETTER.  E.g., since
     `string-ref' is the getter corresponding to a setter which is
     actually `string-set!':
          (define foo "foo")
          ((setter string-ref) foo 0 #\F) ; set element 0 of foo
          foo => "Foo"

 -- Syntax: set place new-value
     If PLACE is a variable name, `set' is equivalent to `set!'.
     Otherwise, 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 `set' is usually unspecified unless
     used with a setter whose definition guarantees to return a useful
     value.
          (set (string-ref foo 2) #\O)  ; generalized location with getter
          foo => "FoO"
          (set foo "foo")               ; like set!
          foo => "foo"

 -- Procedure: add-setter getter setter
     Add procedures GETTER and SETTER to the (inaccessible) list of
     valid setter/getter pairs.  SETTER implements the store operation
     corresponding to the GETTER access operation for the relevant
     state.  The return value is unspecified.

 -- Procedure: remove-setter-for getter
     Removes the setter corresponding to the specified GETTER from the
     list of valid setters.  The return value is unspecified.

 -- Syntax: define-access-operation getter-name
     Shorthand for a Yasos `define-operation' defining an operation
     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.


File: slib.info,  Node: Yasos examples,  Prev: Setters,  Up: Yasos

3.13.4 Examples
---------------

     ;;; 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)
     => "#<Cell: 1>"
     (set (fetch foo) 2)
     =>
     (print foo #f)
     => "#<Cell: 2>"
     (fetch foo)
     => 2


File: slib.info,  Node: Textual Conversion Packages,  Next: Mathematical Packages,  Prev: Scheme Syntax Extension Packages,  Up: Top

4 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
* Parsing XML::                 'parse-xml or 'ssax
* Printing Scheme::             Nicely
* Time and Date::
* NCBI-DNA::                    DNA and protein sequences
* Schmooz::                     Documentation markup for Scheme programs


File: slib.info,  Node: Precedence Parsing,  Next: Format,  Prev: Textual Conversion Packages,  Up: Textual Conversion Packages

4.1 Precedence Parsing
======================

`(require 'precedence-parse)' or `(require 'parse)' 

This package implements:

   * a Pratt style precedence parser;

   * a "tokenizer" which congeals tokens according to assigned classes
     of constituent characters;

   * procedures giving direct control of parser rulesets;

   * procedures for higher level specification of rulesets.

* Menu:

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


File: slib.info,  Node: Precedence Parsing Overview,  Next: Rule Types,  Prev: Precedence Parsing,  Up: Precedence Parsing

4.1.1 Precedence Parsing Overview
---------------------------------

This package offers improvements over previous parsers.

   * Common computer language constructs are concisely specified.

   * Grammars can be changed dynamically.  Operators can be assigned
     different meanings within a lexical context.

   * Rulesets don't need compilation.  Grammars can be changed
     incrementally.

   * Operator precedence is specified by integers.

   * All possibilities of bad input are handled (1) and return as much
     structure as was parsed when the error occured; The symbol `?' is
     substituted for missing input.

The notion of "binding power" may be unfamiliar to those accustomed to
BNF grammars.

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.

Objects at each level of syntactic grouping have binding powers.

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

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

  ---------- Footnotes ----------

  (1) How do I know this?  I parsed 250kbyte of random input (an e-mail
file) with a non-trivial grammar utilizing all constructs.


File: slib.info,  Node: Rule Types,  Next: Ruleset Definition and Use,  Prev: Precedence Parsing Overview,  Up: Precedence Parsing

4.1.2 Rule Types
----------------

Here are the higher-level syntax types and an example of each.
Precedence considerations are omitted for clarity.  See *Note Grammar
Rule Definition:: for full details.

 -- Grammar: nofix bye exit
          bye
     calls the function `exit' with no arguments.

 -- Grammar: prefix - negate
          - 42
     Calls the function `negate' with the argument `42'.

 -- Grammar: infix - difference
          x - y
     Calls the function `difference' with arguments `x' and `y'.

 -- Grammar: nary + sum
          x + y + z
     Calls the function `sum' with arguments `x', `y', and `y'.

 -- Grammar: postfix ! factorial
          5 !
     Calls the function `factorial' with the argument `5'.

 -- Grammar: prestfix set set!
          set foo bar
     Calls the function `set!' with the arguments `foo' and `bar'.

 -- Grammar: commentfix /* */
          /* almost any text here */
     Ignores the comment delimited by `/*' and `*/'.

 -- Grammar: matchfix { list }
          {0, 1, 2}
     Calls the function `list' with the arguments `0', `1', and `2'.

 -- Grammar: inmatchfix ( funcall )
          f(x, y)
     Calls the function `funcall' with the arguments `f', `x', and `y'.

 -- Grammar: delim ;
          set foo bar;
     delimits the extent of the restfix operator `set'.


File: slib.info,  Node: Ruleset Definition and Use,  Next: Token definition,  Prev: Rule Types,  Up: Precedence Parsing

4.1.3 Ruleset Definition and Use
--------------------------------

 -- Variable: *syn-defs*
     A grammar is built by one or more calls to `prec:define-grammar'.
     The rules are appended to *SYN-DEFS*.  The value of *SYN-DEFS* is
     the grammar suitable for passing as an argument to `prec:parse'.

 -- 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 `*syn-ignore-whitespace*'

In order to start defining a grammar, either

     (set! *syn-defs* '())
  or

     (set! *syn-defs* *syn-ignore-whitespace*)

 -- Function: prec:define-grammar rule1 ...
     Appends RULE1 ... to *SYN-DEFS*.  `prec:define-grammar' is used to
     define both the character classes and rules for tokens.

Once your grammar is defined, save the value of `*syn-defs*' in a
variable (for use when calling `prec:parse').

     (define my-ruleset *syn-defs*)

 -- Function: prec:parse ruleset delim
 -- Function: prec:parse ruleset delim port
     The RULESET argument must be a list of rules as constructed by
     `prec:define-grammar' and extracted from *SYN-DEFS*.

     The token DELIM may be a character, symbol, or string.  A
     character 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.

     `prec:parse' reads a RULESET grammar expression delimited by DELIM
     from the given input PORT.  `prec:parse' returns the next object
     parsable from the given input PORT, updating 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 DELIM) is found
     before any characters are found that can begin an object, then
     `#f' is returned.

     The PORT argument may be omitted, in which case it defaults to the
     value returned by `current-input-port'.  It is an error to parse
     from a closed port.  


File: slib.info,  Node: Token definition,  Next: Nud and Led Definition,  Prev: Ruleset Definition and Use,  Up: Precedence Parsing

4.1.4 Token definition
----------------------

 -- Function: tok:char-group group chars chars-proc
     The argument CHARS may be a single character, a list of
     characters, or a string.  Each character in CHARS is treated as
     though `tok:char-group' was called with that character alone.

     The argument CHARS-PROC must be a procedure of one argument, a
     list of characters.  After `tokenize' has finished accumulating
     the characters for a token, it calls CHARS-PROC with the list of
     characters.  The value returned is the token which `tokenize'
     returns.

     The argument GROUP may be an exact integer or a procedure of one
     character argument.  The following discussion concerns the
     treatment which the tokenizing routine, `tokenize', will accord to
     characters on the basis of their groups.

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

     The 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 GROUP is a procedure, then, when triggerd by the occurence of
     an initial (no accumulation) CHARS character, this procedure will
     be repeatedly called with each successive character from the input
     stream until the GROUP procedure returns a non-false value.

The following convenient constants are provided for use with
`tok:char-group'.

 -- Constant: tok:decimal-digits
     Is the string `"0123456789"'.

 -- Constant: tok:upper-case
     Is the string consisting of all upper-case letters
     ("ABCDEFGHIJKLMNOPQRSTUVWXYZ").

 -- Constant: tok:lower-case
     Is the string consisting of all lower-case letters
     ("abcdefghijklmnopqrstuvwxyz").

 -- Constant: tok:whitespaces
     Is the string consisting of all characters between 0 and 255 for
     which `char-whitespace?' returns true.

For the purpose of reporting problems in error messages, this package
keeps track of the "current column".  When the column does not simply
track input characters, `tok:bump-column' can be used to adjust the
current-column.

 -- Function: tok:bump-column pos port
     Adds POS to the current-column for input-port PORT.


File: slib.info,  Node: Nud and Led Definition,  Next: Grammar Rule Definition,  Prev: Token definition,  Up: Precedence Parsing

4.1.5 Nud and Led Definition
----------------------------

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

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

The "Left Denotation" (or "led") of a token is the procedure,
arguments, and lbp applying for that token when there is a "Left", an
unclaimed parsed expression.

In his paper,

     Pratt, V. R.  Top Down Operator Precendence.  `SIGACT/SIGPLAN
     Symposium on Principles of Programming Languages', Boston, 1973,
     pages 41-51

  the "left binding power" (or "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 _dynamically binding_
NUDs and LEDs allows them independence.

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

Character 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.

 -- Function: prec:make-nud tk sop arg1 ...
     Returns a rule specifying that SOP be called when TK is parsed.
     If SOP is a procedure, it is called with TK and ARG1 ... as its
     arguments; the resulting value is incorporated into the expression
     being built.  Otherwise, `(list SOP ARG1 ...)' is incorporated.

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.

 -- Function: prec:make-led tk sop arg1 ...
     Returns a rule specifying that SOP be called when TK is parsed and
     LEFT has an unclaimed parsed expression.  If SOP is a procedure,
     it is called with LEFT, TK, and ARG1 ... as its arguments; the
     resulting value is incorporated into the expression being built.
     Otherwise, LEFT is incorporated.

If no LED has been defined for a token, and LEFT is set, the parser
issues a warning.


File: slib.info,  Node: Grammar Rule Definition,  Prev: Nud and Led Definition,  Up: Precedence Parsing

4.1.6 Grammar Rule Definition
-----------------------------

Here are procedures for defining rules for the syntax types introduced
in *Note Precedence Parsing Overview::.

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

For procedures prec:delim, ..., prec:prestfix, if the SOP argument is
`#f', then the token which triggered this rule is converted to a symbol
and returned.  A false SOP argument to the procedures prec:commentfix,
prec:matchfix, or prec:inmatchfix has a different meaning.

Character 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.

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

 -- Function: prec:nofix tk sop
     Returns a rule specifying the following actions take place when TK
     is parsed:
        * If SOP is a procedure, it is called with no arguments; the
          resulting value is incorporated into the expression being
          built.  Otherwise, the list of SOP is incorporated.

 -- Function: prec:prefix tk sop bp rule1 ...
     Returns a rule specifying the following actions take place when TK
     is parsed:
        * The rules RULE1 ... augment and, in case of conflict, override
          rules currently in effect.

        * `prec:parse1' is called with binding-power BP.

        * If SOP is a procedure, it is called with the expression
          returned from `prec:parse1'; the resulting value is
          incorporated into the expression being built.  Otherwise, the
          list of SOP and the expression returned from `prec:parse1' is
          incorporated.

        * The ruleset in effect before TK was parsed is restored; RULE1
          ... are forgotten.

 -- Function: prec:infix tk sop lbp bp rule1 ...
     Returns a rule declaring the left-binding-precedence of the token
     TK is LBP and specifying the following actions take place when TK
     is parsed:
        * The rules RULE1 ... augment and, in case of conflict, override
          rules currently in effect.

        * One expression is parsed with binding-power LBP.  If instead a
          delimiter is encountered, a warning is issued.

        * If SOP is a procedure, it is applied to the list of LEFT and
          the parsed expression; the resulting value is incorporated
          into the expression being built.  Otherwise, the list of SOP,
          the LEFT expression, and the parsed expression is
          incorporated.

        * The ruleset in effect before TK was parsed is restored; RULE1
          ... are forgotten.

 -- Function: prec:nary tk sop bp
     Returns a rule declaring the left-binding-precedence of the token
     TK is BP and specifying the following actions take place when TK
     is parsed:
        * Expressions are parsed with binding-power BP as far as they
          are interleaved with the token TK.

        * If SOP is a procedure, it is applied to the list of LEFT and
          the parsed expressions; the resulting value is incorporated
          into the expression being built.  Otherwise, the list of SOP,
          the LEFT expression, and the parsed expressions is
          incorporated.

 -- Function: prec:postfix tk sop lbp
     Returns a rule declaring the left-binding-precedence of the token
     TK is LBP and specifying the following actions take place when TK
     is parsed:
        * If SOP is a procedure, it is called with the LEFT expression;
          the resulting value is incorporated into the expression being
          built.  Otherwise, the list of SOP and the LEFT expression is
          incorporated.

 -- Function: prec:prestfix tk sop bp rule1 ...
     Returns a rule specifying the following actions take place when TK
     is parsed:
        * The rules RULE1 ... augment and, in case of conflict, override
          rules currently in effect.

        * Expressions are parsed with binding-power BP until a
          delimiter is reached.

        * If 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 SOP and the
          parsed expressions is incorporated.

        * The ruleset in effect before TK was parsed is restored; RULE1
          ... are forgotten.

 -- Function: prec:commentfix tk stp match rule1 ...
     Returns rules specifying the following actions take place when TK
     is parsed:
        * The rules RULE1 ... augment and, in case of conflict, override
          rules currently in effect.

        * Characters are read until and end-of-file or a sequence of
          characters is read which matches the _string_ MATCH.

        * If STP is a procedure, it is called with the string of all
          that was read between the TK and MATCH (exclusive).

        * The ruleset in effect before TK was parsed is restored; RULE1
          ... are forgotten.

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

 -- Function: prec:matchfix tk sop sep match rule1 ...
     Returns a rule specifying the following actions take place when TK
     is parsed:
        * The rules RULE1 ... augment and, in case of conflict, override
          rules currently in effect.

        * A rule declaring the token MATCH a delimiter takes effect.

        * Expressions are parsed with binding-power `0' until the token
          MATCH is reached.  If the token SEP does not appear between
          each pair of expressions parsed, a warning is issued.

        * If 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 SOP and the
          parsed expressions is incorporated.

        * The ruleset in effect before TK was parsed is restored; RULE1
          ... are forgotten.

 -- Function: prec:inmatchfix tk sop sep match lbp rule1 ...
     Returns a rule declaring the left-binding-precedence of the token
     TK is LBP and specifying the following actions take place when TK
     is parsed:
        * The rules RULE1 ... augment and, in case of conflict, override
          rules currently in effect.

        * A rule declaring the token MATCH a delimiter takes effect.

        * Expressions are parsed with binding-power `0' until the token
          MATCH is reached.  If the token SEP does not appear between
          each pair of expressions parsed, a warning is issued.

        * If SOP is a procedure, it is applied to the list of LEFT and
          the parsed expressions; the resulting value is incorporated
          into the expression being built.  Otherwise, the list of SOP,
          the LEFT expression, and the parsed expressions is
          incorporated.

        * The ruleset in effect before TK was parsed is restored; RULE1
          ... are forgotten.


File: slib.info,  Node: Format,  Next: Standard Formatted I/O,  Prev: Precedence Parsing,  Up: Textual Conversion Packages

4.2 Format (version 3.1)
========================

`(require 'format)' or `(require 'srfi-28)' 

* Menu:

* Format Interface::
* Format Specification::


File: slib.info,  Node: Format Interface,  Next: Format Specification,  Prev: Format,  Up: Format

4.2.1 Format Interface
----------------------

 -- Function: format destination format-string . arguments
     An almost complete implementation of Common LISP format description
     according to the CL reference book `Common LISP' from Guy L.
     Steele, Digital Press.  Backward compatible to most of the
     available Scheme format implementations.

     Returns `#t', `#f' or a string; has side effect of printing
     according to FORMAT-STRING.  If DESTINATION is `#t', the output is
     to the current output port and `#t' is returned.  If DESTINATION
     is `#f', a formatted string is returned as the result of the call.
     NEW: If DESTINATION is a string, DESTINATION is regarded as the
     format string; FORMAT-STRING is then the first argument and the
     output is returned as a string. If DESTINATION is a number, the
     output is to the current error port if available by the
     implementation. Otherwise DESTINATION must be an output port and
     `#t' is returned.

     FORMAT-STRING must be a string.  In case of a formatting error
     format returns `#f' and prints a message on the current output or
     error port.  Characters are output as if the string were output by
     the `display' function with the exception of those prefixed by a
     tilde (~).  For a detailed description of the FORMAT-STRING syntax
     please consult a Common LISP format reference manual.  For a test
     suite to verify this format implementation load `formatst.scm'.
     Please send bug reports to `lutzeb@cs.tu-berlin.de'.

     Note: `format' is not reentrant, i.e. only one `format'-call may
     be executed at a time.



File: slib.info,  Node: Format Specification,  Prev: Format Interface,  Up: Format

4.2.2 Format Specification (Format version 3.1)
-----------------------------------------------

Please consult a Common LISP format reference manual for a detailed
description of the format string syntax.  For a demonstration of the
implemented directives see `formatst.scm'.

  This implementation supports directive parameters and modifiers (`:'
and `@' characters). Multiple parameters must be separated by a comma
(`,').  Parameters can be numerical parameters (positive or negative),
character parameters (prefixed by a quote character (`''), variable
parameters (`v'), number of rest arguments parameter (`#'), empty and
default parameters.  Directive characters are case independent. The
general form of a directive is:

DIRECTIVE ::= ~{DIRECTIVE-PARAMETER,}[:][@]DIRECTIVE-CHARACTER

DIRECTIVE-PARAMETER ::= [ [-|+]{0-9}+ | 'CHARACTER | v | # ]

4.2.2.1 Implemented CL Format Control Directives
................................................

Documentation syntax: Uppercase characters represent the corresponding
control directive characters. Lowercase characters represent control
directive parameter descriptions.

`~A'
     Any (print as `display' does).
    `~@A'
          left pad.

    `~MINCOL,COLINC,MINPAD,PADCHARA'
          full padding.

`~S'
     S-expression (print as `write' does).
    `~@S'
          left pad.

    `~MINCOL,COLINC,MINPAD,PADCHARS'
          full padding.

`~D'
     Decimal.
    `~@D'
          print number sign always.

    `~:D'
          print comma separated.

    `~MINCOL,PADCHAR,COMMACHARD'
          padding.

`~X'
     Hexadecimal.
    `~@X'
          print number sign always.

    `~:X'
          print comma separated.

    `~MINCOL,PADCHAR,COMMACHARX'
          padding.

`~O'
     Octal.
    `~@O'
          print number sign always.

    `~:O'
          print comma separated.

    `~MINCOL,PADCHAR,COMMACHARO'
          padding.

`~B'
     Binary.
    `~@B'
          print number sign always.

    `~:B'
          print comma separated.

    `~MINCOL,PADCHAR,COMMACHARB'
          padding.

`~NR'
     Radix N.
    `~N,MINCOL,PADCHAR,COMMACHARR'
          padding.

`~@R'
     print a number as a Roman numeral.

`~:@R'
     print a number as an "old fashioned" Roman numeral.

`~:R'
     print a number as an ordinal English number.

`~R'
     print a number as a cardinal English number.

`~P'
     Plural.
    `~@P'
          prints `y' and `ies'.

    `~:P'
          as `~P but jumps 1 argument backward.'

    `~:@P'
          as `~@P but jumps 1 argument backward.'

`~C'
     Character.
    `~@C'
          prints a character as the reader can understand it (i.e. `#\'
          prefixing).

    `~:C'
          prints a character as emacs does (eg. `^C' for ASCII 03).

`~F'
     Fixed-format floating-point (prints a flonum like MMM.NNN).
    `~WIDTH,DIGITS,SCALE,OVERFLOWCHAR,PADCHARF'

    `~@F'
          If the number is positive a plus sign is printed.

`~E'
     Exponential floating-point (prints a flonum like MMM.NNN`E'EE).
    `~WIDTH,DIGITS,EXPONENTDIGITS,SCALE,OVERFLOWCHAR,PADCHAR,EXPONENTCHARE'

    `~@E'
          If the number is positive a plus sign is printed.

`~G'
     General floating-point (prints a flonum either fixed or
     exponential).
    `~WIDTH,DIGITS,EXPONENTDIGITS,SCALE,OVERFLOWCHAR,PADCHAR,EXPONENTCHARG'

    `~@G'
          If the number is positive a plus sign is printed.

`~$'
     Dollars floating-point (prints a flonum in fixed with signs
     separated).
    `~DIGITS,SCALE,WIDTH,PADCHAR$'

    `~@$'
          If the number is positive a plus sign is printed.

    `~:@$'
          A sign is always printed and appears before the padding.

    `~:$'
          The sign appears before the padding.

`~%'
     Newline.
    `~N%'
          print N newlines.

`~&'
     print newline if not at the beginning of the output line.
    `~N&'
          prints `~&' and then N-1 newlines.

`~|'
     Page Separator.
    `~N|'
          print N page separators.

`~~'
     Tilde.
    `~N~'
          print N tildes.

`~'<newline>
     Continuation Line.
    `~:'<newline>
          newline is ignored, white space left.

    `~@'<newline>
          newline is left, white space ignored.

`~T'
     Tabulation.
    `~@T'
          relative tabulation.

    `~COLNUM,COLINCT'
          full tabulation.

`~?'
     Indirection (expects indirect arguments as a list).
    `~@?'
          extracts indirect arguments from format arguments.

`~(STR~)'
     Case conversion (converts by `string-downcase').
    `~:(STR~)'
          converts by `string-capitalize'.

    `~@(STR~)'
          converts by `string-capitalize-first'.

    `~:@(STR~)'
          converts by `string-upcase'.

`~*'
     Argument Jumping (jumps 1 argument forward).
    `~N*'
          jumps N arguments forward.

    `~:*'
          jumps 1 argument backward.

    `~N:*'
          jumps N arguments backward.

    `~@*'
          jumps to the 0th argument.

    `~N@*'
          jumps to the Nth argument (beginning from 0)

`~[STR0~;STR1~;...~;STRN~]'
     Conditional Expression (numerical clause conditional).
    `~N['
          take argument from N.

    `~@['
          true test conditional.

    `~:['
          if-else-then conditional.

    `~;'
          clause separator.

    `~:;'
          default clause follows.

`~{STR~}'
     Iteration (args come from the next argument (a list)). Iteration
     bounding is controlled by configuration variables
     FORMAT:ITERATION-BOUNDED and FORMAT:MAX-ITERATIONS.  With both
     variables default, a maximum of 100 iterations will be performed.
    `~N{'
          at most N iterations.

    `~:{'
          args from next arg (a list of lists).

    `~@{'
          args from the rest of arguments.

    `~:@{'
          args from the rest args (lists).

`~^'
     Up and out.
    `~N^'
          aborts if N = 0

    `~N,M^'
          aborts if N = M

    `~N,M,K^'
          aborts if N <= M <= K

4.2.2.2 Not Implemented CL Format Control Directives
....................................................

`~:A'
     print `#f' as an empty list (see below).

`~:S'
     print `#f' as an empty list (see below).

`~<~>'
     Justification.

`~:^'
     (sorry I don't understand its semantics completely)

4.2.2.3 Extended, Replaced and Additional Control Directives
............................................................

`~MINCOL,PADCHAR,COMMACHAR,COMMAWIDTHD'

`~MINCOL,PADCHAR,COMMACHAR,COMMAWIDTHX'

`~MINCOL,PADCHAR,COMMACHAR,COMMAWIDTHO'

`~MINCOL,PADCHAR,COMMACHAR,COMMAWIDTHB'

`~N,MINCOL,PADCHAR,COMMACHAR,COMMAWIDTHR'
     COMMAWIDTH is the number of characters between two comma
     characters.

`~I'
     print a R4RS complex number as `~F~@Fi' with passed parameters for
     `~F'.

`~Y'
     Pretty print formatting of an argument for scheme code lists.

`~K'
     Same as `~?.'

`~!'
     Flushes the output if format DESTINATION is a port.

`~_'
     Print a `#\space' character
    `~N_'
          print N `#\space' characters.

`~/'
     Print a `#\tab' character
    `~N/'
          print N `#\tab' characters.

`~NC'
     Takes N as an integer representation for a character. No arguments
     are consumed. N is converted to a character by `integer->char'.  N
     must be a positive decimal number.

`~:S'
     Print out readproof.  Prints out internal objects represented as
     `#<...>' as strings `"#<...>"' so that the format output can always
     be processed by `read'.

`~:A'
     Print out readproof.  Prints out internal objects represented as
     `#<...>' as strings `"#<...>"' so that the format output can always
     be processed by `read'.

`~Q'
     Prints information and a copyright notice on the format
     implementation.
    `~:Q'
          prints format version.

`~F, ~E, ~G, ~$'
     may also print number strings, i.e. passing a number as a string
     and format it accordingly.

4.2.2.4 Configuration Variables
...............................

Format has some configuration variables at the beginning of
`format.scm' to suit the systems and users needs. There should be no
modification necessary for the configuration that comes with SLIB.  If
modification is desired the variable should be set after the format
code is loaded. Format detects automatically if the running scheme
system implements floating point numbers and complex numbers.

FORMAT:SYMBOL-CASE-CONV
     Symbols are converted by `symbol->string' so the case type of the
     printed symbols is implementation dependent.
     `format:symbol-case-conv' is a one arg closure which is either
     `#f' (no conversion), `string-upcase', `string-downcase' or
     `string-capitalize'. (default `#f')

FORMAT:IOBJ-CASE-CONV
     As FORMAT:SYMBOL-CASE-CONV but applies for the representation of
     implementation internal objects. (default `#f')

FORMAT:EXPCH
     The character prefixing the exponent value in `~E' printing.
     (default `#\E')

FORMAT:ITERATION-BOUNDED
     When `#t', a `~{...~}' control will iterate no more than the
     number of times specified by FORMAT:MAX-ITERATIONS regardless of
     the number of iterations implied by modifiers and arguments.  When
     `#f', a `~{...~}' control will iterate the number of times implied
     by modifiers and arguments, unless termination is forced by
     language or system limitations. (default `#t')

FORMAT:MAX-ITERATIONS
     The maximum number of iterations performed by a `~{...~}' control.
     Has effect only when FORMAT:ITERATION-BOUNDED is `#t'.  (default
     100)


4.2.2.5 Compatibility With Other Format Implementations
.......................................................

SLIB format 2.x:
     See `format.doc'.

SLIB format 1.4:
     Downward compatible except for padding support and `~A', `~S',
     `~P', `~X' uppercase printing.  SLIB format 1.4 uses C-style
     `printf' padding support which is completely replaced by the CL
     `format' padding style.

MIT C-Scheme 7.1:
     Downward compatible except for `~', which is not documented
     (ignores all characters inside the format string up to a newline
     character).  (7.1 implements `~a', `~s', ~NEWLINE, `~~', `~%',
     numerical and variable parameters and `:/@' modifiers in the CL
     sense).

Elk 1.5/2.0:
     Downward compatible except for `~A' and `~S' which print in
     uppercase.  (Elk implements `~a', `~s', `~~', and `~%' (no
     directive parameters or modifiers)).

Scheme->C 01nov91:
     Downward compatible except for an optional destination parameter:
     S2C accepts a format call without a destination which returns a
     formatted string. This is equivalent to a #f destination in S2C.
     (S2C implements `~a', `~s', `~c', `~%', and `~~' (no directive
     parameters or modifiers)).


  This implementation of format is solely useful in the SLIB context
because it requires other components provided by SLIB.


File: slib.info,  Node: Standard Formatted I/O,  Next: Programs and Arguments,  Prev: Format,  Up: Textual Conversion Packages

4.3 Standard Formatted I/O
==========================

* Menu:

* Standard Formatted Output::   'printf
* Standard Formatted Input::    'scanf

4.3.1 stdio
-----------

`(require 'stdio)' 

  `require's `printf' and `scanf' and additionally defines the symbols:

 -- Variable: stdin
     Defined to be `(current-input-port)'.

 -- Variable: stdout
     Defined to be `(current-output-port)'.

 -- Variable: stderr
     Defined to be `(current-error-port)'.


File: slib.info,  Node: Standard Formatted Output,  Next: Standard Formatted Input,  Prev: Standard Formatted I/O,  Up: Standard Formatted I/O

4.3.2 Standard Formatted Output
-------------------------------

`(require 'printf)' 

 -- Procedure: printf format arg1 ...
 -- Procedure: fprintf port format arg1 ...
 -- Procedure: sprintf str format arg1 ...
 -- Procedure: sprintf #f format arg1 ...
 -- Procedure: sprintf k format arg1 ...
     Each function converts, formats, and outputs its ARG1 ...
     arguments according to the control string FORMAT argument and
     returns the number of characters output.

     `printf' sends its output to the port `(current-output-port)'.
     `fprintf' sends its output to the port PORT.  `sprintf'
     `string-set!'s locations of the non-constant string argument STR
     to the output characters.

     Two extensions of `sprintf' return new strings.  If the first
     argument is `#f', then the returned string's length is as many
     characters as specified by the FORMAT and data; if the first
     argument is a non-negative integer K, then the length of the
     returned string is also bounded by K.

     The string 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 ARG1 ....  The
     results are undefined if there are an insufficient number of
     arguments for the format.  If FORMAT is exhausted while some of the
     ARG1 ... arguments remain unused, the excess ARG1 ... arguments
     are ignored.

     The conversion specifications in a format string have the form:

          % [ FLAGS ] [ WIDTH ] [ . PRECISION ] [ TYPE ] CONVERSION

     An output conversion specifications consist of an initial `%'
     character followed in sequence by:

        * Zero or more "flag characters" that modify the normal
          behavior of the conversion specification.

         `-'
               Left-justify the result in the field.  Normally the
               result is right-justified.

         `+'
               For the signed `%d' and `%i' conversions and all inexact
               conversions, prefix a plus sign if the value is positive.

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

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

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

         `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 `-' flag is also specified, or if
               a precision is specified for an exact converson.

        * An optional decimal integer specifying the "minimum field
          width".  If the normal conversion produces fewer characters
          than this, the field is padded (with spaces or zeros per the
          `0' flag) to the specified width.  This is a _minimum_ width;
          if the normal conversion produces more characters than this,
          the field is _not_ truncated.  

          Alternatively, if the field width is `*', 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 `-'
          flag is set (see above) and the absolute value is used as the
          field width.

        * An optional "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 (`.') followed optionally by a decimal integer (which
          defaults to zero if omitted).  

          Alternatively, if the precision is `.*', 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 `*' for both the field
          width and precision, the field width argument precedes the
          precision argument.  The `.*' precision is an enhancement.  C
          library versions may not accept this syntax.

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

          For the `%g' and `%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 `0' or not specified for `%g'
          or `%G', it is treated like a value of `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 `0' with an explicit
          precision of zero produces no characters.

        * An optional one of `l', `h' or `L', which is ignored for
          numeric conversions.  It is an error to specify these
          modifiers for non-numeric conversions.

        * A character that specifies the conversion to be applied.

4.3.2.1 Exact Conversions
.........................

    `b', `B'
          Print an integer as an unsigned binary number.

          _Note:_ `%b' and `%B' are SLIB extensions.

    `d', `i'
          Print an integer as a signed decimal number.  `%d' and `%i'
          are synonymous for output, but are different when used with
          `scanf' for input (*note Standard Formatted Input::).

    `o'
          Print an integer as an unsigned octal number.

    `u'
          Print an integer as an unsigned decimal number.

    `x', `X'
          Print an integer as an unsigned hexadecimal number.  `%x'
          prints using the digits `0123456789abcdef'.  `%X' prints
          using the digits `0123456789ABCDEF'.

4.3.2.2 Inexact Conversions
...........................

    `f'
          Print a floating-point number in fixed-point notation.

    `e', `E'
          Print a floating-point number in exponential notation.  `%e'
          prints `e' between mantissa and exponont.  `%E' prints `E'
          between mantissa and exponont.

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

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


4.3.2.3 Other Conversions
.........................

    `c'
          Print a single character.  The `-' flag is the only one which
          can be specified.  It is an error to specify a precision.

    `s'
          Print a string.  The `-' 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.

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

          _Note:_ `%a' and `%A' are SLIB extensions.

    `%'
          Print a literal `%' character.  No argument is consumed.  It
          is an error to specify flags, field width, precision, or type
          modifiers with `%%'.


File: slib.info,  Node: Standard Formatted Input,  Prev: Standard Formatted Output,  Up: Standard Formatted I/O

4.3.3 Standard Formatted Input
------------------------------

`(require 'scanf)' 

 -- Function: scanf-read-list format
 -- Function: scanf-read-list format port
 -- Function: scanf-read-list format string

 -- Macro: scanf format arg1 ...
 -- Macro: fscanf port format arg1 ...
 -- Macro: sscanf str format arg1 ...
     Each function reads characters, interpreting them according to the
     control string FORMAT argument.

     `scanf-read-list' returns a list of the items specified as far as
     the input matches FORMAT.  `scanf', `fscanf', and `sscanf' return
     the number of items successfully matched and stored.  `scanf',
     `fscanf', and `sscanf' also set the location corresponding to ARG1
     ... using the methods:

    symbol
          `set!'

    car expression
          `set-car!'

    cdr expression
          `set-cdr!'

    vector-ref expression
          `vector-set!'

    substring expression
          `substring-move-left!'

     The argument to a `substring' expression in ARG1 ... must be a
     non-constant string.  Characters will be stored starting at the
     position specified by the second argument to `substring'.  The
     number of characters stored will be limited by either the position
     specified by the third argument to `substring' or the length of the
     matched string, whichever is less.

     The control string, FORMAT, contains conversion specifications and
     other characters used to direct interpretation of input sequences.
     The control string contains:

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

        * An ordinary character (not `%') that must match the next
          character of the input stream.

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


     Unless the specification contains the `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 `*' 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.

          _Note:_ This specification of format strings differs from the
          `ANSI C' and `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 `ANSI C' and SLIB, prepend whitespace to all
          conversion specifications except `[' and `c'.

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

    `%'
          A single % is expected in the input at this point; no value
          is returned.

    `d', `D'
          A decimal integer is expected.

    `u', `U'
          An unsigned decimal integer is expected.

    `o', `O'
          An octal integer is expected.

    `x', `X'
          A hexadecimal integer is expected.

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

    `n'
          Returns the total number of bytes (including white space)
          read by `scanf'.  No input is consumed by `%n'.

    `f', `F', `e', `E', `g', `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 `.', followed
          by an optional exponent field consisting of an `E' or an `e',
          followed by an optional `+', `-', or space, followed by an
          integer.

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

    `s', `S'
          A character string is expected The input field is terminated
          by a white-space character.  `scanf' cannot read a null
          string.

    `['
          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.  `^', 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 `[0123456789]' to be expressed `[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 `^') 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.

     The `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.


File: slib.info,  Node: Programs and Arguments,  Next: HTML,  Prev: Standard Formatted I/O,  Up: Textual Conversion Packages

4.4 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::                   'filename
* Batch::                       'batch


File: slib.info,  Node: Getopt,  Next: Command Line,  Prev: Programs and Arguments,  Up: Programs and Arguments

4.4.1 Getopt
------------

`(require 'getopt)' 

  This routine implements Posix command line argument parsing.  Notice
that returning values through global variables means that `getopt' is
_not_ reentrant.

  Obedience to Posix format for the `getopt' calls sows confusion.
Passing ARGC and ARGV as arguments while referencing OPTIND as a global
variable leads to strange behavior, especially when the calls to
`getopt' are buried in other procedures.

  Even in C, ARGC can be derived from ARGV; what purpose does it serve
beyond providing an opportunity for ARGV/ARGC mismatch?  Just such a
mismatch existed for years in a SLIB `getopt--' example.

  I have removed the ARGC and ARGV arguments to getopt procedures; and
replaced them with a global variable:

 -- Variable: *argv*
     Define *ARGV* with a list of arguments before calling getopt
     procedures.  If you don't want the first (0th) element to be
     ignored, set *OPTIND* to 0 (after requiring getopt).

 -- Variable: *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, *OPTIND* must be reset.

 -- Variable: *optarg*
     Is set by getopt to the (string) option-argument of the current
     option.

 -- Function: getopt optstring
     Returns the next option letter in *ARGV* (starting from
     `(vector-ref argv *optind*)') that matches a letter in OPTSTRING.
     *ARGV* is a vector or list of strings, the 0th of which getopt
     usually ignores.  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 *ARGV*.

     *OPTIND* is the index of the next element of the *ARGV* vector to
     be processed.  It is initialized to 1 by `getopt.scm', and
     `getopt' updates it when it finishes with each element of *ARGV*.

     `getopt' returns the next option character from *ARGV* that
     matches a character in OPTSTRING, if there is one that matches.
     If the option takes an argument, `getopt' sets the variable
     *OPTARG* to the option-argument as follows:

        * If the option was the last character in the string pointed to
          by an element of *ARGV*, then *OPTARG* contains the next
          element of *ARGV*, and *OPTIND* is incremented by 2.  If the
          resulting value of *OPTIND* is greater than or equal to
          `(length *ARGV*)', this indicates a missing option argument,
          and `getopt' returns an error indication.

        * Otherwise, *OPTARG* is set to the string following the option
          character in that element of *ARGV*, and *OPTIND* is
          incremented by 1.

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

     If `getopt' encounters an option character that is not contained in
     OPTSTRING, it returns the question-mark `#\?' character.  If it
     detects a missing option argument, it returns the colon character
     `#\:' if the first character of OPTSTRING was a colon, or a
     question-mark character otherwise.  In either case, `getopt' sets
     the variable GETOPT:OPT to the option character that caused the
     error.

     The special option `"--"' can be used to delimit the end of the
     options; `#f' is returned, and `"--"' is skipped.

     RETURN VALUE

     `getopt' returns the next option character specified on the command
     line.  A colon `#\:' is returned if `getopt' detects a missing
     argument and the first character of OPTSTRING was a colon `#\:'.

     A question-mark `#\?' is returned if `getopt' encounters an option
     character not in OPTSTRING or detects a missing argument and the
     first character of OPTSTRING was not a colon `#\:'.

     Otherwise, `getopt' returns `#f' when all command line options
     have been parsed.

     Example:
          #! /usr/local/bin/scm
          (require 'program-arguments)                                        |
          (require 'getopt)
          (define argv (program-arguments))                                   |
          
          (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)

4.4.2 Getopt--
--------------

 -- Function: `getopt--' optstring
     The procedure `getopt--' is an extended version of `getopt' which
     parses "long option names" of the form `--hold-the-onions' and
     `--verbosity-level=extreme'.  `Getopt--' behaves as `getopt'
     except for non-empty options beginning with `--'.

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

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

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


File: slib.info,  Node: Command Line,  Next: Parameter lists,  Prev: Getopt,  Up: Programs and Arguments

4.4.3 Command Line
------------------

`(require 'read-command)' 

 -- Function: read-command port
 -- Function: read-command
     `read-command' converts a "command line" into a list of strings suitable
     for parsing by `getopt'.  The syntax of command lines supported
     resembles that of popular "shell"s.  `read-command' updates PORT
     to point to the first character past the command delimiter.

     If an end of file is encountered in the input before any
     characters are found that can begin an object or comment, then an
     end of file object is returned.

     The PORT argument may be omitted, in which case it defaults to the
     value returned by `current-input-port'.

     The fields into which the command line is split are delimited by
     whitespace as defined by `char-whitespace?'.  The end of a command
     is delimited by end-of-file or unescaped semicolon (<;>) or
     <newline>.  Any character can be literally included in a field by
     escaping it with a backslach (<\>).

     The initial character and types of fields recognized are:
    `\'
          The next character has is taken literally and not interpreted
          as a field delimiter.  If <\> is the last character before a
          <newline>, that <newline> is just ignored.  Processing
          continues from the characters after the <newline> as though
          the backslash and <newline> were not there.

    `"'
          The characters up to the next unescaped <"> are taken
          literally, according to [R4RS] rules for literal strings
          (*note Strings: (r4rs)Strings.).

    `(', `%''
          One scheme expression is `read' starting with this character.
          The `read' expression is evaluated, converted to a string
          (using `display'), and replaces the expression in the returned
          field.

    `;'
          Semicolon delimits a command.  Using semicolons more than one
          command can appear on a line.  Escaped semicolons and
          semicolons inside strings do not delimit commands.

     The comment field differs from the previous fields in that it must
     be the first character of a command or appear after whitespace in
     order to be recognized.  <#> can be part of fields if these
     conditions are not met.  For instance, `ab#c' is just the field
     ab#c.

    `#'
          Introduces a comment.  The comment continues to the end of
          the line on which the semicolon appears.  Comments are
          treated as whitespace by `read-dommand-line' and backslashes
          before <newline>s in comments are also ignored.

 -- Function: read-options-file filename
     `read-options-file' converts an "options file" into a list of strings
     suitable for parsing by `getopt'.  The syntax of options files is
     the same as the syntax for command lines, except that <newline>s
     do not terminate reading (only <;> or end of file).

     If an end of file is encountered before any characters are found
     that can begin an object or comment, then an end of file object is
     returned.


File: slib.info,  Node: Parameter lists,  Next: Getopt Parameter lists,  Prev: Command Line,  Up: Programs and Arguments

4.4.4 Parameter lists
---------------------

`(require 'parameters)' 

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.

A "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.

A PARAMETER has the form `(parameter-name value1 ...)'.  This format
allows for more than one value per parameter-name.

A PARAMETER-LIST is a list of PARAMETERs, each with a different
PARAMETER-NAME.

 -- Function: make-parameter-list parameter-names
     Returns an empty parameter-list with slots for PARAMETER-NAMES.

 -- Function: parameter-list-ref parameter-list parameter-name
     PARAMETER-NAME must name a valid slot of PARAMETER-LIST.
     `parameter-list-ref' returns the value of parameter PARAMETER-NAME
     of PARAMETER-LIST.

 -- Function: remove-parameter parameter-name parameter-list
     Removes the parameter PARAMETER-NAME from PARAMETER-LIST.
     `remove-parameter' does not alter the argument PARAMETER-LIST.

     If there are more than one PARAMETER-NAME parameters, an error is
     signaled.

 -- Procedure: adjoin-parameters! parameter-list parameter1 ...
     Returns PARAMETER-LIST with PARAMETER1 ... merged in.

 -- Procedure: parameter-list-expand expanders parameter-list
     EXPANDERS is a list of procedures whose order matches the order of
     the PARAMETER-NAMEs in the call to `make-parameter-list' which
     created PARAMETER-LIST.  For each non-false element of EXPANDERS
     that procedure is mapped over the corresponding parameter value
     and the returned parameter lists are merged into PARAMETER-LIST.

     This process is repeated until PARAMETER-LIST stops growing.  The
     value returned from `parameter-list-expand' is unspecified.

 -- Function: fill-empty-parameters defaulters parameter-list
     DEFAULTERS is a list of procedures whose order matches the order
     of the PARAMETER-NAMEs in the call to `make-parameter-list' which
     created PARAMETER-LIST.  `fill-empty-parameters' returns a new
     parameter-list with each empty parameter replaced with the list
     returned by calling the corresponding DEFAULTER with
     PARAMETER-LIST as its argument.

 -- Function: check-parameters checks parameter-list
     CHECKS is a list of procedures whose order matches the order of
     the PARAMETER-NAMEs in the call to `make-parameter-list' which
     created PARAMETER-LIST.

     `check-parameters' returns PARAMETER-LIST if each CHECK of the
     corresponding PARAMETER-LIST returns non-false.  If some CHECK
     returns `#f' a warning is signaled.

In the following procedures ARITIES is a list of symbols.  The elements
of `arities' can be:

`single'
     Requires a single parameter.

`optional'
     A single parameter or no parameter is acceptable.

`boolean'
     A single boolean parameter or zero parameters is acceptable.

`nary'
     Any number of parameters are acceptable.

`nary1'
     One or more of parameters are acceptable.

 -- Function: parameter-list->arglist positions arities parameter-list
     Returns PARAMETER-LIST converted to an argument list.  Parameters
     of ARITY type `single' and `boolean' are converted to the single
     value associated with them.  The other ARITY types are converted
     to lists of the value(s).

     POSITIONS is a list of positive integers whose order matches the
     order of the PARAMETER-NAMEs in the call to `make-parameter-list'
     which created PARAMETER-LIST.  The integers specify in which
     argument position the corresponding parameter should appear.


File: slib.info,  Node: Getopt Parameter lists,  Next: Filenames,  Prev: Parameter lists,  Up: Programs and Arguments

4.4.5 Getopt Parameter lists
----------------------------

`(require 'getopt-parameters)' 

 -- Function: getopt->parameter-list optnames arities types aliases
          desc ...
     Returns *ARGV* converted to a parameter-list.  OPTNAMES are the
     parameter-names.  ARITIES and TYPES are lists of symbols
     corresponding to OPTNAMES.

     ALIASES is a list of lists of strings or integers paired with
     elements of OPTNAMES.  Each one-character string will be treated
     as a single `-' option by `getopt'.  Longer strings will be
     treated as long-named options (*note getopt-: Getopt.).

     If the ALIASES association list has only strings as its `car's,
     then all the option-arguments after an option (and before the next
     option) are adjoined to that option.

     If the ALIASES association list has integers, then each (string)
     option will take at most one option-argument.  Unoptioned
     arguments are collected in a list.  A `-1' alias will take the
     last argument in this list; `+1' will take the first argument in
     the list.  The aliases -2 then +2; -3 then +3; ... are tried so
     long as a positive or negative consecutive alias is found and
     arguments remain in the list.  Finally a `0' alias, if found,
     absorbs any remaining arguments.

     In all cases, if unclaimed arguments remain after processing, a
     warning is signaled and #f is returned.

 -- Function: getopt->arglist optnames positions arities types
          defaulters checks aliases desc ...
     Like `getopt->parameter-list', but converts *ARGV* to an
     argument-list as specified by OPTNAMES, POSITIONS, ARITIES, TYPES,
     DEFAULTERS, CHECKS, and ALIASES.  If the options supplied violate
     the ARITIES or CHECKS constraints, then a warning is signaled and
     #f is returned.

These `getopt' functions can be used with SLIB relational databases.
For an example, *Note make-command-server: Using Databases.

If errors are encountered while processing options, directions for using
the options (and argument strings DESC ...) are printed to
`current-error-port'.

     (begin
       (set! *optind* 1)
       (set! *argv* '("cmd" "-?")
       (getopt->parameter-list
        '(flag number symbols symbols string flag2 flag3 num2 num3)
        '(boolean optional nary1 nary single boolean boolean nary nary)
        '(boolean integer symbol symbol string boolean boolean integer integer)
        '(("flag" flag)
          ("f" flag)
          ("Flag" flag2)
          ("B" flag3)
          ("optional" number)
          ("o" number)
          ("nary1" symbols)
          ("N" symbols)
          ("nary" symbols)
          ("n" symbols)
          ("single" string)
          ("s" string)
          ("a" num2)
          ("Abs" num3))))
     -|
     Usage: cmd [OPTION ARGUMENT ...] ...

       -f, --flag
       -o, --optional=<number>
       -n, --nary=<symbols> ...
       -N, --nary1=<symbols> ...
       -s, --single=<string>
           --Flag
       -B
       -a        <num2> ...
           --Abs=<num3> ...

     ERROR: getopt->parameter-list "unrecognized option" "-?"


File: slib.info,  Node: Filenames,  Next: Batch,  Prev: Getopt Parameter lists,  Up: Programs and Arguments

4.4.6 Filenames
---------------

`(require 'filename)'                                                         |

 -- Function: filename:match?? pattern
 -- Function: filename:match-ci?? pattern
     Returns a predicate which returns a non-false value if its string
     argument matches (the string) PATTERN, false otherwise.  Filename
     matching is like "glob" expansion described the bash manpage,
     except that names beginning with `.' are matched and `/'
     characters are not treated specially.

     These functions interpret the following characters specially in
     PATTERN strings:
    `*'
          Matches any string, including the null string.

    `?'
          Matches any single character.

    `[...]'
          Matches any one of the enclosed characters.  A pair of
          characters separated by a minus sign (-) denotes a range; any
          character lexically between those two characters, inclusive,
          is matched.  If the first character following the `[' is a
          `!' or a `^' then any character not enclosed is matched.  A
          `-' or `]' may be matched by including it as the first or
          last character in the set.

 -- Function: filename:substitute?? pattern template
 -- Function: filename:substitute-ci?? pattern template
     Returns a function transforming a single string argument according
     to glob patterns PATTERN and TEMPLATE.  PATTERN and TEMPLATE must
     have the same number of wildcard specifications, which need not be
     identical.  PATTERN and TEMPLATE may have a different number of
     literal sections. If an argument to the function matches PATTERN
     in the sense of `filename:match??' then it returns a copy of
     TEMPLATE in which each wildcard specification is replaced by the
     part of the argument matched by the corresponding wildcard
     specification in PATTERN.  A `*' wildcard matches the longest
     leftmost string possible.  If the argument does not match PATTERN
     then false is returned.

     TEMPLATE may be a function accepting the same number of string
     arguments as there are wildcard specifications in PATTERN.  In the
     case of a match the result of applying TEMPLATE to a list of the
     substrings matched by wildcard specifications will be returned,
     otherwise TEMPLATE will not be called and `#f' will be returned.

     ((filename:substitute?? "scm_[0-9]*.html" "scm5c4_??.htm")
      "scm_10.html")
     => "scm5c4_10.htm"
     ((filename:substitute?? "??" "beg?mid?end") "AZ")
     => "begAmidZend"
     ((filename:substitute?? "*na*" "?NA?") "banana")
     => "banaNA"
     ((filename:substitute?? "?*?" (lambda (s1 s2 s3) (string-append s3 s1)))
      "ABZ")
     => "ZA"

 -- Function: replace-suffix str old new
     STR can be a string or a list of strings.  Returns a new string
     (or strings) similar to `str' but with the suffix string OLD
     removed and the suffix string NEW appended.  If the end of STR
     does not match OLD, an error is signaled.

     (replace-suffix "/usr/local/lib/slib/batch.scm" ".scm" ".c")
     => "/usr/local/lib/slib/batch.c"

 -- Function: call-with-tmpnam proc k
 -- Function: call-with-tmpnam proc
     Calls PROC with K arguments, strings returned by successive calls
     to `tmpnam'.  If PROC returns, then any files named by the
     arguments to PROC are deleted automatically and the value(s)
     yielded by the PROC is(are) returned.  K may be ommited, in which
     case it defaults to `1'.

 -- Function: call-with-tmpnam proc suffix1 ...
     Calls PROC with strings returned by successive calls to `tmpnam',
     each with the corresponding SUFFIX string appended.  If PROC
     returns, then any files named by the arguments to PROC are deleted
     automatically and the value(s) yielded by the PROC is(are)
     returned.


File: slib.info,  Node: Batch,  Prev: Filenames,  Up: Programs and Arguments

4.4.7 Batch
-----------

`(require 'batch)' 

The batch procedures provide a way to write and execute portable scripts
for a variety of operating systems.  Each `batch:' procedure takes as
its first argument a parameter-list (*note Parameter lists::).  This
parameter-list argument PARMS contains named associations.  Batch
currently uses 2 of these:

`batch-port'
     The port on which to write lines of the batch file.

`batch-dialect'
     The syntax of batch file to generate.  Currently supported are:
        * unix

        * dos

        * vms

        * amigaos

        * system

        * *unknown*

The `batch' module uses 2 enhanced relational tables (*note Using
Databases::) to store information linking the names of
`operating-system's to `batch-dialect'es.

 -- Function: batch:initialize! database
     Defines `operating-system' and `batch-dialect' tables and adds the
     domain `operating-system' to the enhanced relational database
     DATABASE.

 -- Variable: *operating-system*
     Is batch's best guess as to which operating-system it is running
     under.  `*operating-system*' is set to `(software-type)' (*note
     Configuration::) unless `(software-type)' is `unix', in which case
     finer distinctions are made.

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

The rest of the `batch:' procedures write (or execute if
`batch-dialect' is `system') commands to the batch port which has been
added to PARMS or `(copy-tree PARMS)' by the code:

     (adjoin-parameters! PARMS (list 'batch-port PORT))

 -- Function: batch:command parms string1 string2 ...
     Calls `batch:try-command' (below) with arguments, but signals an
     error if `batch:try-command' returns `#f'.

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

 -- Function: batch:try-command parms string1 string2 ...
     Writes a command to the `batch-port' in PARMS which executes the
     program named STRING1 with arguments STRING2 ....

 -- Function: batch:try-chopped-command parms arg1 arg2 ... list
     breaks the last argument LIST into chunks small enough so that the
     command:

          ARG1 ARG2 ... CHUNK

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

     `batch:try-chopped-command' calls `batch:try-command' with the
     command and returns non-false only if the commands all fit and
     `batch:try-command' of each command line returned non-false.

 -- Function: batch:run-script parms string1 string2 ...
     Writes a command to the `batch-port' in PARMS which executes the
     batch script named STRING1 with arguments STRING2 ....

     _Note:_ `batch:run-script' and `batch:try-command' are not the
     same for some operating systems (VMS).

 -- Function: batch:comment parms line1 ...
     Writes comment lines LINE1 ... to the `batch-port' in PARMS.

 -- Function: batch:lines->file parms file line1 ...
     Writes commands to the `batch-port' in PARMS which create a file
     named FILE with contents LINE1 ....

 -- Function: batch:delete-file parms file
     Writes a command to the `batch-port' in PARMS which deletes the
     file named FILE.

 -- Function: batch:rename-file parms old-name new-name
     Writes a command to the `batch-port' in PARMS which renames the
     file OLD-NAME to NEW-NAME.

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

 -- Function: truncate-up-to path char
 -- Function: truncate-up-to path string
 -- Function: truncate-up-to path charlist
     PATH can be a string or a list of strings.  Returns PATH sans any
     prefixes ending with a character of the second argument.  This can
     be used to derive a filename moved locally from elsewhere.

          (truncate-up-to "/usr/local/lib/slib/batch.scm" "/")
          => "batch.scm"

 -- Function: string-join joiner string1 ...
     Returns a new string consisting of all the strings STRING1 ...  in
     order appended together with the string JOINER between each
     adjacent pair.

 -- Function: must-be-first list1 list2
     Returns a new list consisting of the elements of LIST2 ordered so
     that if some elements of LIST1 are `equal?' to elements of LIST2,
     then those elements will appear first and in the order of LIST1.

 -- Function: must-be-last list1 list2
     Returns a new list consisting of the elements of LIST1 ordered so
     that if some elements of LIST2 are `equal?' to elements of LIST1,
     then those elements will appear last and in the order of LIST2.

 -- Function: os->batch-dialect osname
     Returns its best guess for the `batch-dialect' to be used for the
     operating-system named OSNAME.  `os->batch-dialect' uses the
     tables added to DATABASE by `batch:initialize!'.

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

     (require 'databases)
     (require 'parameters)
     (require 'batch)
     (require 'filename)                                                      |
     
     (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")
         )))

Produces the file `my-batch':

     #! /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

When run, `my-batch' prints:

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


File: slib.info,  Node: HTML,  Next: HTML Tables,  Prev: Programs and Arguments,  Up: Textual Conversion Packages

4.5 HTML
========

`(require 'html-form)' 

 -- Function: html:atval txt
     Returns a string with character substitutions appropriate to send
     TXT as an "attribute-value".  

 -- Function: html:plain txt
     Returns a string with character substitutions appropriate to send
     TXT as an "plain-text".  

 -- Function: html:meta name content
     Returns a tag of meta-information suitable for passing as the
     third argument to `html:head'.  The tag produced is `<META
     NAME="NAME" CONTENT="CONTENT">'.  The string or symbol NAME can be
     `author', `copyright', `keywords', `description', `date',
     `robots', ....

 -- Function: html:http-equiv name content
     Returns a tag of HTTP information suitable for passing as the
     third argument to `html:head'.  The tag produced is `<META
     HTTP-EQUIV="NAME" CONTENT="CONTENT">'.  The string or symbol NAME
     can be `Expires', `PICS-Label', `Content-Type', `Refresh', ....

 -- Function: html:meta-refresh delay uri
 -- Function: html:meta-refresh delay
     Returns a tag suitable for passing as the third argument to
     `html:head'.  If URI argument is supplied, then DELAY seconds after
     displaying the page with this tag, Netscape or IE browsers will
     fetch and display URI.  Otherwise, DELAY seconds after displaying
     the page with this tag, Netscape or IE browsers will fetch and
     redisplay this page.

 -- Function: html:head title backlink tags ...
 -- Function: html:head title backlink
 -- Function: html:head title
     Returns header string for an HTML page named TITLE.  If BACKLINK
     is a string, it is used verbatim between the `H1' tags; otherwise
     TITLE is used.  If string arguments TAGS ... are supplied, then
     they are included verbatim within the <HEAD> section.

 -- Function: html:body body ...
     Returns HTML string to end a page.

 -- Function: html:pre line1 line ...
     Returns the strings LINE1, LINES as "PRE"formmated plain text (rendered
     in fixed-width font).  Newlines are inserted between LINE1, LINES.
     HTML tags (`<tag>') within LINES will be visible verbatim.

 -- Function: html:comment line1 line ...
     Returns the strings LINE1 as HTML comments.

4.6 HTML Forms
==============

 -- Function: html:form method action body ...
     The symbol METHOD is either `get', `head', `post', `put', or
     `delete'.  The strings BODY form the body of the form.
     `html:form' returns the HTML "form".  

 -- Function: html:hidden name value
     Returns HTML string which will cause NAME=VALUE in form.

 -- Function: html:checkbox pname default
     Returns HTML string for check box.

 -- Function: html:text pname default size ...
     Returns HTML string for one-line text box.

 -- Function: html:text-area pname default-list
     Returns HTML string for multi-line text box.

 -- Function: html:select pname arity default-list foreign-values
     Returns HTML string for pull-down menu selector.

 -- Function: html:buttons pname arity default-list foreign-values
     Returns HTML string for any-of selector.

 -- Function: form:submit submit-label command
 -- Function: form:submit submit-label
     The string or symbol SUBMIT-LABEL appears on the button which
     submits the form.  If the optional second argument COMMAND is
     given, then `*command*=COMMAND' and `*button*=SUBMIT-LABEL' are
     set in the query.  Otherwise, `*command*=SUBMIT-LABEL' is set in
     the query.

 -- Function: form:image submit-label image-src
     The IMAGE-SRC appears on the button which submits the form.

 -- Function: form:reset
     Returns a string which generates a "reset" button.  

 -- Function: form:element pname arity default-list foreign-values
     Returns a string which generates an INPUT element for the field
     named PNAME.  The element appears in the created form with its
     representation determined by its ARITY and domain.  For domains
     which are foreign-keys:

    `single'
          select menu

    `optional'
          select menu

    `nary'
          check boxes

    `nary1'
          check boxes

     If the foreign-key table has a field named `visible-name', then
     the contents of that field are the names visible to the user for
     those choices.  Otherwise, the foreign-key itself is visible.

     For other types of domains:

    `single'
          text area

    `optional'
          text area

    `boolean'
          check box

    `nary'
          text area

    `nary1'
          text area

 -- Function: form:delimited pname doc aliat arity default-list
          foreign-values
     Returns a HTML string for a form element embedded in a line of a
     delimited list.  Apply map `form:delimited' to the list returned by
     `command->p-specs'.

 -- Function: html:delimited-list row ...
     Wraps its arguments with delimited-list (`DL' command.

 -- Function: get-foreign-choices tab
     Returns a list of the `visible-name' or first fields of table TAB.

 -- Function: command->p-specs rdb command-table command
     The symbol COMMAND-TABLE names a command table in the RDB
     relational database.  The symbol COMMAND names a key in
     COMMAND-TABLE.

     `command->p-specs' returns a list of lists of PNAME, DOC, ALIAT,
     ARITY, DEFAULT-LIST, and FOREIGN-VALUES.  The returned list has
     one element for each parameter of command COMMAND.

     This example demonstrates how to create a HTML-form for the `build'
     command.

          (require (in-vicinity (implementation-vicinity) "build.scm"))
          (call-with-output-file "buildscm.html"
            (lambda (port)
              (display
               (string-append
                (html:head 'commands)
                (html:body
                 (sprintf #f "<H2>%s:</H2><BLOCKQUOTE>%s</BLOCKQUOTE>\\n"
                          (html:plain 'build)
                          (html:plain ((comtab 'get 'documentation) 'build)))
                 (html:form
                  'post
                  (or "http://localhost:8081/buildscm" "/cgi-bin/build.cgi")
                  (apply html:delimited-list
                         (apply map form:delimited
                                (command->p-specs build '*commands* 'build)))
                  (form:submit 'build)
                  (form:reset))))
               port)))


File: slib.info,  Node: HTML Tables,  Next: HTTP and CGI,  Prev: HTML,  Up: Textual Conversion Packages

4.7 HTML Tables
===============

`(require 'db->html)' 

 -- Function: html:table options row ...

 -- Function: html:caption caption align
 -- Function: html:caption caption
     ALIGN can be `top' or `bottom'.

 -- Function: html:heading columns
     Outputs a heading row for the currently-started table.

 -- Function: html:href-heading columns uris
     Outputs a heading row with column-names COLUMNS linked to URIs
     URIS.

 -- Function: html:linked-row-converter k foreigns
     The positive integer K is the primary-key-limit (number of
     primary-keys) of the table.  FOREIGNS is a list of the filenames of
     foreign-key field pages and #f for non foreign-key fields.

     `html:linked-row-converter' returns a procedure taking a row for
     its single argument.  This returned procedure returns the html
     string for that table row.

 -- Function: table-name->filename table-name
     Returns the symbol TABLE-NAME converted to a filename.

 -- Function: table->linked-html caption db table-name match-key1 ...
     Returns HTML string for DB table TABLE-NAME chopped into 50-row
     HTML tables.  Every foreign-key value is linked to the page (of
     the table) defining that key.

     The optional MATCH-KEY1 ... arguments restrict actions to a subset
     of the table.  *Note match-key: Table Operations.

 -- Function: table->linked-page db table-name index-filename arg ...
     Returns a complete HTML page.  The string INDEX-FILENAME names the
     page which refers to this one.

     The optional ARGS ... arguments restrict actions to a subset of
     the table.  *Note match-key: Table Operations.

 -- Function: catalog->html db caption arg ...
     Returns HTML string for the catalog table of DB.

4.7.1 HTML editing tables
-------------------------

A client can modify one row of an editable table at a time.  For any
change submitted, these routines check if that row has been modified
during the time the user has been editing the form.  If so, an error
page results.

The behavior of edited rows is:

   * If no fields are changed, then no change is made to the table.

   * If the primary keys equal null-keys (parameter defaults), and no
     other user has modified that row, then that row is deleted.

   * If only primary keys are changed, there are non-key fields, and no
     row with the new keys is in the table, then the old row is deleted
     and one with the new keys is inserted.

   * If only non-key fields are changed, and that row has not been
     modified by another user, then the row is changed to reflect the
     fields.

   * If both keys and non-key fields are changed, and no row with the
     new keys is in the table, then a row is created with the new keys
     and fields.

   * If fields are changed, all fields are primary keys, and no row with
     the new keys is in the table, then a row is created with the new
     keys.

After any change to the table, a `sync-database' of the database is
performed.

 -- Function: command:modify-table table-name null-keys update delete
          retrieve
 -- Function: command:modify-table table-name null-keys update delete
 -- Function: command:modify-table table-name null-keys update
 -- Function: command:modify-table table-name null-keys
     Returns procedure (of DB) which returns procedure to modify row of
     TABLE-NAME.  NULL-KEYS is the list of "null" keys indicating the
     row is to be deleted when any matches its corresponding primary
     key.  Optional arguments UPDATE, DELETE, and RETRIEVE default to
     the `row:update', `row:delete', and `row:retrieve' of TABLE-NAME
     in DB.

 -- Function: command:make-editable-table rdb table-name arg ...
     Given TABLE-NAME in RDB, creates parameter and `*command*' tables
     for editing one row of TABLE-NAME at a time.
     `command:make-editable-table' returns a procedure taking a row
     argument which returns the HTML string for editing that row.

     Optional ARGS are expressions (lists) added to the call to
     `command:modify-table'.

     The domain name of a column determines the expected arity of the
     data stored in that column.  Domain names ending in:

    `*'
          have arity `nary';

    `+'
          have arity `nary1'.

 -- Function: html:editable-row-converter k names edit-point
          edit-converter
     The positive integer K is the primary-key-limit (number of
     primary-keys) of the table.  NAMES is a list of the field-names.
     EDIT-POINT is the list of primary-keys denoting the row to edit
     (or #f).  EDIT-CONVERTER is the procedure called with K, NAMES,
     and the row to edit.

     `html:editable-row-converter' returns a procedure taking a row for
     its single argument.  This returned procedure returns the html
     string for that table row.

     Each HTML table constructed using `html:editable-row-converter'
     has first K fields (typically the primary key fields) of each row
     linked to a text encoding of these fields (the result of calling
     `row->anchor').  The page so referenced typically allows the user
     to edit fields of that row.

4.7.2 HTML databases
--------------------

 -- Function: db->html-files db dir index-filename caption
     DB must be a relational database.  DIR must be #f or a non-empty
     string naming an existing sub-directory of the current directory.

     `db->html-files' creates an html page for each table in the
     database DB in the sub-directory named DIR, or the current
     directory if DIR is #f.  The top level page with the catalog of
     tables (captioned CAPTION) is written to a file named
     INDEX-FILENAME.

 -- Function: db->html-directory db dir index-filename
 -- Function: db->html-directory db dir
     DB must be a relational database.  DIR must be a non-empty string
     naming an existing sub-directory of the current directory or one
     to be created.  The optional string INDEX-FILENAME names the
     filename of the top page, which defaults to `index.html'.

     `db->html-directory' creates sub-directory DIR if neccessary, and
     calls `(db->html-files DB DIR INDEX-FILENAME DIR)'.  The `file:'
     URI of INDEX-FILENAME is returned.

 -- Function: db->netscape db dir index-filename
 -- Function: db->netscape db dir
     `db->netscape' is just like `db->html-directory', but calls
     `browse-url' with the uri for the top page after the pages are
     created.


File: slib.info,  Node: HTTP and CGI,  Next: Parsing HTML,  Prev: HTML Tables,  Up: Textual Conversion Packages

4.8 HTTP and CGI
================

`(require 'http)' or `(require 'cgi)' 

 -- Function: http:header alist
     Returns a string containing lines for each element of ALIST; the
     `car' of which is followed by `: ', then the `cdr'.

 -- Function: http:content alist body ...
     Returns the concatenation of strings BODY with the `(http:header
     ALIST)' and the `Content-Length' prepended.

 -- Variable: *http:byline*
     String appearing at the bottom of error pages.

 -- Function: http:error-page status-code reason-phrase html-string ...
     STATUS-CODE and REASON-PHRASE should be an integer and string as
     specified in `RFC 2068'.  The returned page (string) will show the
     STATUS-CODE and REASON-PHRASE and any additional HTML-STRINGS ...;
     with *HTTP:BYLINE* or SLIB's default at the bottom.

 -- Function: http:forwarding-page title dly uri html-string ...
     The string or symbol TITLE is the page title.  DLY is a
     non-negative integer.  The HTML-STRINGS ... are typically used to
     explain to the user why this page is being forwarded.

     `http:forwarding-page' returns an HTML string for a page which
     automatically forwards to URI after DLY seconds.  The returned
     page (string) contains any HTML-STRINGS ... followed by a manual
     link to URI, in case the browser does not forward automatically.

 -- Function: http:serve-query serve-proc input-port output-port
     reads the "URI" and "query-string" from INPUT-PORT.  If the query
     is a valid `"POST"' or `"GET"' query, then `http:serve-query' calls
     SERVE-PROC with three arguments, the REQUEST-LINE, QUERY-STRING,
     and HEADER-ALIST.  Otherwise, `http:serve-query' calls SERVE-PROC
     with the REQUEST-LINE, #f, and HEADER-ALIST.

     If SERVE-PROC returns a string, it is sent to OUTPUT-PORT.  If
     SERVE-PROC returns a list, then an error page with number 525 and
     strings from the list.  If SERVE-PROC returns #f, then a `Bad
     Request' (400) page is sent to OUTPUT-PORT.

     Otherwise, `http:serve-query' replies (to OUTPUT-PORT) with
     appropriate HTML describing the problem.

  This example services HTTP queries from PORT-NUMBER:

     (define socket (make-stream-socket AF_INET 0))
     (and (socket:bind socket port-number) ; AF_INET INADDR_ANY
          (socket:listen socket 10)        ; Queue up to 10 requests.
          (dynamic-wind
              (lambda () #f)
              (lambda ()
                (do ((port (socket:accept socket) (socket:accept socket)))
                    (#f)
                  (let ((iport (duplicate-port port "r"))
                        (oport (duplicate-port port "w")))
                    (http:serve-query build:serve iport oport)
                    (close-port iport)
                    (close-port oport))
                  (close-port port)))
              (lambda () (close-port socket))))

 -- Function: cgi:serve-query serve-proc
     reads the "URI" and "query-string" from `(current-input-port)'.
     If the query is a valid `"POST"' or `"GET"' query, then
     `cgi:serve-query' calls SERVE-PROC with three arguments, the
     REQUEST-LINE, QUERY-STRING, and HEADER-ALIST.  Otherwise,
     `cgi:serve-query' calls SERVE-PROC with the REQUEST-LINE, #f, and
     HEADER-ALIST.

     If SERVE-PROC returns a string, it is sent to
     `(current-input-port)'.  If SERVE-PROC returns a list, then an
     error page with number 525 and strings from the list.  If
     SERVE-PROC returns #f, then a `Bad Request' (400) page is sent to
     `(current-input-port)'.

     Otherwise, `cgi:serve-query' replies (to `(current-input-port)')
     with appropriate HTML describing the problem.

 -- Function: make-query-alist-command-server rdb command-table
 -- Function: make-query-alist-command-server rdb command-table #t
     Returns a procedure of one argument.  When that procedure is called
     with a QUERY-ALIST (as returned by `uri:decode-query', the value
     of the `*command*' association will be the command invoked in
     COMMAND-TABLE.  If `*command*' is not in the QUERY-ALIST then the
     value of `*suggest*' is tried.  If neither name is in the
     QUERY-ALIST, then the literal value `*default*' is tried in
     COMMAND-TABLE.

     If optional third argument is non-false, then the command is called
     with just the parameter-list; otherwise, command is called with the
     arguments described in its table.


File: slib.info,  Node: Parsing HTML,  Next: URI,  Prev: HTTP and CGI,  Up: Textual Conversion Packages

4.9 Parsing HTML
================

`(require 'html-for-each)' 

 -- Function: html-for-each file word-proc markup-proc white-proc
          newline-proc
     FILE is an input port or a string naming an existing file
     containing HTML text.  WORD-PROC is a procedure of one argument or
     #f.  MARKUP-PROC is a procedure of one argument or #f.  WHITE-PROC
     is a procedure of one argument or #f.  NEWLINE-PROC is a procedure
     of no arguments or #f.

     `html-for-each' opens and reads characters from port FILE or the
     file named by string FILE.  Sequential groups of characters are
     assembled into strings which are either

        * enclosed by `<' and `>' (hypertext markups or comments);

        * end-of-line;

        * whitespace; or

        * none of the above (words).

     Procedures are called according to these distinctions in order of
     the string's occurrence in FILE.

     NEWLINE-PROC is called with no arguments for end-of-line _not
     within a markup or comment_.

     WHITE-PROC is called with strings of non-newline whitespace.

     MARKUP-PROC is called with hypertext markup strings (including `<'
     and `>').

     WORD-PROC is called with the remaining strings.

     `html-for-each' returns an unspecified value.

 -- Function: html:read-title file limit
 -- Function: html:read-title file
     FILE is an input port or a string naming an existing file
     containing HTML text.  If supplied, LIMIT must be an integer.
     LIMIT defaults to 1000.

     `html:read-title' opens and reads HTML from port FILE or the file
     named by string FILE, until reaching the (mandatory) `TITLE'
     field.  `html:read-title' returns the title string with adjacent
     whitespaces collapsed to one space.  `html:read-title' returns #f
     if the title field is empty, absent, if the first character read
     from FILE is not `#\<', or if the end of title is not found within
     the first (approximately) LIMIT words.

 -- Function: htm-fields htm
     HTM is a hypertext markup string.

     If HTM is a (hypertext) comment, then `htm-fields' returns #f.
     Otherwise `htm-fields' returns the hypertext element symbol
     (created by `string-ci->symbol') consed onto an association list
     of the attribute name-symbols and values.  Each value is a number
     or string; or #t if the name had no value assigned within the
     markup.


File: slib.info,  Node: URI,  Next: Parsing XML,  Prev: Parsing HTML,  Up: Textual Conversion Packages

4.10 URI
========

`(require 'uri)' 

Implements "Uniform Resource Identifiers" (URI) as described in RFC
2396.

 -- Function: make-uri
 -- Function: make-uri fragment
 -- Function: make-uri query fragment
 -- Function: make-uri path query fragment
 -- Function: make-uri authority path query fragment
 -- Function: make-uri scheme authority path query fragment
     Returns a Uniform Resource Identifier string from component
     arguments.

 -- Function: uri:make-path path
     Returns a URI string combining the components of list PATH.

 -- Function: html:anchor name
     Returns a string which defines this location in the (HTML) file as
     NAME.  The hypertext `<A HREF="#NAME">' will link to this point.

          (html:anchor "(section 7)")
          =>
          "<A NAME=\"(section%207)\"></A>"

 -- Function: html:link uri highlighted
     Returns a string which links the HIGHLIGHTED text to URI.

          (html:link (make-uri "(section 7)") "section 7")
          =>
          "<A HREF=\"#(section%207)\">section 7</A>"

 -- Function: html:base uri
     Returns a string specifying the "base" URI of a document, for inclusion
     in the HEAD of the document (*note head: HTML.).

 -- Function: html:isindex prompt
     Returns a string specifying the search PROMPT of a document, for
     inclusion in the HEAD of the document (*note head: HTML.).

 -- Function: uri->tree uri-reference base-tree
 -- Function: uri->tree uri-reference
     Returns a list of 5 elements corresponding to the parts (SCHEME
     AUTHORITY PATH QUERY FRAGMENT) of string URI-REFERENCE.  Elements
     corresponding to absent parts are #f.

     The PATH is a list of strings.  If the first string is empty, then
     the path is absolute; otherwise relative.  The optional BASE-TREE
     is a tree as returned by `uri->tree'; and is used as the base
     address for relative URIs.

     If the AUTHORITY component is a "Server-based Naming Authority",
     then it is a list of the USERINFO, HOST, and PORT strings (or #f).
     For other types of AUTHORITY components the AUTHORITY will be a
     string.

          (uri->tree "http://www.ics.uci.edu/pub/ietf/uri/#Related")
          =>
          (http "www.ics.uci.edu" ("" "pub" "ietf" "uri" "") #f "Related")

 -- Function: uri:split-fields txt chr
     Returns a list of TXT split at each occurrence of CHR.  CHR does
     not appear in the returned list of strings.

 -- Function: uri:decode-query query-string
     Converts a "URI" encoded QUERY-STRING to a query-alist.  

`uric:' prefixes indicate procedures dealing with URI-components.

 -- Function: uric:encode uri-component allows
     Returns a copy of the string URI-COMPONENT in which all "unsafe"
     octets (as defined in RFC 2396) have been `%' "escaped".  `uric:decode'
     decodes strings encoded by `uric:encode'.

 -- Function: uric:decode uri-component
     Returns a copy of the string URI-COMPONENT in which each `%'
     escaped characters in URI-COMPONENT is replaced with the character
     it encodes.  This routine is useful for showing URI contents on
     error pages.

 -- Function: uri:path->keys path-list ptypes
     PATH-LIST is a path-list as returned by `uri:split-fields'.
     `uri:path->keys' returns a list of items returned by
     `uri:decode-path', coerced to types PTYPES.

File-system Locators and Predicates
-----------------------------------

 -- Function: path->uri path
     Returns a URI-string for PATH on the local host.

 -- Function: absolute-uri? str
     Returns #t if STR is an absolute-URI as indicated by a
     syntactically valid (per RFC 2396) "scheme"; otherwise returns #f.

 -- Function: absolute-path? file-name
     Returns #t if FILE-NAME is a fully specified pathname (does not
     depend on the current working directory); otherwise returns #f.

 -- Function: null-directory? str
     Returns #t if changing directory to STR would leave the current
     directory unchanged; otherwise returns #f.

 -- Function: glob-pattern? str
     Returns #t if the string STR contains characters used for
     specifying glob patterns, namely `*', `?', or `['.

Before RFC 2396, the "File Transfer Protocol" (FTP) served a similar
purpose.

 -- Function: parse-ftp-address uri
     Returns a list of the decoded FTP URI; or #f if indecipherable.
     FTP "Uniform Resource Locator", "ange-ftp", and "getit" formats
     are handled.  The returned list has four elements which are
     strings or #f:

       0. username

       1. password

       2. remote-site

       3. remote-directory


File: slib.info,  Node: Parsing XML,  Next: Printing Scheme,  Prev: URI,  Up: Textual Conversion Packages

4.11 Parsing XML
================

`(require 'xml-parse)' or `(require 'ssax)'

The XML standard document referred to in this module is
`http://www.w3.org/TR/1998/REC-xml-19980210.html'.

The present frameworks fully supports the XML Namespaces Recommendation
`http://www.w3.org/TR/REC-xml-names'.

4.11.1 String Glue
------------------

 -- Function: ssax:reverse-collect-str list-of-frags
     Given the list of fragments (some of which are text strings),
     reverse the list and concatenate adjacent text strings.  If
     LIST-OF-FRAGS has zero or one element, the result of the procedure
     is `equal?' to its argument.

 -- Function: ssax:reverse-collect-str-drop-ws list-of-frags
     Given the list of fragments (some of which are text strings),
     reverse the list and concatenate adjacent text strings while
     dropping "unsignificant" whitespace, that is, whitespace in front,
     behind and between elements.  The whitespace that is included in
     character data is not affected.

     Use this procedure to "intelligently" drop "insignificant"
     whitespace in the parsed SXML.  If the strict compliance with the
     XML Recommendation regarding the whitespace is desired, use the
     `ssax:reverse-collect-str' procedure instead.

4.11.2 Character and Token Functions
------------------------------------

The following functions either skip, or build and return tokens,
according to inclusion or delimiting semantics.  The list of characters
to expect, include, or to break at may vary from one invocation of a
function to another.  This allows the functions to easily parse even
context-sensitive languages.

  Exceptions are mentioned specifically.  The list of expected
characters (characters to skip until, or break-characters) may include
an EOF "character", which is coded as symbol *eof*

  The input stream to parse is specified as a PORT, which is the last
argument.

 -- Function: ssax:assert-current-char char-list string port
     Reads a character from the PORT and looks it up in the CHAR-LIST
     of expected characters.  If the read character was found among
     expected, it is returned.  Otherwise, the procedure writes a
     message using STRING as a comment and quits.

 -- Function: ssax:skip-while char-list port
     Reads characters from the PORT and disregards them, as long as they
     are mentioned in the CHAR-LIST.  The first character (which may be
     EOF) peeked from the stream that is _not_ a member of the
     CHAR-LIST is returned.

 -- Function: ssax:init-buffer
     Returns an initial buffer for `ssax:next-token*' procedures.
     `ssax:init-buffer' may allocate a new buffer at each invocation.

 -- Function: ssax:next-token prefix-char-list break-char-list
          comment-string port
     Skips any number of the prefix characters (members of the
     PREFIX-CHAR-LIST), if any, and reads the sequence of characters up
     to (but not including) a break character, one of the
     BREAK-CHAR-LIST.

     The string of characters thus read is returned.  The break
     character is left on the input stream.  BREAK-CHAR-LIST may
     include the symbol `*eof*'; otherwise, EOF is fatal, generating an
     error message including a specified COMMENT-STRING.

`ssax:next-token-of' is similar to `ssax:next-token' except that it
implements an inclusion rather than delimiting semantics.

 -- Function: ssax:next-token-of inc-charset port
     Reads characters from the PORT that belong to the list of
     characters INC-CHARSET.  The reading stops at the first character
     which is not a member of the set.  This character is left on the
     stream.  All the read characters are returned in a string.

 -- Function: ssax:next-token-of pred port
     Reads characters from the PORT for which PRED (a procedure of one
     argument) returns non-#f.  The reading stops at the first
     character for which PRED returns #f.  That character is left on
     the stream.  All the results of evaluating of PRED up to #f are
     returned in a string.

     PRED is a procedure that takes one argument (a character or the
     EOF object) and returns a character or #f.  The returned character
     does not have to be the same as the input argument to the PRED.
     For example,

          (ssax:next-token-of (lambda (c)
                                (cond ((eof-object? c) #f)
                                      ((char-alphabetic? c) (char-downcase c))
                                      (else #f)))
                              (current-input-port))

     will try to read an alphabetic token from the current input port,
     and return it in lower case.

 -- Function: ssax:read-string len port
     Reads LEN characters from the PORT, and returns them in a string.
     If EOF is encountered before LEN characters are read, a shorter
     string will be returned.

4.11.3 Data Types
-----------------

`TAG-KIND'
     A symbol `START', `END', `PI', `DECL', `COMMENT', `CDSECT', or
     `ENTITY-REF' that identifies a markup token

`UNRES-NAME'
     a name (called GI in the XML Recommendation) as given in an XML
     document for a markup token: start-tag, PI target, attribute name.
     If a GI is an NCName, UNRES-NAME is this NCName converted into a
     Scheme symbol.  If a GI is a QName, `UNRES-NAME' is a pair of
     symbols: `(PREFIX . LOCALPART)'.

`RES-NAME'
     An expanded name, a resolved version of an `UNRES-NAME'.  For an
     element or an attribute name with a non-empty namespace URI,
     `RES-NAME' is a pair of symbols, `(URI-SYMB . LOCALPART)'.
     Otherwise, it's a single symbol.

`ELEM-CONTENT-MODEL'
     A symbol:
    `ANY'
          anything goes, expect an END tag.

    `EMPTY-TAG'
          no content, and no END-tag is coming

    `EMPTY'
          no content, expect the END-tag as the next token

    `PCDATA'
          expect character data only, and no children elements

    `MIXED'

    `ELEM-CONTENT'

`URI-SYMB'
     A symbol representing a namespace URI - or other symbol chosen by
     the user to represent URI.  In the former case, `URI-SYMB' is
     created by %-quoting of bad URI characters and converting the
     resulting string into a symbol.

`NAMESPACES'
     A list representing namespaces in effect.  An element of the list
     has one of the following forms:

    `(PREFIX URI-SYMB . URI-SYMB) or'

    `(PREFIX USER-PREFIX . URI-SYMB)'
          USER-PREFIX is a symbol chosen by the user to represent the
          URI.

    `(#f USER-PREFIX . URI-SYMB)'
          Specification of the user-chosen prefix and a URI-SYMBOL.

    `(*DEFAULT* USER-PREFIX . URI-SYMB)'
          Declaration of the default namespace

    `(*DEFAULT* #f . #f)'
          Un-declaration of the default namespace.  This notation
          represents overriding of the previous declaration


     A NAMESPACES list may contain several elements for the same PREFIX.
     The one closest to the beginning of the list takes effect.

`ATTLIST'
     An ordered collection of (NAME . VALUE) pairs, where NAME is a
     RES-NAME or an UNRES-NAME.  The collection is an ADT.

`STR-HANDLER'
     A procedure of three arguments: STRING1 STRING2 SEED returning a
     new SEED.  The procedure is supposed to handle a chunk of
     character data STRING1 followed by a chunk of character data
     STRING2.  STRING2 is a short string, often `"\n"' and even `""'.

`ENTITIES'
     An assoc list of pairs:
             (NAMED-ENTITY-NAME . NAMED-ENTITY-BODY)

     where NAMED-ENTITY-NAME is a symbol under which the entity was
     declared, NAMED-ENTITY-BODY is either a string, or (for an
     external entity) a thunk that will return an input port (from which
     the entity can be read).  NAMED-ENTITY-BODY may also be #f.  This
     is an indication that a NAMED-ENTITY-NAME is currently being
     expanded.  A reference to this NAMED-ENTITY-NAME will be an error:
     violation of the WFC nonrecursion.

`XML-TOKEN'
     This record represents a markup, which is, according to the XML
     Recommendation, "takes the form of start-tags, end-tags,
     empty-element tags, entity references, character references,
     comments, CDATA section delimiters, document type declarations, and
     processing instructions."

    kind
          a TAG-KIND

    head
          an UNRES-NAME.  For XML-TOKENs of kinds 'COMMENT and 'CDSECT,
          the head is #f.

     For example,
          <P>                   => kind=START,      head=P
          </P>                  => kind=END,        head=P
          <BR/>                 => kind=EMPTY-EL,   head=BR
          <!DOCTYPE OMF ...>    => kind=DECL,       head=DOCTYPE
          <?xml version="1.0"?> => kind=PI,         head=xml
          &my-ent;              => kind=ENTITY-REF, head=my-ent

     Character references are not represented by xml-tokens as these
     references are transparently resolved into the corresponding
     characters.

`XML-DECL'
     The record represents a datatype of an XML document: the list of
     declared elements and their attributes, declared notations, list of
     replacement strings or loading procedures for parsed general
     entities, etc.  Normally an XML-DECL record is created from a DTD
     or an XML Schema, although it can be created and filled in in many
     other ways (e.g., loaded from a file).

    ELEMS
          an (assoc) list of decl-elem or #f.  The latter instructs the
          parser to do no validation of elements and attributes.

    DECL-ELEM
          declaration of one element:

          `(ELEM-NAME ELEM-CONTENT DECL-ATTRS)'

          ELEM-NAME is an UNRES-NAME for the element.

          ELEM-CONTENT is an ELEM-CONTENT-MODEL.

          DECL-ATTRS is an `ATTLIST', of `(ATTR-NAME . VALUE)'
          associations.

          This element can declare a user procedure to handle parsing
          of an element (e.g., to do a custom validation, or to build a
          hash of IDs as they're encountered).

    DECL-ATTR
          an element of an `ATTLIST', declaration of one attribute:

          `(ATTR-NAME CONTENT-TYPE USE-TYPE DEFAULT-VALUE)'

          ATTR-NAME is an UNRES-NAME for the declared attribute.

          CONTENT-TYPE is a symbol: `CDATA', `NMTOKEN', `NMTOKENS', ...
          or a list of strings for the enumerated type.

          USE-TYPE is a symbol: `REQUIRED', `IMPLIED', or `FIXED'.

          DEFAULT-VALUE is a string for the default value, or #f if not
          given.



4.11.4 Low-Level Parsers and Scanners
-------------------------------------

These procedures deal with primitive lexical units (Names, whitespaces,
tags) and with pieces of more generic productions.  Most of these
parsers must be called in appropriate context.  For example,
`ssax:complete-start-tag' must be called only when the start-tag has
been detected and its GI has been read.

 -- Function: ssax:skip-s port
     Skip the S (whitespace) production as defined by
          [3] S ::= (#x20 | #x09 | #x0D | #x0A)

     `ssax:skip-s' returns the first not-whitespace character it
     encounters while scanning the PORT.  This character is left on the
     input stream.

 -- Function: ssax:read-ncname port
     Read a NCName starting from the current position in the PORT and
     return it as a symbol.

          [4] NameChar ::= Letter | Digit | '.' | '-' | '_' | ':'
                           | CombiningChar | Extender
          [5] Name ::= (Letter | '_' | ':') (NameChar)*

     This code supports the XML Namespace Recommendation REC-xml-names,
     which modifies the above productions as follows:

          [4] NCNameChar ::= Letter | Digit | '.' | '-' | '_'
                                | CombiningChar | Extender
          [5] NCName ::= (Letter | '_') (NCNameChar)*

     As the Rec-xml-names says,

          "An XML document conforms to this specification if all other
          tokens [other than element types and attribute names] in the
          document which are required, for XML conformance, to match
          the XML production for Name, match this specification's
          production for NCName."

     Element types and attribute names must match the production QName,
     defined below.

 -- Function: ssax:read-qname port
     Read a (namespace-) Qualified Name, QName, from the current
     position in PORT; and return an UNRES-NAME.

     From REC-xml-names:
          [6] QName ::= (Prefix ':')? LocalPart
          [7] Prefix ::= NCName
          [8] LocalPart ::= NCName

 -- Function: ssax:read-markup-token port
     This procedure starts parsing of a markup token.  The current
     position in the stream must be `<'.  This procedure scans enough
     of the input stream to figure out what kind of a markup token it
     is seeing.  The procedure returns an XML-TOKEN structure
     describing the token.  Note, generally reading of the current
     markup is not finished!  In particular, no attributes of the
     start-tag token are scanned.

     Here's a detailed break out of the return values and the position
     in the PORT when that particular value is returned:

    PI-token
          only PI-target is read.  To finish the Processing-Instruction
          and disregard it, call `ssax:skip-pi'.  `ssax:read-attributes'
          may be useful as well (for PIs whose content is
          attribute-value pairs).

    END-token
          The end tag is read completely; the current position is right
          after the terminating `>' character.

    COMMENT
          is read and skipped completely.  The current position is
          right after `-->' that terminates the comment.

    CDSECT
          The current position is right after `<!CDATA['.  Use
          `ssax:read-cdata-body' to read the rest.

    DECL
          We have read the keyword (the one that follows `<!')
          identifying this declaration markup.  The current position is
          after the keyword (usually a whitespace character)

    START-token
          We have read the keyword (GI) of this start tag.  No
          attributes are scanned yet.  We don't know if this tag has an
          empty content either.  Use `ssax:complete-start-tag' to
          finish parsing of the token.


 -- Function: ssax:skip-pi port
     The current position is inside a PI.  Skip till the rest of the PI

 -- Function: ssax:read-pi-body-as-string port
     The current position is right after reading the PITarget.  We read
     the body of PI and return is as a string.  The port will point to
     the character right after `?>' combination that terminates PI.

          [16] PI ::= '<?' PITarget (S (Char* - (Char* '?>' Char*)))? '?>'

 -- Function: ssax:skip-internal-dtd port
     The current pos in the port is inside an internal DTD subset (e.g.,
     after reading `#\[' that begins an internal DTD subset) Skip until
     the `]>' combination that terminates this DTD.

 -- Function: ssax:read-cdata-body port str-handler seed
     This procedure must be called after we have read a string
     `<![CDATA[' that begins a CDATA section.  The current position
     must be the first position of the CDATA body.  This function reads
     _lines_ of the CDATA body and passes them to a STR-HANDLER, a
     character data consumer.

     STR-HANDLER is a procedure taking arguments: STRING1, STRING2, and
     SEED.  The first STRING1 argument to STR-HANDLER never contains a
     newline; the second STRING2 argument often will.  On the first
     invocation of STR-HANDLER, SEED is the one passed to
     `ssax:read-cdata-body' as the third argument.  The result of this
     first invocation will be passed as the SEED argument to the second
     invocation of the line consumer, and so on.  The result of the
     last invocation of the STR-HANDLER is returned by the
     `ssax:read-cdata-body'.  Note a similarity to the fundamental
     "fold" iterator.

     Within a CDATA section all characters are taken at their face
     value, with three exceptions:
        * CR, LF, and CRLF are treated as line delimiters, and passed
          as a single `#\newline' to STR-HANDLER

        * `]]>' combination is the end of the CDATA section.  `&gt;' is
          treated as an embedded `>' character.

        * `&lt;' and `&amp;' are not specially recognized (and are not
          expanded)!


 -- Function: ssax:read-char-ref port
          [66]  CharRef ::=  '&#' [0-9]+ ';'
                           | '&#x' [0-9a-fA-F]+ ';'

     This procedure must be called after we we have read `&#' that
     introduces a char reference.  The procedure reads this reference
     and returns the corresponding char.  The current position in PORT
     will be after the `;' that terminates the char reference.

     Faults detected:
     WFC: XML-Spec.html#wf-Legalchar

     According to Section `4.1 Character and Entity References' of the
     XML Recommendation:

          "[Definition: A character reference refers to a specific
          character in the ISO/IEC 10646 character set, for example one
          not directly accessible from available input devices.]"


 -- Function: ssax:handle-parsed-entity port name entities
          content-handler str-handler seed
     Expands and handles a parsed-entity reference.

     NAME is a symbol, the name of the parsed entity to expand.
     CONTENT-HANDLER is a procedure of arguments PORT, ENTITIES, and
     SEED that returns a seed.  STR-HANDLER is called if the entity in
     question is a pre-declared entity.

     `ssax:handle-parsed-entity' returns the result returned by
     CONTENT-HANDLER or STR-HANDLER.

     Faults detected:
     WFC: XML-Spec.html#wf-entdeclared
     WFC: XML-Spec.html#norecursion

 -- Function: attlist-add attlist name-value
     Add a NAME-VALUE pair to the existing ATTLIST, preserving its
     sorted ascending order; and return the new list.  Return #f if a
     pair with the same name already exists in ATTLIST

 -- Function: attlist-remove-top attlist
     Given an non-null ATTLIST, return a pair of values: the top and
     the rest.

 -- Function: ssax:read-attributes port entities
     This procedure reads and parses a production "Attribute".  

          [41] Attribute ::= Name Eq AttValue
          [10] AttValue ::=  '"' ([^<&"] | Reference)* '"'
                          | "'" ([^<&'] | Reference)* "'"
          [25] Eq ::= S? '=' S?

     The procedure returns an ATTLIST, of Name (as UNRES-NAME), Value
     (as string) pairs.  The current character on the PORT is a
     non-whitespace character that is not an NCName-starting character.

     Note the following rules to keep in mind when reading an
     "AttValue": 

          Before the value of an attribute is passed to the application
          or checked for validity, the XML processor must normalize it
          as follows:

             * A character reference is processed by appending the
               referenced character to the attribute value.

             * An entity reference is processed by recursively
               processing the replacement text of the entity.  The
               named entities `amp', `lt', `gt', `quot', and `apos' are
               pre-declared.

             * A whitespace character (#x20, #x0D, #x0A, #x09) is
               processed by appending #x20 to the normalized value,
               except that only a single #x20 is appended for a
               "#x0D#x0A" sequence that is part of an external parsed
               entity or the literal entity value of an internal parsed
               entity.

             * Other characters are processed by appending them to the
               normalized value.



     Faults detected:
     WFC: XML-Spec.html#CleanAttrVals
     WFC: XML-Spec.html#uniqattspec

 -- Function: ssax:resolve-name port unres-name namespaces
          apply-default-ns?
     Convert an UNRES-NAME to a RES-NAME, given the appropriate
     NAMESPACES declarations.  The last parameter, APPLY-DEFAULT-NS?,
     determines if the default namespace applies (for instance, it does
     not for attribute names).

     Per REC-xml-names/#nsc-NSDeclared, the "xml" prefix is considered
     pre-declared and bound to the namespace name
     "http://www.w3.org/XML/1998/namespace".

     `ssax:resolve-name' tests for the namespace constraints:
     `http://www.w3.org/TR/REC-xml-names/#nsc-NSDeclared'

 -- Function: ssax:complete-start-tag tag port elems entities namespaces
     Complete parsing of a start-tag markup.  `ssax:complete-start-tag'
     must be called after the start tag token has been read.  TAG is an
     UNRES-NAME.  ELEMS is an instance of the ELEMS slot of XML-DECL;
     it can be #f to tell the function to do _no_ validation of
     elements and their attributes.

     `ssax:complete-start-tag' returns several values:
        * ELEM-GI: a RES-NAME.

        * ATTRIBUTES: element's attributes, an ATTLIST of (RES-NAME .
          STRING) pairs.  The list does NOT include xmlns attributes.

        * NAMESPACES: the input list of namespaces amended with
          namespace (re-)declarations contained within the start-tag
          under parsing

        * ELEM-CONTENT-MODEL

     On exit, the current position in PORT will be the first character
     after `>' that terminates the start-tag markup.

     Faults detected:
     VC: XML-Spec.html#enum
     VC: XML-Spec.html#RequiredAttr
     VC: XML-Spec.html#FixedAttr
     VC: XML-Spec.html#ValueType
     WFC: XML-Spec.html#uniqattspec (after namespaces prefixes are
     resolved)
     VC: XML-Spec.html#elementvalid
     WFC: REC-xml-names/#dt-NSName

     _Note_: although XML Recommendation does not explicitly say it,
     xmlns and xmlns: attributes don't have to be declared (although
     they can be declared, to specify their default value).

 -- Function: ssax:read-external-id port
     Parses an ExternalID production:

          [75] ExternalID ::= 'SYSTEM' S SystemLiteral
                            | 'PUBLIC' S PubidLiteral S SystemLiteral
          [11] SystemLiteral ::= ('"' [^"]* '"') | ("'" [^']* "'")
          [12] PubidLiteral ::=  '"' PubidChar* '"'
                               | "'" (PubidChar - "'")* "'"
          [13] PubidChar ::=  #x20 | #x0D | #x0A | [a-zA-Z0-9]
                                   | [-'()+,./:=?;!*#@$_%]

     Call `ssax:read-external-id' when an ExternalID is expected; that
     is, the current character must be either #\S or #\P that starts
     correspondingly a SYSTEM or PUBLIC token.  `ssax:read-external-id'
     returns the SYSTEMLITERAL as a string.  A PUBIDLITERAL is
     disregarded if present.

4.11.5 Mid-Level Parsers and Scanners
-------------------------------------

These procedures parse productions corresponding to the whole
(document) entity or its higher-level pieces (prolog, root element,
etc).

 -- Function: ssax:scan-misc port
     Scan the Misc production in the context:

          [1]  document ::=  prolog element Misc*
          [22] prolog ::= XMLDecl? Misc* (doctypedec l Misc*)?
          [27] Misc ::= Comment | PI |  S

     Call `ssax:scan-misc' in the prolog or epilog contexts.  In these
     contexts, whitespaces are completely ignored.  The return value
     from `ssax:scan-misc' is either a PI-token, a DECL-token, a START
     token, or *EOF*.  Comments are ignored and not reported.

 -- Function: ssax:read-char-data port expect-eof? str-handler iseed
     Read the character content of an XML document or an XML element.

          [43] content ::=
          (element | CharData | Reference | CDSect | PI | Comment)*

     To be more precise, `ssax:read-char-data' reads CharData, expands
     CDSect and character entities, and skips comments.
     `ssax:read-char-data' stops at a named reference, EOF, at the
     beginning of a PI, or a start/end tag.

     EXPECT-EOF? is a boolean indicating if EOF is normal; i.e., the
     character data may be terminated by the EOF.  EOF is normal while
     processing a parsed entity.

     ISEED is an argument passed to the first invocation of STR-HANDLER.

     `ssax:read-char-data' returns two results: SEED and TOKEN.  The
     SEED is the result of the last invocation of STR-HANDLER, or the
     original ISEED if STR-HANDLER was never called.

     TOKEN can be either an eof-object (this can happen only if
     EXPECT-EOF?  was #t), or:
        * an xml-token describing a START tag or an END-tag; For a
          start token, the caller has to finish reading it.

        * an xml-token describing the beginning of a PI.  It's up to an
          application to read or skip through the rest of this PI;

        * an xml-token describing a named entity reference.


     CDATA sections and character references are expanded inline and
     never returned.  Comments are silently disregarded.

     As the XML Recommendation requires, all whitespace in character
     data must be preserved.  However, a CR character (#x0D) must be
     disregarded if it appears before a LF character (#x0A), or replaced
     by a #x0A character otherwise.  See Secs. 2.10 and 2.11 of the XML
     Recommendation.  See also the canonical XML Recommendation.

 -- Function: ssax:assert-token token kind gi error-cont
     Make sure that TOKEN is of anticipated KIND and has anticipated
     GI.  Note that the GI argument may actually be a pair of two
     symbols, Namespace-URI or the prefix, and of the localname.  If
     the assertion fails, ERROR-CONT is evaluated by passing it three
     arguments: TOKEN KIND GI.  The result of ERROR-CONT is returned.

4.11.6 High-level Parsers
-------------------------

These procedures are to instantiate a SSAX parser.  A user can
instantiate the parser to do the full validation, or no validation, or
any particular validation.  The user specifies which PI he wants to be
notified about.  The user tells what to do with the parsed character
and element data.  The latter handlers determine if the parsing follows
a SAX or a DOM model.

 -- Function: ssax:make-pi-parser my-pi-handlers
     Create a parser to parse and process one Processing Element (PI).

     MY-PI-HANDLERS is an association list of pairs `(PI-TAG .
     PI-HANDLER)' where PI-TAG is an NCName symbol, the PI target; and
     PI-HANDLER is a procedure taking arguments PORT, PI-TAG, and SEED.

     PI-HANDLER should read the rest of the PI up to and including the
     combination `?>' that terminates the PI.  The handler should
     return a new seed.  One of the PI-TAGs may be the symbol
     `*DEFAULT*'.  The corresponding handler will handle PIs that no
     other handler will.  If the *DEFAULT* PI-TAG is not specified,
     `ssax:make-pi-parser' will assume the default handler that skips
     the body of the PI.

     `ssax:make-pi-parser' returns a procedure of arguments PORT,
     PI-TAG, and SEED; that will parse the current PI according to
     MY-PI-HANDLERS.

 -- Function: ssax:make-elem-parser my-new-level-seed my-finish-element
          my-char-data-handler my-pi-handlers
     Create a parser to parse and process one element, including its
     character content or children elements.  The parser is typically
     applied to the root element of a document.

    MY-NEW-LEVEL-SEED
          is a procedure taking arguments:

          ELEM-GI ATTRIBUTES NAMESPACES EXPECTED-CONTENT SEED

          where ELEM-GI is a RES-NAME of the element about to be
          processed.

          MY-NEW-LEVEL-SEED is to generate the seed to be passed to
          handlers that process the content of the element.

    MY-FINISH-ELEMENT
          is a procedure taking arguments:

          ELEM-GI ATTRIBUTES NAMESPACES PARENT-SEED SEED

          MY-FINISH-ELEMENT is called when parsing of ELEM-GI is
          finished.  The SEED is the result from the last content
          parser (or from MY-NEW-LEVEL-SEED if the element has the
          empty content).  PARENT-SEED is the same seed as was passed
          to MY-NEW-LEVEL-SEED.  MY-FINISH-ELEMENT is to generate a
          seed that will be the result of the element parser.

    MY-CHAR-DATA-HANDLER
          is a STR-HANDLER as described in Data Types above.

    MY-PI-HANDLERS
          is as described for `ssax:make-pi-handler' above.


     The generated parser is a procedure taking arguments:

     START-TAG-HEAD PORT ELEMS ENTITIES NAMESPACES PRESERVE-WS? SEED

     The procedure must be called after the start tag token has been
     read.  START-TAG-HEAD is an UNRES-NAME from the start-element tag.
     ELEMS is an instance of ELEMS slot of XML-DECL.

     Faults detected:
     VC: XML-Spec.html#elementvalid
     WFC: XML-Spec.html#GIMatch

 -- Function: ssax:make-parser user-handler-tag user-handler ...
     Create an XML parser, an instance of the XML parsing framework.
     This will be a SAX, a DOM, or a specialized parser depending on the
     supplied user-handlers.

     `ssax:make-parser' takes an even number of arguments;
     USER-HANDLER-TAG is a symbol that identifies a procedure (or
     association list for `PROCESSING-INSTRUCTIONS') (USER-HANDLER)
     that follows the tag.  Given below are tags and signatures of the
     corresponding procedures.  Not all tags have to be specified.  If
     some are omitted, reasonable defaults will apply.

    `DOCTYPE'
          handler-procedure: PORT DOCNAME SYSTEMID INTERNAL-SUBSET? SEED

          If INTERNAL-SUBSET? is #t, the current position in the port is
          right after we have read `[' that begins the internal DTD
          subset.  We must finish reading of this subset before we
          return (or must call `skip-internal-dtd' if we aren't
          interested in reading it).  PORT at exit must be at the first
          symbol after the whole DOCTYPE declaration.

          The handler-procedure must generate four values:

               ELEMS ENTITIES NAMESPACES SEED

          ELEMS is as defined for the ELEMS slot of XML-DECL.  It may be
          #f to switch off validation.  NAMESPACES will typically
          contain USER-PREFIXes for selected URI-SYMBs.  The default
          handler-procedure skips the internal subset, if any, and
          returns `(values #f '() '() seed)'.

    `UNDECL-ROOT'
          procedure: ELEM-GI SEED

          where ELEM-GI is an UNRES-NAME of the root element.  This
          procedure is called when an XML document under parsing
          contains _no_ DOCTYPE declaration.

          The handler-procedure, as a DOCTYPE handler procedure above,
          must generate four values:

               ELEMS ENTITIES NAMESPACES SEED

          The default handler-procedure returns (values #f '() '() seed)

    `DECL-ROOT'
          procedure: ELEM-GI SEED

          where ELEM-GI is an UNRES-NAME of the root element.  This
          procedure is called when an XML document under parsing does
          contains the DOCTYPE declaration.  The handler-procedure must
          generate a new SEED (and verify that the name of the root
          element matches the doctype, if the handler so wishes).  The
          default handler-procedure is the identity function.

    `NEW-LEVEL-SEED'
          procedure: see ssax:make-elem-parser, my-new-level-seed

    `FINISH-ELEMENT'
          procedure: see ssax:make-elem-parser, my-finish-element

    `CHAR-DATA-HANDLER'
          procedure: see ssax:make-elem-parser, my-char-data-handler

    `PROCESSING-INSTRUCTIONS'
          association list as is passed to `ssax:make-pi-parser'.  The
          default value is '()


     The generated parser is a procedure of arguments PORT and SEED.

     This procedure parses the document prolog and then exits to an
     element parser (created by `ssax:make-elem-parser') to handle the
     rest.

          [1]  document ::=  prolog element Misc*
          [22] prolog ::= XMLDecl? Misc* (doctypedec | Misc*)?
          [27] Misc ::= Comment | PI |  S
          [28] doctypedecl ::=  '<!DOCTYPE' S Name (S ExternalID)? S?
                        ('[' (markupdecl | PEReference | S)* ']' S?)? '>'
          [29] markupdecl ::= elementdecl | AttlistDecl
                               | EntityDecl
                               | NotationDecl | PI
                               | Comment

4.11.7 Parsing XML to SXML
--------------------------

 -- Function: ssax:xml->sxml port namespace-prefix-assig
     This is an instance of the SSAX parser that returns an SXML
     representation of the XML document to be read from PORT.
     NAMESPACE-PREFIX-ASSIG is a list of `(USER-PREFIX . URI-STRING)'
     that assigns USER-PREFIXes to certain namespaces identified by
     particular URI-STRINGs.  It may be an empty list.
     `ssax:xml->sxml' returns an SXML tree.  The port points out to the
     first character after the root element.


File: slib.info,  Node: Printing Scheme,  Next: Time and Date,  Prev: Parsing XML,  Up: Textual Conversion Packages

4.12 Printing Scheme
====================

* Menu:

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


File: slib.info,  Node: Generic-Write,  Next: Object-To-String,  Prev: Printing Scheme,  Up: Printing Scheme

4.12.1 Generic-Write
--------------------

`(require 'generic-write)' 

  `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.

 -- Procedure: generic-write obj display? width output
    OBJ
          Scheme data value to transform.

    DISPLAY?
          Boolean, controls whether characters and strings are quoted.

    WIDTH
          Extended boolean, selects format:
         #f
               single line format

         integer > 0
               pretty-print (value = max nb of chars per line)

    OUTPUT
          Procedure of 1 argument of string type, called repeatedly with
          successive substrings of the textual representation.  This
          procedure can return `#f' to stop the transformation.

     The value returned by `generic-write' is undefined.

     Examples:
          (write obj) == (generic-write obj #f #f DISPLAY-STRING)
          (display obj) == (generic-write obj #t #f DISPLAY-STRING)
     where
          DISPLAY-STRING ==
          (lambda (s) (for-each write-char (string->list s)) #t)


File: slib.info,  Node: Object-To-String,  Next: Pretty-Print,  Prev: Generic-Write,  Up: Printing Scheme

4.12.2 Object-To-String
-----------------------

`(require 'object->string)' 

 -- Function: object->string obj
     Returns the textual representation of OBJ as a string.

 -- Function: object->limited-string obj limit
     Returns the textual representation of OBJ as a string of length at
     most LIMIT.


File: slib.info,  Node: Pretty-Print,  Prev: Object-To-String,  Up: Printing Scheme

4.12.3 Pretty-Print
-------------------

`(require 'pretty-print)' 

 -- Procedure: pretty-print obj
 -- Procedure: pretty-print obj port
     `pretty-print's OBJ on PORT.  If PORT is not specified,
     `current-output-port' is used.

     Example:
          (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)))
             -| ((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))

 -- Procedure: pretty-print->string obj
 -- Procedure: pretty-print->string obj width
     Returns the string of OBJ `pretty-print'ed in WIDTH columns.  If
     WIDTH is not specified, `(output-port-width)' is used.

     Example:
          (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)))
          =>
          "((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))
          "
          (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)
          =>
          "((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))
          "

  `(require 'pprint-file)' 

 -- Procedure: pprint-file infile
 -- Procedure: pprint-file infile outfile
     Pretty-prints all the code in INFILE.  If OUTFILE is specified,
     the output goes to OUTFILE, otherwise it goes to
     `(current-output-port)'.

 -- Function: pprint-filter-file infile proc outfile
 -- Function: pprint-filter-file infile proc
     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 PROC is applied to them sequentially.

     OUTFILE is a port or a string.  If no OUTFILE is specified then
     `current-output-port' is assumed.  These expanded expressions are
     then `pretty-print'ed to this port.

     Whitepsace and comments (introduced by `;') which are not part of
     scheme expressions are reproduced in the output.  This procedure
     does not affect the values returned by `current-input-port' and
     `current-output-port'.

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


File: slib.info,  Node: Time and Date,  Next: NCBI-DNA,  Prev: Printing Scheme,  Up: Textual Conversion Packages

4.13 Time and Date
==================

* Menu:

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

If `(provided? 'current-time)':

The procedures `current-time', `difftime', and `offset-time' deal with
a "calendar time" datatype which may or may not be disjoint from other
Scheme datatypes.

 -- Function: 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 `get-universal-time' in *Note Common-Lisp
     Time::.

 -- Function: difftime caltime1 caltime0
     Returns the difference (number of seconds) between twe calendar
     times: CALTIME1 - CALTIME0.  CALTIME0 may also be a number.

 -- Function: offset-time caltime offset
     Returns the calendar time of CALTIME offset by OFFSET number of
     seconds `(+ caltime offset)'.


File: slib.info,  Node: Time Zone,  Next: Posix Time,  Prev: Time and Date,  Up: Time and Date

4.13.1 Time Zone
----------------

(require 'time-zone)

 -- Data Format: TZ-string
     POSIX standards specify several formats for encoding time-zone
     rules.

    :<pathname>
          If the first character of <pathname> is `/', then <pathname>
          specifies the absolute pathname of a tzfile(5) format
          time-zone file.  Otherwise, <pathname> is interpreted as a
          pathname within TZFILE:VICINITY (/usr/lib/zoneinfo/) naming a
          tzfile(5) format time-zone file.

    <std><offset>
          The string <std> consists of 3 or more alphabetic characters.
          <offset> specifies the time difference from GMT.  The <offset>
          is positive if the local time zone is west of the Prime
          Meridian and negative if it is east.  <offset> can be the
          number of hours or hours and minutes (and optionally seconds)
          separated by `:'.  For example, `-4:30'.

    <std><offset><dst>
          <dst> is the at least 3 alphabetic characters naming the local
          daylight-savings-time.

    <std><offset><dst><doffset>
          <doffset> specifies the offset from the Prime Meridian when
          daylight-savings-time is in effect.

     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.

    ,<date>/<time>,<date>/<time>
          The <time>s are specified like the <offset>s above, except
          that leading `+' and `-' are not allowed.

          Each <date> has one of the formats:

         J<day>
               specifies the Julian day with <day> between 1 and 365.
               February 29 is never counted and cannot be referenced.

         <day>
               This specifies the Julian day with n between 0 and 365.
               February 29 is counted in leap years and can be
               specified.

         M<month>.<week>.<day>
               This specifies day <day> (0 <= <day> <= 6) of week
               <week> (1 <= <week> <= 5) of month <month> (1 <= <month>
               <= 12).  Week 1 is the first week in which day d occurs
               and week 5 is the last week in which day <day> occurs.
               Day 0 is a Sunday.


 -- Data Type: time-zone
     is a datatype encoding how many hours from Greenwich Mean Time the
     local time is, and the "Daylight Savings Time" rules for changing
     it.

 -- Function: time-zone TZ-string
     Creates and returns a time-zone object specified by the string
     TZ-STRING.  If `time-zone' cannot interpret TZ-STRING, `#f' is
     returned.

 -- Function: tz:params caltime tz
     TZ is a time-zone object.  `tz:params' returns a list of three
     items:
       0. An integer.  0 if standard time is in effect for timezone TZ
          at CALTIME; 1 if daylight savings time is in effect for
          timezone TZ at CALTIME.

       1. The number of seconds west of the Prime Meridian timezone TZ
          is at CALTIME.

       2. The name for timezone TZ at CALTIME.

     `tz:params' is unaffected by the default timezone; inquiries can be
     made of any timezone at any calendar time.


 -- Function: tz:std-offset tz
     TZ is a time-zone object.  `tz:std-offset' returns the number of
     seconds west of the Prime Meridian timezone TZ is.


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

 -- Function: tzset
     Returns the default time-zone.

 -- Function: tzset tz
     Sets (and returns) the default time-zone to TZ.

 -- Function: tzset TZ-string
     Sets (and returns) the default time-zone to that specified by
     TZ-STRING.

     `tzset' also sets the variables *TIMEZONE*, DAYLIGHT?, and TZNAME.
     This function is automatically called by the time conversion
     procedures which depend on the time zone (*note Time and Date::).

 -- Variable: *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).  `*timezone*' is initialized by
     `tzset'.

 -- Variable: daylight?
     is `#t' if the default timezone has rules for "Daylight Savings
     Time".  _Note:_ DAYLIGHT? does not tell you when Daylight Savings
     Time is in effect, just that the default zone sometimes has
     Daylight Savings Time.

 -- Variable: tzname
     is a vector of strings.  Index 0 has the abbreviation for the
     standard timezone; If DAYLIGHT?, then index 1 has the abbreviation
     for the Daylight Savings timezone.


File: slib.info,  Node: Posix Time,  Next: Common-Lisp Time,  Prev: Time Zone,  Up: Time and Date

4.13.2 Posix Time
-----------------

     (require 'posix-time)
     

 -- Data Type: Calendar-Time
     is a datatype encapsulating time.

 -- Data Type: Coordinated Universal Time
     (abbreviated "UTC") is a vector of integers representing time:

       0.  seconds (0 - 61)

       1.  minutes (0 - 59)

       2.  hours since midnight (0 - 23)

       3.  day of month (1 - 31)

       4.  month (0 - 11).  Note difference from
          `decode-universal-time'.

       5.  the number of years since 1900.  Note difference from
          `decode-universal-time'.

       6.  day of week (0 - 6)

       7.  day of year (0 - 365)

       8.  1 for daylight savings, 0 for regular time

 -- Function: gmtime caltime
     Converts the calendar time CALTIME to UTC and returns it.

 -- Function: localtime caltime tz
     Returns CALTIME converted to UTC relative to timezone TZ.

 -- Function: localtime caltime
     converts the calendar time CALTIME to a vector of integers
     expressed relative to the user's time zone.  `localtime' sets the
     variable *TIMEZONE* with the difference between Coordinated
     Universal Time (UTC) and local standard time in seconds (*note
     tzset: Time Zone.).


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

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

 -- Function: mktime univtime tz
     Converts a vector of integers in Coordinated Universal Time (UTC)
     format (relative to time-zone TZ) to calendar time.

 -- Function: asctime univtime
     Converts the vector of integers CALTIME in Coordinated Universal
     Time (UTC) format into a string of the form `"Wed Jun 30 21:49:08
     1993"'.

 -- Function: gtime caltime
 -- Function: ctime caltime
 -- Function: ctime caltime tz
     Equivalent to `(asctime (gmtime CALTIME))', `(asctime (localtime
     CALTIME))', and `(asctime (localtime CALTIME TZ))', respectively.


File: slib.info,  Node: Common-Lisp Time,  Next: Time Infrastructure,  Prev: Posix Time,  Up: Time and Date

4.13.3 Common-Lisp Time
-----------------------

 -- Function: get-decoded-time
     Equivalent to `(decode-universal-time (get-universal-time))'.

 -- Function: get-universal-time
     Returns the current time as "Universal Time", number of seconds
     since 00:00:00 Jan 1, 1900 GMT.  Note that the reference time is
     different from `current-time'.

 -- Function: decode-universal-time univtime
     Converts UNIVTIME to "Decoded Time" format.  Nine values are
     returned:
       0.  seconds (0 - 61)

       1.  minutes (0 - 59)

       2.  hours since midnight

       3.  day of month

       4.  month (1 - 12).  Note difference from `gmtime' and
          `localtime'.

       5.  year (A.D.).  Note difference from `gmtime' and `localtime'.

       6.  day of week (0 - 6)

       7.  #t for daylight savings, #f otherwise

       8.  hours west of GMT (-24 - +24)

     Notice that the values returned by `decode-universal-time' do not
     match the arguments to `encode-universal-time'.

 -- Function: encode-universal-time second minute hour date month year
 -- Function: encode-universal-time second minute hour date month year
          time-zone
     Converts the arguments in Decoded Time format to Universal Time
     format.  If 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 `decode-universal-time' do not
     match the arguments to `encode-universal-time'.


File: slib.info,  Node: Time Infrastructure,  Prev: Common-Lisp Time,  Up: Time and Date

4.13.4 Time Infrastructure
--------------------------

`(require 'time-core)'

 -- Function: time:gmtime tm
 -- Function: time:invert decoder target
 -- Function: time:split t tm_isdst tm_gmtoff tm_zone

  `(require 'tzfile)'

 -- Function: tzfile:read path


File: slib.info,  Node: NCBI-DNA,  Next: Schmooz,  Prev: Time and Date,  Up: Textual Conversion Packages

4.14 NCBI-DNA
=============

`(require 'ncbi-dma)' 

 -- Function: ncbi:read-dna-sequence port
     Reads the NCBI-format DNA sequence following the word `ORIGIN'
     from PORT.

 -- Function: ncbi:read-file file
     Reads the NCBI-format DNA sequence following the word `ORIGIN'
     from FILE.

 -- Function: mrna<-cdna str
     Replaces `T' with `U' in STR

 -- Function: codons<-cdna cdna
     Returns a list of three-letter symbol codons comprising the protein
     sequence encoded by CDNA starting with its first occurence of
     `atg'.

 -- Function: protein<-cdna cdna
     Returns a list of three-letter symbols for the protein sequence
     encoded by CDNA starting with its first occurence of `atg'.

 -- Function: p<-cdna cdna
     Returns a string of one-letter amino acid codes for the protein
     sequence encoded by CDNA starting with its first occurence of
     `atg'.

  These cDNA count routines provide a means to check the nucleotide
sequence with the `BASE COUNT' line preceding the sequence from NCBI.

 -- Function: cdna:base-count cdna
     Returns a list of counts of `a', `c', `g', and `t' occurrencing in
     CDNA.

 -- Function: cdna:report-base-count cdna
     Prints the counts of `a', `c', `g', and `t' occurrencing in CDNA.


File: slib.info,  Node: Schmooz,  Prev: NCBI-DNA,  Up: Textual Conversion Packages

4.15 Schmooz
============

"Schmooz" is a simple, lightweight markup language for interspersing
Texinfo documentation with Scheme source code.  Schmooz does not create
the top level Texinfo file; it creates `txi' files which can be
imported into the documentation using the Texinfo command `@include'.

  `(require 'schmooz)' defines the function `schmooz', which is used to
process files.  Files containing schmooz documentation should not
contain `(require 'schmooz)'.

 -- Procedure: schmooz filename.scm ...
     FILENAME.scm should be a string ending with `.scm' naming an
     existing file containing Scheme source code.  `schmooz' extracts
     top-level comments containing schmooz commands from FILENAME.scm
     and writes the converted Texinfo source to a file named
     FILENAME.txi.

 -- Procedure: schmooz filename.texi ...
 -- Procedure: schmooz filename.tex ...
 -- Procedure: schmooz filename.txi ...
     FILENAME should be a string naming an existing file containing
     Texinfo source code.  For every occurrence of the string `@include
     FILENAME.txi' within that file, `schmooz' calls itself with the
     argument `FILENAME.scm'.

  Schmooz comments are distinguished (from non-schmooz comments) by
their first line, which must start with an at-sign (@) preceded by one
or more semicolons (;).  A schmooz comment ends at the first subsequent
line which does _not_ start with a semicolon.  Currently schmooz
comments are recognized only at top level.

  Schmooz comments are copied to the Texinfo output file with the
leading contiguous semicolons removed.  Certain character sequences
starting with at-sign are treated specially.  Others are copied
unchanged.

  A schmooz comment starting with `@body' must be followed by a Scheme
definition.  All comments between the `@body' line and the definition
will be included in a Texinfo definition, either a `@defun' or a
`@defvar', depending on whether a procedure or a variable is being
defined.

  Within the text of that schmooz comment, at-sign followed by `0' will
be replaced by `@code{procedure-name}' if the following definition is
of a procedure; or `@var{variable}' if defining a variable.

  An at-sign followed by a non-zero digit will expand to the variable
citation of that numbered argument: `@var{argument-name}'.

  If more than one definition follows a `@body' comment line without an
intervening blank or comment line, then those definitions will be
included in the same Texinfo definition using `@defvarx' or `@defunx',
depending on whether the first definition is of a variable or of a
procedure.

  Schmooz can figure out whether a definition is of a procedure if it
is of the form:

  `(define (<identifier> <arg> ...) <expression>)'

or if the left hand side of the definition is some form ending in a
lambda expression.  Obviously, it can be fooled.  In order to force
recognition of a procedure definition, start the documentation with
`@args' instead of `@body'.  `@args' should be followed by the argument
list of the function being defined, which may be enclosed in
parentheses and delimited by whitespace, (as in Scheme), enclosed in
braces and separated by commas, (as in Texinfo), or consist of the
remainder of the line, separated by whitespace.

  For example:

     ;;@args arg1 args ...
     ;;@0 takes argument @1 and any number of @2
     (define myfun (some-function-returning-magic))

  Will result in:

     @defun myfun arg1 args @dots{}

     @code{myfun} takes argument @var{arg1} and any number of @var{args}
     @end defun

  `@args' may also be useful for indicating optional arguments by name.
If `@args' occurs inside a schmooz comment section, rather than at the
beginning, then it will generate a `@defunx' line with the arguments
supplied.

  If the first at-sign in a schmooz comment is immediately followed by
whitespace, then the comment will be expanded to whatever follows that
whitespace.  If the at-sign is followed by a non-whitespace character
then the at-sign will be included as the first character of the
expansion.  This feature is intended to make it easy to include Texinfo
directives in schmooz comments.


File: slib.info,  Node: Mathematical Packages,  Next: Database Packages,  Prev: Textual Conversion Packages,  Up: Top

5 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


File: slib.info,  Node: Bit-Twiddling,  Next: Modular Arithmetic,  Prev: Mathematical Packages,  Up: Mathematical Packages

5.1 Bit-Twiddling
=================

`(require 'logical)' or `(require 'srfi-60)' 

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

5.1.1 Bitwise Operations
------------------------

 -- Function: logand n1 ...
 -- Function: bitwise-and n1 ...
     Returns the integer which is the bit-wise AND of the integer
     arguments.

     Example:
          (number->string (logand #b1100 #b1010) 2)
             => "1000"

 -- Function: logior n1 ...
 -- Function: bitwise-ior n1 ...
     Returns the integer which is the bit-wise OR of the integer
     arguments.

     Example:
          (number->string (logior #b1100 #b1010) 2)
             => "1110"

 -- Function: logxor n1 ...
 -- Function: bitwise-xor n1 ...
     Returns the integer which is the bit-wise XOR of the integer
     arguments.

     Example:
          (number->string (logxor #b1100 #b1010) 2)
             => "110"

 -- Function: lognot n
 -- Function: bitwise-not n
     Returns the integer which is the one's-complement of the integer
     argument.

     Example:
          (number->string (lognot #b10000000) 2)
             => "-10000001"
          (number->string (lognot #b0) 2)
             => "-1"

 -- Function: bitwise-if mask n0 n1
 -- Function: bitwise-merge mask n0 n1
     Returns an integer composed of some bits from integer N0 and some
     from integer N1.  A bit of the result is taken from N0 if the
     corresponding bit of integer MASK is 1 and from N1 if that bit of
     MASK is 0.

 -- Function: logtest j k
 -- Function: any-bits-set? j k
          (logtest j k) == (not (zero? (logand j k)))

          (logtest #b0100 #b1011) => #f
          (logtest #b0100 #b0111) => #t

5.1.2 Integer Properties
------------------------

 -- Function: logcount n
     Returns the number of bits in integer 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:
          (logcount #b10101010)
             => 4
          (logcount 0)
             => 0
          (logcount -2)
             => 1

On `discuss@r6rs.org' Ben Harris credits Simon Tatham with the idea to
have `bitwise-bit-count' return a negative count for negative inputs.
Alan Bawden came up with the succinct invariant.

 -- Function: bitwise-bit-count n
     If N is non-negative, this procedure returns the number of 1 bits
     in the two's-complement representation of N.  Otherwise it returns
     the result of the following computation:

          (bitwise-not (bitwise-bit-count (bitwise-not N)))

 -- Function: integer-length n
     Returns the number of bits neccessary to represent N.

     Example:
          (integer-length #b10101010)
             => 8
          (integer-length 0)
             => 0
          (integer-length #b1111)
             => 4

 -- Function: log2-binary-factors n
 -- Function: first-set-bit n
     Returns the number of factors of two of integer N.  This value is
     also the bit-index of the least-significant `1' bit in N.

          (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)))
          -|
          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

5.1.3 Bit Within Word
---------------------

 -- Function: logbit? index n
 -- Function: bit-set? index n
          (logbit? index n) == (logtest (expt 2 index) n)

          (logbit? 0 #b1101) => #t
          (logbit? 1 #b1101) => #f
          (logbit? 2 #b1101) => #t
          (logbit? 3 #b1101) => #t
          (logbit? 4 #b1101) => #f

 -- Function: copy-bit index from bit
     Returns an integer the same as FROM except in the INDEXth bit,
     which is 1 if BIT is `#t' and 0 if BIT is `#f'.

     Example:
          (number->string (copy-bit 0 0 #t) 2)       => "1"
          (number->string (copy-bit 2 0 #t) 2)       => "100"
          (number->string (copy-bit 2 #b1111 #f) 2)  => "1011"

5.1.4 Field of Bits
-------------------

 -- Function: bit-field n start end
     Returns the integer composed of the START (inclusive) through END
     (exclusive) bits of N.  The STARTth bit becomes the 0-th bit in
     the result.

     Example:
          (number->string (bit-field #b1101101010 0 4) 2)
             => "1010"
          (number->string (bit-field #b1101101010 4 9) 2)
             => "10110"

 -- Function: copy-bit-field to from start end
     Returns an integer the same as TO except possibly in the START
     (inclusive) through END (exclusive) bits, which are the same as
     those of FROM.  The 0-th bit of FROM becomes the STARTth bit of
     the result.

     Example:
          (number->string (copy-bit-field #b1101101010 0 0 4) 2)
                  => "1101100000"
          (number->string (copy-bit-field #b1101101010 -1 0 4) 2)
                  => "1101101111"
          (number->string (copy-bit-field #b110100100010000 -1 5 9) 2)
                  => "110100111110000"

 -- Function: ash n count
 -- Function: arithmetic-shift n count
     Returns an integer equivalent to `(inexact->exact (floor (* N
     (expt 2 COUNT))))'.

     Example:
          (number->string (ash #b1 3) 2)
             => "1000"
          (number->string (ash #b1010 -1) 2)
             => "101"

 -- Function: rotate-bit-field n count start end
     Returns N with the bit-field from START to END cyclically permuted
     by COUNT bits towards high-order.

     Example:
          (number->string (rotate-bit-field #b0100 3 0 4) 2)
              => "10"
          (number->string (rotate-bit-field #b0100 -1 0 4) 2)
              => "10"
          (number->string (rotate-bit-field #b110100100010000 -1 5 9) 2)
              => "110100010010000"
          (number->string (rotate-bit-field #b110100100010000 1 5 9) 2)
              => "110100000110000"

 -- Function: reverse-bit-field n start end
     Returns N with the order of bits START to END reversed.

          (number->string (reverse-bit-field #xa7 0 8) 16)
            => "e5"

5.1.5 Bits as Booleans
----------------------

 -- Function: integer->list k len
 -- Function: integer->list k
     `integer->list' returns a list of LEN booleans corresponding to
     each bit of the given integer.  #t is coded for each 1; #f for 0.
     The LEN argument defaults to `(integer-length K)'.

 -- Function: list->integer list
     `list->integer' returns an integer formed from the booleans in the
     list LIST, which must be a list of booleans.  A 1 bit is coded for
     each #t; a 0 bit for #f.

     `integer->list' and `list->integer' are inverses so far as
     `equal?' is concerned.

 -- Function: booleans->integer bool1 ...
     Returns the integer coded by the BOOL1 ... arguments.


File: slib.info,  Node: Modular Arithmetic,  Next: Irrational Integer Functions,  Prev: Bit-Twiddling,  Up: Mathematical Packages

5.2 Modular Arithmetic
======================

`(require 'modular)' 

 -- Function: extended-euclid n1 n2
     Returns a list of 3 integers `(d x y)' such that d = gcd(N1, N2) =
     N1 * x + N2 * y.

 -- Function: symmetric:modulus m
     For odd positive integer M, returns an object suitable for passing
     as the first argument to `modular:' procedures, directing them to
     return a symmetric modular number, ie. an N such that
          (<= (quotient M -2) N (quotient M 2)

 -- Function: modular:characteristic modulus
     Returns the non-negative integer characteristic of the ring formed
     when MODULUS is used with `modular:' procedures.

 -- Function: modular:normalize modulus n
     Returns the integer `(modulo N (modular:characteristic MODULUS))'
     in the representation specified by MODULUS.

The rest of these functions assume normalized arguments; That is, the
arguments are constrained by the following table:

For all of these functions, if the first argument (MODULUS) is:
`positive?'
     Integers mod MODULUS.  The result is between 0 and MODULUS.

`zero?'
     The arguments are treated as integers.  An integer is returned.

Otherwise, if MODULUS is a value returned by `(symmetric:modulus
RADIX)', then the arguments and result are treated as members of the
integers modulo RADIX, but with "symmetric" representation; i.e.  
     (<= (quotient RADIX 2) N (quotient (- -1 RADIX) 2)

If all the arguments are fixnums the computation will use only fixnums.

 -- Function: modular:invertable? modulus k
     Returns `#t' if there exists an integer n such that K * n == 1 mod
     MODULUS, and `#f' otherwise.

 -- Function: modular:invert modulus n2
     Returns an integer n such that 1 = (n * N2) mod MODULUS.  If N2
     has no inverse mod MODULUS an error is signaled.

 -- Function: modular:negate modulus n2
     Returns (-N2) mod MODULUS.

 -- Function: modular:+ modulus n2 n3
     Returns (N2 + N3) mod MODULUS.

 -- Function: modular:- modulus n2 n3
     Returns (N2 - N3) mod MODULUS.

 -- Function: modular:* modulus n2 n3
     Returns (N2 * N3) mod MODULUS.

     The Scheme code for `modular:*' with negative MODULUS is not
     completed for fixnum-only implementations.

 -- Function: modular:expt modulus n2 n3
     Returns (N2 ^ N3) mod MODULUS.


File: slib.info,  Node: Irrational Integer Functions,  Next: Irrational Real Functions,  Prev: Modular Arithmetic,  Up: Mathematical Packages

5.3 Irrational Integer Functions
================================

`(require 'math-integer)' 

 -- Function: integer-expt n1 n2
     Returns N1 raised to the power N2 if that result is an exact
     integer; otherwise signals an error.

     `(integer-expt 0 N2)'

     returns 1 for N2 equal to 0; returns 0 for positive integer N2;
     signals an error otherwise.

 -- Function: integer-log base k
     Returns the largest exact integer whose power of BASE is less than
     or equal to K. If BASE or K is not a positive exact integer, then
     `integer-log' signals an error.

 -- Function: integer-sqrt k
     For non-negative integer K returns the largest integer whose square
     is less than or equal to K; otherwise signals an error.

 -- Variable: quotient
 -- Variable: remainder
 -- Variable: modulo
     are redefined so that they accept only exact-integer arguments.


File: slib.info,  Node: Irrational Real Functions,  Next: Prime Numbers,  Prev: Irrational Integer Functions,  Up: Mathematical Packages

5.4 Irrational Real Functions
=============================

`(require '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.

 -- Function: real-exp X
 -- Function: real-ln X
 -- Function: real-log Y X
 -- Function: real-sin X
 -- Function: real-cos X
 -- Function: real-tan X
 -- Function: real-asin X
 -- Function: real-acos X
 -- Function: real-atan X
 -- Function: atan Y X
     These procedures are part of every implementation that supports
     general real numbers; they compute the usual transcendental
     functions.  `real-ln' computes the natural logarithm of X;
     `real-log' computes the logarithm of X base Y, which is `(/
     (real-ln x) (real-ln y))'.  If arguments X and Y are not both
     real; or if the correct result would not be real, then these
     procedures signal an error.


 -- Function: real-sqrt X
     For non-negative real X the result will be its positive square
     root; otherwise an error will be signaled.


 -- Function: real-expt x1 x2
     Returns X1 raised to the power X2 if that result is a real number;
     otherwise signals an error.

     `(real-expt 0.0 X2)'

        * returns 1.0 for X2 equal to 0.0;

        * returns 0.0 for positive real X2;

        * signals an error otherwise.


 -- Function: quo x1 x2
 -- Function: rem x1 x2
 -- Function: mod x1 x2
     X2 should be non-zero.

              (quo X1 X2)                     ==> N_Q
              (rem X1 X2)                     ==> X_R
              (mod X1 X2)                     ==> X_M

     where N_Q is X1/X2 rounded towards zero, 0 < |X_R| < |X2|, 0 <
     |X_M| < |X2|, X_R and X_M differ from X1 by a multiple of X2, X_R
     has the same sign as X1, and X_M has the same sign as X2.

     From this we can conclude that for X2 not equal to 0,

               (= X1 (+ (* X2 (quo X1 X2))
                     (rem X1 X2)))
                                                 ==>  #t

     provided all numbers involved in that computation are exact.

              (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

 -- Function: ln Z
     These procedures are part of every implementation that supports
     general real numbers.  `Ln' computes the natural logarithm of Z

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


 -- Function: abs x
     For real argument X, `Abs' returns the absolute value of X'
     otherwise it signals an error.

     (abs -7)                               ==>  7


 -- Function: make-rectangular x1 x2
 -- Function: make-polar x3 x4
     These procedures are part of every implementation that supports
     general complex numbers.  Suppose X1, X2, X3, and X4 are real
     numbers and Z is a complex number such that

                         Z = X1 + X2i = X3 . e^i X4

     Then

     (make-rectangular X1 X2)               ==> Z
     (make-polar X3 X4)                     ==> Z

     where -pi < x_angle <= pi with x_angle = X4 + 2pi n for some
     integer n.

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



File: slib.info,  Node: Prime Numbers,  Next: Random Numbers,  Prev: Irrational Real Functions,  Up: Mathematical Packages

5.5 Prime Numbers
=================

`(require 'factor)' 

 -- Variable: prime:prngs
     PRIME:PRNGS is the random-state (*note Random Numbers::) used by
     these procedures.  If you call these procedures from more than one
     thread (or from interrupt), `random' may complain about reentrant
     calls.
  _Note:_ The prime test and generation procedures implement (or use)
the Solovay-Strassen primality test. See

   * Robert Solovay and Volker Strassen, `A Fast Monte-Carlo Test for
     Primality', SIAM Journal on Computing, 1977, pp 84-85.

 -- Function: jacobi-symbol p q
     Returns the value (+1, -1, or 0) of the Jacobi-Symbol of exact
     non-negative integer P and exact positive odd integer Q.

 -- Variable: prime:trials
     PRIME:TRIALS the maxinum number of iterations of Solovay-Strassen
     that will be done to test a number for primality.

 -- Function: prime? n
     Returns `#f' if N is composite; `#t' if N is prime.  There is a
     slight chance `(expt 2 (- prime:trials))' that a composite will
     return `#t'.

 -- Function: primes< start count
     Returns a list of the first COUNT prime numbers less than START.
     If there are fewer than COUNT prime numbers less than START, then
     the returned list will have fewer than START elements.

 -- Function: primes> start count
     Returns a list of the first COUNT prime numbers greater than START.

 -- Function: factor k
     Returns a list of the prime factors of K.  The order of the
     factors is unspecified.  In order to obtain a sorted list do
     `(sort! (factor K) <)'.


File: slib.info,  Node: Random Numbers,  Next: Discrete Fourier Transform,  Prev: Prime Numbers,  Up: Mathematical Packages

5.6 Random Numbers
==================

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 "DIEHARD" (`http://stat.fsu.edu/~geo/diehard.html').
`diehard.c' has a bug which the patch
`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
`0', the numbers generated pass DIEHARD; but when bits are combined
from sequential bytes, tests fail.  With the seed
`http://swissnet.ai.mit.edu/~jaffer/SLIB.html', all of those tests pass.

* Menu:

* Exact Random Numbers::        'random
* Inexact Random Numbers::      'random-inexact


File: slib.info,  Node: Exact Random Numbers,  Next: Inexact Random Numbers,  Prev: Random Numbers,  Up: Random Numbers

5.6.1 Exact Random Numbers
--------------------------

`(require 'random)' 

 -- Function: random n state
 -- Function: random n
     N must be an exact positive integer.  `random' returns an exact
     integer between zero (inclusive) and N (exclusive).  The values
     returned by `random' are uniformly distributed from 0 to N.

     The optional argument STATE must be of the type returned by
     `(seed->random-state)' or `(make-random-state)'.  It defaults to
     the value of the variable `*random-state*'.  This object is used
     to maintain the state of the pseudo-random-number generator and is
     altered as a side effect of calls to `random'.

 -- Variable: *random-state*
     Holds a data structure that encodes the internal state of the
     random-number generator that `random' uses by default.  The nature
     of this data structure is implementation-dependent.  It may be
     printed out and successfully read back in, but may or may not
     function correctly as a random-number state object in another
     implementation.

 -- Function: copy-random-state state
     Returns a new copy of argument STATE.

 -- Function: copy-random-state
     Returns a new copy of `*random-state*'.

 -- Function: seed->random-state seed
     Returns a new object of type suitable for use as the value of the
     variable `*random-state*' or as a second argument to `random'.
     The number or string SEED is used to initialize the state.  If
     `seed->random-state' is called twice with arguments which are
     `equal?', then the returned data structures will be `equal?'.
     Calling `seed->random-state' with unequal arguments will nearly
     always return unequal states.

 -- Function: make-random-state
 -- Function: make-random-state obj
     Returns a new object of type suitable for use as the value of the
     variable `*random-state*' or as a second argument to `random'.  If
     the optional argument OBJ is given, it should be a printable
     Scheme object; the first 50 characters of its printed
     representation will be used as the seed.  Otherwise the value of
     `*random-state*' is used as the seed.


File: slib.info,  Node: Inexact Random Numbers,  Prev: Exact Random Numbers,  Up: Random Numbers

5.6.2 Inexact Random Numbers
----------------------------

`(require 'random-inexact)' 

 -- Function: random:uniform
 -- Function: random:uniform state
     Returns an uniformly distributed inexact real random number in the
     range between 0 and 1.

 -- Function: random:exp
 -- Function: random:exp state
     Returns an inexact real in an exponential distribution with mean
     1.  For an exponential distribution with mean U use
     `(* U (random:exp))'.

 -- Function: random:normal
 -- Function: random:normal state
     Returns an inexact real in a normal distribution with mean 0 and
     standard deviation 1.  For a normal distribution with mean M and
     standard deviation D use `(+ M (* D (random:normal)))'.

 -- Procedure: random:normal-vector! vect
 -- Procedure: random:normal-vector! vect state
     Fills VECT with inexact real random numbers which are independent
     and standard normally distributed (i.e., with mean 0 and variance
     1).

 -- Procedure: random:hollow-sphere! vect
 -- Procedure: random:hollow-sphere! vect state
     Fills VECT with inexact real random numbers the sum of whose
     squares is equal to 1.0.  Thinking of VECT as coordinates in space
     of dimension n = `(vector-length VECT)', the coordinates are
     uniformly distributed over the surface of the unit n-shere.

 -- Procedure: random:solid-sphere! vect
 -- Procedure: random:solid-sphere! vect state
     Fills VECT with inexact real random numbers the sum of whose
     squares is less than 1.0.  Thinking of VECT as coordinates in
     space of dimension N = `(vector-length VECT)', the coordinates are
     uniformly distributed within the unit N-shere.  The sum of the
     squares of the numbers is returned.


File: slib.info,  Node: Discrete Fourier Transform,  Next: Cyclic Checksum,  Prev: Random Numbers,  Up: Mathematical Packages

5.7 Discrete Fourier Transform
==============================

`(require 'dft)' or `(require 'Fourier-transform)' 

  `fft' and `fft-1' compute the Fast-Fourier-Transforms (O(n*log(n)))
of arrays whose dimensions are all powers of 2.

  `sft' and `sft-1' compute the Discrete-Fourier-Transforms for all
combinations of dimensions (O(n^2)).

 -- Function: sft array prot
 -- Function: sft array
     ARRAY is an array of positive rank.  `sft' returns an array of
     type PROT (defaulting to ARRAY) of complex numbers comprising the
     "Discrete Fourier Transform" of ARRAY.  

 -- Function: sft-1 array prot
 -- Function: sft-1 array
     ARRAY is an array of positive rank.  `sft-1' returns an array of
     type PROT (defaulting to ARRAY) of complex numbers comprising the
     inverse Discrete Fourier Transform of ARRAY.

 -- Function: fft array prot
 -- Function: fft array
     ARRAY is an array of positive rank whose dimensions are all powers
     of 2.  `fft' returns an array of type PROT (defaulting to ARRAY)
     of complex numbers comprising the Discrete Fourier Transform of
     ARRAY.

 -- Function: fft-1 array prot
 -- Function: fft-1 array
     ARRAY is an array of positive rank whose dimensions are all powers
     of 2.  `fft-1' returns an array of type PROT (defaulting to ARRAY)
     of complex numbers comprising the inverse Discrete Fourier
     Transform of ARRAY.

  `dft' and `dft-1' compute the discrete Fourier transforms using the
best method for decimating each dimension.

 -- Function: dft array prot
 -- Function: dft array
     `dft' returns an array of type PROT (defaulting to ARRAY) of
     complex numbers comprising the Discrete Fourier Transform of ARRAY.

 -- Function: dft-1 array prot
 -- Function: dft-1 array
     `dft-1' returns an array of type PROT (defaulting to ARRAY) of
     complex numbers comprising the inverse Discrete Fourier Transform
     of ARRAY.

`(fft-1 (fft ARRAY))' will return an array of values close to ARRAY.

     (fft '#(1 0+i -1 0-i 1 0+i -1 0-i)) =>

     #(0.0 0.0 0.0+628.0783185208527e-18i 0.0
       0.0 0.0 8.0-628.0783185208527e-18i 0.0)

     (fft-1 '#(0 0 0 0 0 0 8 0)) =>

     #(1.0 -61.23031769111886e-18+1.0i -1.0 61.23031769111886e-18-1.0i
       1.0 -61.23031769111886e-18+1.0i -1.0 61.23031769111886e-18-1.0i)


File: slib.info,  Node: Cyclic Checksum,  Next: Graphing,  Prev: Discrete Fourier Transform,  Up: Mathematical Packages

5.8 Cyclic Checksum
===================

`(require 'crc)' Cyclic Redundancy Checks using Galois field GF(2)
polynomial arithmetic are used for error detection in many data
transmission and storage applications.

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:

   * the byte-order and bit-order of the data stream;

   * whether the CRC or its inverse is being calculated;

   * the initial CRC value; and

   * whether and where the CRC value is appended (inverted or
     non-inverted) to the data stream.


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.

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:

   * Philip Koopman and Tridib Chakravarty,
     "Cyclic Redundancy Code (CRC) Polynomial Selection For Embedded
     Networks",
     The International Conference on Dependable Systems and Networks,
     DSN-2004.

`http://www.ece.cmu.edu/~koopman/roses/dsn04/koopman04_crc_poly_embedded.pdf'

There is even some controversy over the polynomials themselves.

 -- 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 `crc-32-polynomial' uses the latter definition.

 -- 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.

 -- 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.

 -- 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).

 -- 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.

 -- 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

 -- 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.

 -- 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.

 -- 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.

Each of these polynomial constants is a string of `1's and `0's, the
exponent of each power of X in descending order.

 -- Function: crc:make-table poly
     POLY must be string of `1's and `0's beginning with `1' and having
     length greater than 8.  `crc:make-table' returns a vector of 256
     integers, such that:

          (set! CRC
                (logxor (ash (logand (+ -1 (ash 1 (- DEG 8))) CRC) 8)
                        (vector-ref CRC-TABLE
                                    (logxor (ash CRC (- 8 DEG)) BYTE))))

     will compute the CRC with the 8 additional bits in BYTE; where CRC
     is the previous accumulated CRC value, DEG is the degree of POLY,
     and CRC-TABLE is the vector returned by `crc:make-table'.

     If the implementation does not support DEG-bit integers, then
     `crc:make-table' returns #f.


 -- Function: cksum file
     Computes the P1003.2/D11.2 (POSIX.2) 32-bit checksum of FILE.

          (require 'crc)
          (cksum (in-vicinity (library-vicinity) "ratize.scm"))
          => 157103930

 -- Function: cksum port
     Computes the checksum of the bytes read from PORT until the
     end-of-file.


`cksum-string', which returns the P1003.2/D11.2 (POSIX.2) 32-bit
checksum of the bytes in STR, can be defined as follows:

     (require 'string-port)
     (define (cksum-string str) (call-with-input-string str cksum))

 -- Function: crc16 file
     Computes the USB data-packet (16-bit) CRC of FILE.

 -- Function: crc16 port
     Computes the USB data-packet (16-bit) CRC of the bytes read from
     PORT until the end-of-file.

     `crc16' calculates the same values as the crc16.pl program given
     in http://www.usb.org/developers/data/crcdes.pdf.


 -- Function: crc5 file
     Computes the USB token (5-bit) CRC of FILE.

 -- Function: crc5 port
     Computes the USB token (5-bit) CRC of the bytes read from PORT
     until the end-of-file.

     `crc5' calculates the same values as the crc5.pl program given in
     http://www.usb.org/developers/data/crcdes.pdf.



File: slib.info,  Node: Graphing,  Next: Solid Modeling,  Prev: Cyclic Checksum,  Up: Mathematical Packages

5.9 Graphing
============

* Menu:

* Character Plotting::
* PostScript Graphing::


File: slib.info,  Node: Character Plotting,  Next: PostScript Graphing,  Prev: Graphing,  Up: Graphing

5.9.1 Character Plotting
------------------------

`(require 'charplot)' 

 -- Variable: 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 CHARPLOT:DIMENSIONS is the
     `output-port-height' and `output-port-width' of
     `current-output-port'.

 -- Procedure: plot coords x-label y-label
     COORDS is a list or vector of coordinates, lists of x and y
     coordinates.  X-LABEL and Y-LABEL are strings with which to label
     the x and y axes.

     Example:
          (require '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)")
          -|
            Sin(x)   _________________________________________
                   1|-       ****                             |
                    |      **    **                           |
                0.75|-    *        *                          |
                    |    *          *                         |
                 0.5|-  *            *                        |
                    |  *                                     *|
                0.25|-                *                     * |
                    | *                *                      |
                   0|-------------------*------------------*--|
                    |                                     *   |
               -0.25|-                   *               *    |
                    |                     *             *     |
                -0.5|-                     *                  |
                    |                       *          *      |
               -0.75|-                       *        *       |
                    |                         **    **        |
                  -1|-                          ****          |
                    |:_____._____:_____._____:_____._____:____|
               x                 2           4           6

 -- Procedure: plot func x1 x2
 -- Procedure: plot func x1 x2 npts
     Plots the function of one argument FUNC over the range X1 to X2.
     If the optional integer argument NPTS is supplied, it specifies
     the number of points to evaluate FUNC at.

          (plot sin 0 (* 2 pi))
          -|
                     _________________________________________
                   1|-:       ****                            |
                    | :     **    **                          |
                0.75|-:    *        *                         |
                    | :   *          *                        |
                 0.5|-:  **          **                       |
                    | : *             *                       |
                0.25|-:**              **                     |
                    | :*                *                     |
                   0|-*------------------*--------------------|
                    | :                  *                 *  |
               -0.25|-:                   **              **  |
                    | :                    *             *    |
                -0.5|-:                     *           **    |
                    | :                      *          *     |
               -0.75|-:                       *       **      |
                    | :                        **    **       |
                  -1|-:                          ****         |
                    |_:_____._____:_____._____:_____._____:___|
                      0           2           4           6

 -- Procedure: histograph data label
     Creates and displays a histogram of the numerical values contained
     in vector or list DATA

          (require 'random-inexact)
          (histograph (do ((idx 99 (+ -1 idx))
                           (lst '() (cons (* .02 (random:normal)) lst)))
                          ((negative? idx) lst))
                      "normal")
          -|
                     _________________________________________
                   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


File: slib.info,  Node: PostScript Graphing,  Prev: Character Plotting,  Up: Graphing

5.9.2 PostScript Graphing
-------------------------

`(require 'eps-graph)'

This is a graphing package creating encapsulated-PostScript files.  Its
motivations and design choice are described in
`http://swiss.csail.mit.edu/~jaffer/Docupage/grapheps'

A dataset to be plotted is taken from a 2-dimensional array.
Corresponding coordinates are in rows.  Coordinates from any pair of
columns can be plotted.

 -- Function: create-postscript-graph filename.eps size elt1 ...
     FILENAME.EPS should be a string naming an output file to be
     created.  SIZE should be an exact integer, a list of two exact
     integers, or #f.  ELT1, ... are values returned by graphing
     primitives described here.

     `create-postscript-graph' creates an "Encapsulated-PostScript"
     file named FILENAME.EPS containing graphs as directed by the ELT1,
     ... arguments.

     The size of the graph is determined by the SIZE argument.  If a
     list of two integers, they specify the width and height.  If one
     integer, then that integer is the width and the height is 3/4 of
     the width.  If #f, the graph will be 800 by 600.

These graphing procedures should be called as arguments to
`create-postscript-graph'.  The order of these arguments is
significant; PostScript graphics state is affected serially from the
first ELT argument to the last.

 -- Function: whole-page
     Pushes a rectangle for the whole encapsulated page onto the
     PostScript stack.  This pushed rectangle is an implicit argument to
     `partition-page' or `setup-plot'.

* Menu:

* Column Ranges::
* Drawing the Graph::
* Graphics Context::
* Rectangles::
* Legending::
* Legacy Plotting::
* Example Graph::


File: slib.info,  Node: Column Ranges,  Next: Drawing the Graph,  Prev: PostScript Graphing,  Up: PostScript Graphing

5.9.2.1 Column Ranges
.....................

A "range" is a list of two numbers, the minimum and the maximum.  Ranges
can be given explicity or computed in PostScript by `column-range'.

 -- Function: column-range array k
     Returns the range of values in 2-dimensional ARRAY column K.

 -- Function: pad-range range p
     Expands RANGE by P/100 on each end.

 -- Function: snap-range range
     Expands RANGE to round number of ticks.

 -- Function: combine-ranges range1 range2 ...
     Returns the minimal range covering all RANGE1, RANGE2, ...

 -- Function: setup-plot x-range y-range pagerect
 -- Function: setup-plot x-range y-range
     X-RANGE and Y-RANGE should each be a list of two numbers or the
     value returned by `pad-range', `snap-range', or `combine-range'.
     PAGERECT is the rectangle bounding the graph to be drawn; if
     missing, the rectangle from the top of the PostScript stack is
     popped and used.

     Based on the given ranges, `setup-plot' sets up scaling and
     margins for making a graph.  The margins are sized proportional to
     the FONTHEIGHT value at the time of the call to setup-plot.
     `setup-plot' sets two variables:

    PLOTRECT
          The region where data points will be plotted.

    GRAPHRECT
          The PAGERECT argument to `setup-plot'.  Includes plotrect,
          legends, etc.


File: slib.info,  Node: Drawing the Graph,  Next: Graphics Context,  Prev: Column Ranges,  Up: PostScript Graphing

5.9.2.2 Drawing the Graph
.........................

 -- Function: plot-column array x-column y-column proc3s
     Plots points with x coordinate in X-COLUMN of ARRAY and y
     coordinate Y-COLUMN of ARRAY.  The symbol PROC3S specifies the
     type of glyph or drawing style for presenting these coordinates.

The glyphs and drawing styles available are:

`line'
     Draws line connecting points in order.

`mountain'
     Fill area below line connecting points.

`cloud'
     Fill area above line connecting points.

`impulse'
     Draw line from x-axis to each point.

`bargraph'
     Draw rectangle from x-axis to each point.

`disc'
     Solid round dot.

`point'
     Minimal point - invisible if linewidth is 0.

`square'
     Square box.

`diamond'
     Square box at 45.o

`plus'
     Plus sign.

`cross'
     X sign.

`triup'
     Triangle pointing upward

`tridown'
     Triangle pointing downward

`pentagon'
     Five sided polygon

`circle'
     Hollow circle


File: slib.info,  Node: Graphics Context,  Next: Rectangles,  Prev: Drawing the Graph,  Up: PostScript Graphing

5.9.2.3 Graphics Context
........................

 -- Function: in-graphic-context arg ...
     Saves the current graphics state, executes ARGS, then restores to
     saved graphics state.

 -- Function: set-color color
     COLOR should be a string naming a Resene color, a saturate color,
     or a number between 0 and 100.

     `set-color' sets the PostScript color to the color of the given
     string, or a grey value between black (0) and white (100).

 -- Function: set-font name fontheight
     NAME should be a (case-sensitive) string naming a PostScript font.
     FONTHEIGHT should be a positive real number.

     `set-font' Changes the current PostScript font to NAME with height
     equal to FONTHEIGHT.  The default font is Helvetica (12pt).

The base set of PostScript fonts is:

Times          Times-Italic       Times-Bold         Times-BoldItalic
Helvetica      Helvetica-Oblique  Helvetica-Bold     Helvetica-BoldOblique
Courier        Courier-Oblique    Courier-Bold       Courier-BoldOblique
Symbol                                               

Line parameters do no affect fonts; they do effect glyphs.

 -- Function: set-linewidth w
     The default linewidth is 1.  Setting it to 0 makes the lines drawn
     as skinny as possible.  Linewidth must be much smaller than
     glyphsize for readable glyphs.

 -- Function: set-linedash j k
     Lines are drawn J-on K-off.

 -- Function: set-linedash j
     Lines are drawn J-on J-off.

 -- Function: set-linedash
     Turns off dashing.

 -- Function: set-glyphsize w
     Sets the (PostScript) variable glyphsize to W.  The default
     glyphsize is 6.

The effects of `clip-to-rect' are also part of the graphic context.


File: slib.info,  Node: Rectangles,  Next: Legending,  Prev: Graphics Context,  Up: PostScript Graphing

5.9.2.4 Rectangles
..................

A "rectangle" is a list of 4 numbers; the first two elements are the x
and y coordinates of lower left corner of the rectangle.  The other two
elements are the width and height of the rectangle.

 -- Function: whole-page
     Pushes a rectangle for the whole encapsulated page onto the
     PostScript stack.  This pushed rectangle is an implicit argument to
     `partition-page' or `setup-plot'.

 -- Function: partition-page xparts yparts
     Pops the rectangle currently on top of the stack and pushes XPARTS
     * YPARTS sub-rectangles onto the stack in decreasing y and
     increasing x order.  If you are drawing just one graph, then you
     don't need `partition-page'.

 -- Variable: plotrect
     The rectangle where data points should be plotted.  PLOTRECT is
     set by `setup-plot'.

 -- Variable: graphrect
     The PAGERECT argument of the most recent call to `setup-plot'.
     Includes plotrect, legends, etc.

 -- Function: fill-rect rect
     fills RECT with the current color.

 -- Function: outline-rect rect
     Draws the perimiter of RECT in the current color.

 -- Function: clip-to-rect rect
     Modifies the current graphics-state so that nothing will be drawn
     outside of the rectangle RECT.  Use `in-graphic-context' to limit
     the extent of `clip-to-rect'.


File: slib.info,  Node: Legending,  Next: Legacy Plotting,  Prev: Rectangles,  Up: PostScript Graphing

5.9.2.5 Legending
.................

 -- Function: title-top title subtitle
 -- Function: title-top title
     Puts a TITLE line and an optional SUBTITLE line above the
     `graphrect'.

 -- Function: title-bottom title subtitle
 -- Function: title-bottom title
     Puts a TITLE line and an optional SUBTITLE line below the
     `graphrect'.

 -- Variable: topedge
 -- Variable: bottomedge
     These edge coordinates of `graphrect' are suitable for passing as
     the first argument to `rule-horizontal'.

 -- Variable: leftedge
 -- Variable: rightedge
     These edge coordinates of `graphrect' are suitable for passing as
     the first argument to `rule-vertical'.

 -- Function: set-margin-templates left right
     The margin-templates are strings whose displayed width is used to
     reserve space for the left and right side numerical legends.  The
     default values are "-.0123456789".

 -- Function: rule-vertical x-coord text tick-width
     Draws a vertical ruler with X coordinate X-COORD and labeled with
     string TEXT.  If TICK-WIDTH is positive, then the ticks are
     TICK-WIDTH long on the right side of X-COORD; and TEXT and numeric
     legends are on the left.  If TICK-WIDTH is negative, then the
     ticks are -TICK-WIDTH long on the left side of X-COORD; and TEXT
     and numeric legends are on the right.

 -- Function: rule-horizontal y-coord text tick-height
     Draws a horizontal ruler with Y coordinate Y-COORD and labeled with
     string TEXT.  If TICK-HEIGHT is positive, then the ticks are
     TICK-HEIGHT long on the top side of Y-COORD; and TEXT and numeric
     legends are on the bottom.  If TICK-HEIGHT is negative, then the
     ticks are -TICK-HEIGHT long on the bottom side of Y-COORD; and
     TEXT and numeric legends are on the top.

 -- Function: y-axis
     Draws the y-axis.

 -- Function: x-axis
     Draws the x-axis.

 -- Function: grid-verticals
     Draws vertical lines through `graphrect' at each tick on the
     vertical ruler.

 -- Function: grid-horizontals
     Draws horizontal lines through `graphrect' at each tick on the
     horizontal ruler.


File: slib.info,  Node: Legacy Plotting,  Next: Example Graph,  Prev: Legending,  Up: PostScript Graphing

5.9.2.6 Legacy Plotting
.......................

 -- Variable: graph:dimensions
     A list of the width and height of the graph to be plotted using
     `plot'.

 -- Function: plot func x1 x2 npts
 -- Function: plot func x1 x2
     Creates and displays using `(system "gv tmp.eps")' an encapsulated
     PostScript graph of the function of one argument FUNC over the
     range X1 to X2.  If the optional integer argument NPTS is
     supplied, it specifies the number of points to evaluate FUNC at.

 -- Function: x1 x2 npts func1 func2 ...
     Creates and displays an encapsulated PostScript graph of the
     one-argument functions FUNC1, FUNC2, ... over the range X1 to X2
     at NPTS points.

 -- Function: plot coords x-label y-label
     COORDS is a list or vector of coordinates, lists of x and y
     coordinates.  X-LABEL and Y-LABEL are strings with which to label
     the x and y axes.


File: slib.info,  Node: Example Graph,  Prev: Legacy Plotting,  Up: PostScript Graphing

5.9.2.7 Example Graph
.....................

The file `am1.5.html', a table of solar irradiance, is fetched with
`wget' if it isn't already in the working directory.  The file is read
and stored into an array, IRRADIANCE.

  `create-postscript-graph' is then called to create an
encapsulated-PostScript file, `solarad.eps'.  The size of the page is
set to 600 by 300.  `whole-page' is called and leaves the rectangle on
the PostScript stack.  `setup-plot' is called with a literal range for
x and computes the range for column 1.

  Two calls to `top-title' are made so a different font can be used for
the lower half.  `in-graphic-context' is used to limit the scope of the
font change.  The graphing area is outlined and a rule drawn on the
left side.

  Because the X range was intentionally reduced, `in-graphic-context'
is called and `clip-to-rect' limits drawing to the plotting area.  A
black line is drawn from data column 1.  That line is then overlayed
with a mountain plot of the same column colored "Bright Sun".

  After returning from the `in-graphic-context', the bottom ruler is
drawn.  Had it been drawn earlier, all its ticks would have been
painted over by the mountain plot.

  The color is then changed to `seagreen' and the same graphrect is
setup again, this time with a different Y scale, 0 to 1000.  The
graphic context is again clipped to PLOTRECT, linedash is set, and
column 2 is plotted as a dashed line.  Finally the rightedge is ruled.
Having the line and its scale both in green helps disambiguate the
scales.

     (require 'eps-graph)
     (require 'line-i/o)
     (require 'string-port)

     (define irradiance
       (let ((url "http://www.pv.unsw.edu.au/am1.5.html")
             (file "am1.5.html"))
         (define (read->list line)
           (define elts '())
           (call-with-input-string line
             (lambda (iprt) (do ((elt (read iprt) (read iprt)))
                                ((eof-object? elt) elts)
                              (set! elts (cons elt elts))))))
         (if (not (file-exists? file))
             (system (string-append "wget -c -O" file " " url)))
         (call-with-input-file file
           (lambda (iprt)
             (define lines '())
             (do ((line (read-line iprt) (read-line iprt)))
                 ((eof-object? line)
                  (let ((nra (make-array (A:floR64b)
                                           (length lines)
                                           (length (car lines)))))
                    (do ((lns lines (cdr lns))
                         (idx (+ -1 (length lines)) (+ -1 idx)))
                        ((null? lns) nra)
                      (do ((kdx (+ -1 (length (car lines))) (+ -1 kdx))
                           (lst (car lns) (cdr lst)))
                          ((null? lst))
                        (array-set! nra (car lst) idx kdx)))))
               (if (and (positive? (string-length line))
                        (char-numeric? (string-ref line 0)))
                   (set! lines (cons (read->list line) lines))))))))

     (let ((xrange '(.25 2.5)))
       (create-postscript-graph
        "solarad.eps" '(600 300)
        (whole-page)
        (setup-plot xrange (column-range irradiance 1))
        (title-top
         "Solar Irradiance   http://www.pv.unsw.edu.au/am1.5.html")
        (in-graphic-context
         (set-font "Helvetica-Oblique" 12)
         (title-top
          ""
          "Key Centre for Photovoltaic Engineering UNSW - Air Mass 1.5 Global Spectrum"))
        (outline-rect plotrect)
        (rule-vertical leftedge "W/(m^2.um)" 10)
        (in-graphic-context (clip-to-rect plotrect)
                            (plot-column irradiance 0 1 'line)
                            (set-color "Bright Sun")
                            (plot-column irradiance 0 1 'mountain)
                            )
        (rule-horizontal bottomedge "Wavelength in .um" 5)
        (set-color 'seagreen)

        (setup-plot xrange '(0 1000) graphrect)
        (in-graphic-context (clip-to-rect plotrect)
                            (set-linedash 5 2)
                            (plot-column irradiance 0 2 'line))
        (rule-vertical rightedge "Integrated .W/(m^2)" -10)
        ))

     (system "gv solarad.eps")


File: slib.info,  Node: Solid Modeling,  Next: Color,  Prev: Graphing,  Up: Mathematical Packages

5.10 Solid Modeling
===================

`(require 'solid)' 

`http://swiss.csail.mit.edu/~jaffer/Solid/#Example' gives an example
use of this package.

 -- Function: vrml node ...
     Returns the VRML97 string (including header) of the concatenation
     of strings NODES, ....

 -- Function: vrml-append node1 node2 ...
     Returns the concatenation with interdigitated newlines of strings
     NODE1, NODE2, ....

 -- Function: vrml-to-file file node ...
     Writes to file named FILE the VRML97 string (including header) of
     the concatenation of strings NODES, ....

 -- Function: world:info title info ...
     Returns a VRML97 string setting the title of the file in which it
     appears to TITLE.  Additional strings INFO, ... are comments.

VRML97 strings passed to `vrml' and `vrml-to-file' as arguments will
appear in the resulting VRML code.  This string turns off the headlight
at the viewpoint:
     " NavigationInfo {headlight FALSE}"

 -- Function: scene:panorama front right back left top bottom
     Specifies the distant images on the inside faces of the cube
     enclosing the virtual world.

 -- Function: scene:sphere colors angles
     COLORS is a list of color objects.  Each may be of type *Note
     color: Color Data-Type, a 24-bit sRGB integer, or a list of 3
     numbers between 0.0 and 1.0.

     ANGLES is a list of non-increasing angles the same length as
     COLORS.  Each angle is between 90 and -90 degrees.  If 90 or -90
     are not elements of ANGLES, then the color at the zenith and nadir
     are taken from the colors paired with the angles nearest them.

     `scene:sphere' fills horizontal bands with interpolated colors on
     the background sphere encasing the world.

 -- Function: scene:sky-and-dirt
     Returns a blue and brown background sphere encasing the world.

 -- Function: scene:sky-and-grass
     Returns a blue and green background sphere encasing the world.

 -- Function: scene:sun latitude julian-day hour turbidity strength
 -- Function: scene:sun latitude julian-day hour turbidity
     LATITUDE is the virtual place's latitude in degrees.  JULIAN-DAY
     is an integer from 0 to 366, the day of the year.  HOUR is a real
     number from 0 to 24 for the time of day; 12 is noon.  TURBIDITY is
     the degree of fogginess described in *Note turbidity: Daylight.

     `scene:sun' returns a bright yellow, distant sphere where the sun
     would be at HOUR on JULIAN-DAY at LATITUDE.  If STRENGTH is
     positive, included is a light source of STRENGTH (default 1).

 -- Function: scene:overcast latitude julian-day hour turbidity strength
 -- Function: scene:overcast latitude julian-day hour turbidity
     LATITUDE is the virtual place's latitude in degrees.  JULIAN-DAY
     is an integer from 0 to 366, the day of the year.  HOUR is a real
     number from 0 to 24 for the time of day; 12 is noon.  TURBIDITY is
     the degree of cloudiness described in *Note turbidity: Daylight.

     `scene:overcast' returns an overcast sky as it might look at HOUR
     on JULIAN-DAY at LATITUDE.  If STRENGTH is positive, included is
     an ambient light source of STRENGTH (default 1).

Viewpoints are objects in the virtual world, and can be transformed
individually or with solid objects.

 -- Function: scene:viewpoint name distance compass pitch
 -- Function: scene:viewpoint name distance compass
     Returns a viewpoint named NAME facing the origin and placed
     DISTANCE from it.  COMPASS is a number from 0 to 360 giving the
     compass heading.  PITCH is a number from -90 to 90, defaulting to
     0, specifying the angle from the horizontal.

 -- Function: scene:viewpoints proximity
     Returns 6 viewpoints, one at the center of each face of a cube
     with sides 2 * PROXIMITY, centered on the origin.

Light Sources
-------------

In VRML97, lights shine only on objects within the same children node
and descendants of that node.  Although it would have been convenient
to let light direction be rotated by `solid:rotation', this restricts a
rotated light's visibility to objects rotated with it.

To workaround this limitation, these directional light source
procedures accept either Cartesian or spherical coordinates for
direction.  A spherical coordinate is a list `(THETA AZIMUTH)'; where
THETA is the angle in degrees from the zenith, and AZIMUTH is the angle
in degrees due west of south.

It is sometimes useful for light sources to be brighter than `1'.  When
INTENSITY arguments are greater than 1, these functions gang multiple
sources to reach the desired strength.

 -- Function: light:ambient color intensity
 -- Function: light:ambient color
     Ambient light shines on all surfaces with which it is grouped.

     COLOR is a an object of type *Note color: Color Data-Type, a
     24-bit sRGB integer, or a list of 3 numbers between 0.0 and 1.0.
     If COLOR is #f, then the default color will be used.  INTENSITY is
     a real non-negative number defaulting to `1'.

     `light:ambient' returns a light source or sources of COLOR with
     total strength of INTENSITY (or 1 if omitted).

 -- Function: light:directional color direction intensity
 -- Function: light:directional color direction
 -- Function: light:directional color
     Directional light shines parallel rays with uniform intensity on
     all objects with which it is grouped.

     COLOR is a an object of type *Note color: Color Data-Type, a
     24-bit sRGB integer, or a list of 3 numbers between 0.0 and 1.0.
     If COLOR is #f, then the default color will be used.

     DIRECTION must be a list or vector of 2 or 3 numbers specifying
     the direction to this light.  If DIRECTION has 2 numbers, then
     these numbers are the angle from zenith and the azimuth in
     degrees; if DIRECTION has 3 numbers, then these are taken as a
     Cartesian vector specifying the direction to the light source.
     The default direction is upwards; thus its light will shine down.

     INTENSITY is a real non-negative number defaulting to `1'.

     `light:directional' returns a light source or sources of COLOR
     with total strength of INTENSITY, shining from DIRECTION.

 -- Function: light:beam attenuation radius aperture peak
 -- Function: light:beam attenuation radius aperture
 -- Function: light:beam attenuation radius
 -- Function: light:beam attenuation
     ATTENUATION is a list or vector of three nonnegative real numbers
     specifying the reduction of intensity, the reduction of intensity
     with distance, and the reduction of intensity as the square of
     distance.  RADIUS is the distance beyond which the light does not
     shine.  RADIUS defaults to `100'.

     APERTURE is a real number between 0 and 180, the angle centered on
     the light's axis through which it sheds some light.  PEAK is a
     real number between 0 and 90, the angle of greatest illumination.

 -- Function: light:point location color intensity beam
 -- Function: light:point location color intensity
 -- Function: light:point location color
 -- Function: light:point location
     Point light radiates from LOCATION, intensity decreasing with
     distance, towards all objects with which it is grouped.

     COLOR is a an object of type *Note color: Color Data-Type, a
     24-bit sRGB integer, or a list of 3 numbers between 0.0 and 1.0.
     If COLOR is #f, then the default color will be used.  INTENSITY is
     a real non-negative number defaulting to `1'.  BEAM is a structure
     returned by `light:beam' or #f.

     `light:point' returns a light source or sources at LOCATION of
     COLOR with total strength INTENSITY and BEAM properties.  Note
     that the pointlight itself is not visible.  To make it so, place
     an object with emissive appearance at LOCATION.

 -- Function: light:spot location direction color intensity beam
 -- Function: light:spot location direction color intensity
 -- Function: light:spot location direction color
 -- Function: light:spot location direction
 -- Function: light:spot location
     Spot light radiates from LOCATION towards DIRECTION, intensity
     decreasing with distance, illuminating objects with which it is
     grouped.

     DIRECTION must be a list or vector of 2 or 3 numbers specifying
     the direction to this light.  If DIRECTION has 2 numbers, then
     these numbers are the angle from zenith and the azimuth in
     degrees; if DIRECTION has 3 numbers, then these are taken as a
     Cartesian vector specifying the direction to the light source.
     The default direction is upwards; thus its light will shine down.

     COLOR is a an object of type *Note color: Color Data-Type, a
     24-bit sRGB integer, or a list of 3 numbers between 0.0 and 1.0.
     If COLOR is #f, then the default color will be used.

     INTENSITY is a real non-negative number defaulting to `1'.

     `light:spot' returns a light source or sources at LOCATION of
     DIRECTION with total strength COLOR.  Note that the spotlight
     itself is not visible.  To make it so, place an object with
     emissive appearance at LOCATION.

Object Primitives
-----------------

 -- Function: solid:box geometry appearance
 -- Function: solid:box geometry
     GEOMETRY must be a number or a list or vector of three numbers.
     If GEOMETRY is a number, the `solid:box' returns a cube with sides
     of length GEOMETRY centered on the origin.  Otherwise, `solid:box'
     returns a rectangular box with dimensions GEOMETRY centered on the
     origin.  APPEARANCE determines the surface properties of the
     returned object.

 -- Function: solid:lumber geometry appearance
     Returns a box of the specified GEOMETRY, but with the y-axis of a
     texture specified in APPEARANCE being applied along the longest
     dimension in GEOMETRY.

 -- Function: solid:cylinder radius height appearance
 -- Function: solid:cylinder radius height
     Returns a right cylinder with dimensions `(abs RADIUS)' and `(abs
     HEIGHT)' centered on the origin.  If HEIGHT is positive, then the
     cylinder ends will be capped.  If RADIUS is negative, then only
     the ends will appear.  APPEARANCE determines the surface
     properties of the returned object.

 -- Function: solid:disk radius thickness appearance
 -- Function: solid:disk radius thickness
     THICKNESS must be a positive real number.  `solid:disk' returns a
     circular disk with dimensions RADIUS and THICKNESS centered on the
     origin.  APPEARANCE determines the surface properties of the
     returned object.

 -- Function: solid:cone radius height appearance
 -- Function: solid:cone radius height
     Returns an isosceles cone with dimensions RADIUS and HEIGHT
     centered on the origin.  APPEARANCE determines the surface
     properties of the returned object.

 -- Function: solid:pyramid side height appearance
 -- Function: solid:pyramid side height
     Returns an isosceles pyramid with dimensions SIDE and HEIGHT
     centered on the origin.  APPEARANCE determines the surface
     properties of the returned object.

 -- Function: solid:sphere radius appearance
 -- Function: solid:sphere radius
     Returns a sphere of radius RADIUS centered on the origin.
     APPEARANCE determines the surface properties of the returned
     object.

 -- Function: solid:ellipsoid geometry appearance
 -- Function: solid:ellipsoid geometry
     GEOMETRY must be a number or a list or vector of three numbers.
     If GEOMETRY is a number, the `solid:ellipsoid' returns a sphere of
     diameter GEOMETRY centered on the origin.  Otherwise,
     `solid:ellipsoid' returns an ellipsoid with diameters GEOMETRY
     centered on the origin.  APPEARANCE determines the surface
     properties of the returned object.

 -- Function: solid:polyline coordinates appearance
 -- Function: solid:polyline coordinates
     COORDINATES must be a list or vector of coordinate lists or vectors
     specifying the x, y, and z coordinates of points.
     `solid:polyline' returns lines connecting successive pairs of
     points.  If called with one argument, then the polyline will be
     white.  If APPEARANCE is given, then the polyline will have its
     emissive color only; being black if APPEARANCE does not have an
     emissive color.

     The following code will return a red line between points at `(1 2
     3)' and `(4 5 6)':
          (solid:polyline '((1 2 3) (4 5 6)) (solid:color #f 0 #f 0 '(1 0 0)))

 -- Function: solid:prism xz-array y appearance
 -- Function: solid:prism xz-array y
     XZ-ARRAY must be an N-by-2 array holding a sequence of coordinates
     tracing a non-intersecting clockwise loop in the x-z plane.
     `solid:prism' will close the sequence if the first and last
     coordinates are not the same.

     `solid:prism' returns a capped prism Y long.

 -- Function: solid:basrelief width height depth colorray appearance
 -- Function: solid:basrelief width height depth appearance
 -- Function: solid:basrelief width height depth
     One of WIDTH, HEIGHT, or DEPTH must be a 2-dimensional array; the
     others must be real numbers giving the length of the basrelief in
     those dimensions.  The rest of this description assumes that
     HEIGHT is an array of heights.

     `solid:basrelief' returns a WIDTH by DEPTH basrelief solid with
     heights per array HEIGHT with the buttom surface centered on the
     origin.

     If present, APPEARANCE determines the surface properties of the
     returned object.  If present, COLORRAY must be an array of objects
     of type *Note color: Color Data-Type, 24-bit sRGB integers or
     lists of 3 numbers between 0.0 and 1.0.

     If COLORRAY's dimensions match HEIGHT, then each element of
     COLORRAY paints its corresponding vertex of HEIGHT.  If COLORRAY
     has all dimensions one smaller than HEIGHT, then each element of
     COLORRAY paints the corresponding face of HEIGHT.  Other
     dimensions for COLORRAY are in error.

 -- Function: solid:text fontstyle str len appearance
 -- Function: solid:text fontstyle str len
     FONTSTYLE must be a value returned by `solid:font'.

     STR must be a string or list of strings.

     LEN must be #f, a nonnegative integer, or list of nonnegative
     integers.

     APPEARANCE, if given, determines the surface properties of the
     returned object.

     `solid:text' returns a two-sided, flat text object positioned in
     the Z=0 plane of the local coordinate system

Surface Attributes
------------------

 -- Function: solid:color diffuseColor ambientIntensity specularColor
          shininess emissiveColor transparency
 -- Function: solid:color diffuseColor ambientIntensity specularColor
          shininess emissiveColor
 -- Function: solid:color diffuseColor ambientIntensity specularColor
          shininess
 -- Function: solid:color diffuseColor ambientIntensity specularColor
 -- Function: solid:color diffuseColor ambientIntensity
 -- Function: solid:color diffuseColor
     Returns an "appearance", the optical properties of the objects with
     which it is associated.  AMBIENTINTENSITY, SHININESS, and
     TRANSPARENCY must be numbers between 0 and 1.  DIFFUSECOLOR,
     SPECULARCOLOR, and EMISSIVECOLOR are objects of type *Note color:
     Color Data-Type, 24-bit sRGB integers or lists of 3 numbers
     between 0.0 and 1.0.  If a color argument is omitted or #f, then
     the default color will be used.

 -- Function: solid:texture image color scale rotation center
          translation
 -- Function: solid:texture image color scale rotation center
 -- Function: solid:texture image color scale rotation
 -- Function: solid:texture image color scale
 -- Function: solid:texture image color
 -- Function: solid:texture image
     Returns an "appearance", the optical properties of the objects with
     which it is associated.  IMAGE is a string naming a JPEG or PNG
     image resource.  COLOR is #f, a color, or the string returned by
     `solid:color'.  The rest of the optional arguments specify
     2-dimensional transforms applying to the IMAGE.

     SCALE must be #f, a number, or list or vector of 2 numbers
     specifying the scale to apply to IMAGE.  ROTATION must be #f or
     the number of degrees to rotate IMAGE.  CENTER must be #f or a
     list or vector of 2 numbers specifying the center of IMAGE
     relative to the IMAGE dimensions.  TRANSLATION must be #f or a
     list or vector of 2 numbers specifying the translation to apply to
     IMAGE.

 -- Function: solid:font family style justify size spacing language
          direction
     Returns a fontstyle object suitable for passing as an argument to
     `solid:text'.  Any of the arguments may be #f, in which case its
     default value, which is first in each list of allowed values, is
     used.

     FAMILY is a case-sensitive string naming a font; `SERIF', `SANS',
     and `TYPEWRITER' are supported at the minimum.

     STYLE is a case-sensitive string `PLAIN', `BOLD', `ITALIC', or
     `BOLDITALIC'.

     JUSTIFY is a case-sensitive string `FIRST', `BEGIN', `MIDDLE', or
     `END'; or a list of one or two case-sensitive strings (same
     choices).  The mechanics of JUSTIFY get complicated; it is
     explained by tables 6.2 to 6.7 of
     `http://www.web3d.org/x3d/specifications/vrml/ISO-IEC-14772-IS-VRML97WithAmendment1/part1/nodesRef.html#Table6.2'

     SIZE is the extent, in the non-advancing direction, of the text.
     SIZE defaults to 1.

     SPACING is the ratio of the line (or column) offset to SIZE.
     SPACING defaults to 1.

     LANGUAGE is the RFC-1766 language name.

     DIRECTION is a list of two numbers: `(X Y)'.  If
     `(> (abs X) (abs Y))', then the text will be arrayed horizontally;
     otherwise vertically.  The direction in which characters are
     arrayed is determined by the sign of the major axis: positive X
     being left-to-right; positive Y being top-to-bottom.

Aggregating Objects
-------------------

 -- Function: solid:center-row-of number solid spacing
     Returns a row of NUMBER SOLID objects spaced evenly SPACING apart.

 -- Function: solid:center-array-of number-a number-b solid spacing-a
          spacing-b
     Returns NUMBER-B rows, SPACING-B apart, of NUMBER-A SOLID objects
     SPACING-A apart.

 -- Function: solid:center-pile-of number-a number-b number-c solid
          spacing-a spacing-b spacing-c
     Returns NUMBER-C planes, SPACING-C apart, of NUMBER-B rows,
     SPACING-B apart, of NUMBER-A SOLID objects SPACING-A apart.

 -- Function: solid:arrow center
     CENTER must be a list or vector of three numbers.  Returns an
     upward pointing metallic arrow centered at CENTER.

 -- Function: solid:arrow
     Returns an upward pointing metallic arrow centered at the origin.

Spatial Transformations
-----------------------

 -- Function: solid:translation center solid ...
     CENTER must be a list or vector of three numbers.
     `solid:translation' Returns an aggregate of SOLIDS, ... with their
     origin moved to CENTER.

 -- Function: solid:scale scale solid ...
     SCALE must be a number or a list or vector of three numbers.
     `solid:scale' Returns an aggregate of SOLIDS, ... scaled per SCALE.

 -- Function: solid:rotation axis angle solid ...
     AXIS must be a list or vector of three numbers.  `solid:rotation'
     Returns an aggregate of SOLIDS, ... rotated ANGLE degrees around
     the axis AXIS.


File: slib.info,  Node: Color,  Next: Root Finding,  Prev: Solid Modeling,  Up: Mathematical Packages

5.11 Color
==========

`http://swiss.csail.mit.edu/~jaffer/Color'

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


File: slib.info,  Node: Color Data-Type,  Next: Color Spaces,  Prev: Color,  Up: Color

5.11.1 Color Data-Type
----------------------

`(require 'color)'

 -- Function: color? obj
     Returns #t if OBJ is a color.

 -- Function: color? obj typ
     Returns #t if OBJ is a color of color-space TYP.  The symbol TYP
     must be one of:

        * CIEXYZ

        * RGB709

        * L*a*b*

        * L*u*v*

        * sRGB

        * e-sRGB

        * L*C*h

 -- Function: make-color space arg ...
     Returns a color of type SPACE.

        * For SPACE arguments `CIEXYZ', `RGB709', and `sRGB', the sole
          ARG is a list of three numbers.

        * For SPACE arguments `L*a*b*', `L*u*v*', and `L*C*h', ARG is a
          list of three numbers optionally followed by a whitepoint.

        * For `xRGB', ARG is an integer.

        * For `e-sRGB', the arguments are as for `e-sRGB->color'.

 -- Function: color-space color
     Returns the symbol for the color-space in which COLOR is embedded.

 -- Function: color-precision color
     For colors in digital color-spaces, `color-precision' returns the
     number of bits used for each of the R, G, and B channels of the
     encoding.  Otherwise, `color-precision' returns #f

 -- Function: color-white-point color
     Returns the white-point of COLOR in all color-spaces except CIEXYZ.

 -- Function: convert-color color space white-point
 -- Function: convert-color color space
 -- Function: convert-color color e-sRGB precision
     Converts COLOR into SPACE at optional WHITE-POINT.

5.11.1.1 External Representation
................................

Each color encoding has an external, case-insensitive representation.
To ensure portability, the white-point for all color strings is D65.
(1)

Color Space              External Representation
CIEXYZ                   CIEXYZ:<X>/<Y>/<Z>
RGB709                   RGBi:<R>/<G>/<B>
L*a*b*                   CIELAB:<L>/<a>/<b>
L*u*v*                   CIELuv:<L>/<u>/<v>
L*C*h                    CIELCh:<L>/<C>/<h>

The X, Y, Z, L, A, B, U, V, C, H, R, G, and B fields are (Scheme) real
numbers within the appropriate ranges.

Color Space              External Representation
sRGB                     sRGB:<R>/<G>/<B>
e-sRGB10                 e-sRGB10:<R>/<G>/<B>
e-sRGB12                 e-sRGB12:<R>/<G>/<B>
e-sRGB16                 e-sRGB16:<R>/<G>/<B>

The R, G, and B, fields are non-negative exact decimal integers within
the appropriate ranges.

Several additional syntaxes are supported by `string->color':

Color Space              External Representation
sRGB                     sRGB:<RRGGBB>
sRGB                     #<RRGGBB>
sRGB                     0x<RRGGBB>
sRGB                     #x<RRGGBB>

  Where RRGGBB is a non-negative six-digit hexadecimal number.

 -- Function: color->string color
     Returns a string representation of COLOR.

 -- Function: string->color string
     Returns the color represented by STRING.  If STRING is not a
     syntactically valid notation for a color, then `string->color'
     returns #f.

5.11.1.2 White
..............

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 "white point" in CIEXYZ
coordinates.  

The white point for digital color spaces is set to D65.  For the other
spaces a 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.

 -- Constant: D65
     Is the color of 6500.K (blackbody) illumination.  D65 is close to
     the average color of daylight.

 -- 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.

  ---------- Footnotes ----------

  (1) 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.


File: slib.info,  Node: Color Spaces,  Next: Spectra,  Prev: Color Data-Type,  Up: Color

5.11.2 Color Spaces
-------------------

Measurement-based Color Spaces
..............................

The "tristimulus" color spaces are those whose component values are
proportional measurements of light intensity.  The CIEXYZ(1931) system
provides 3 sets of spectra to dot-product with a spectrum of interest.
The result of those dot-products is coordinates in CIEXYZ space.  All
tristimuls color spaces are related to CIEXYZ by linear transforms,
namely matrix multiplication.  Of the color spaces listed here, CIEXYZ
and RGB709 are tristimulus spaces.

 -- Color Space: CIEXYZ
     The CIEXYZ color space covers the full "gamut".  It is the basis
     for color-space conversions.

     CIEXYZ is a list of three inexact numbers between 0.0 and 1.1.
     '(0. 0. 0.) is black; '(1. 1. 1.) is white.

 -- Function: ciexyz->color xyz
     XYZ must be a list of 3 numbers.  If XYZ is valid CIEXYZ
     coordinates, then `ciexyz->color' returns the color specified by
     XYZ; otherwise returns #f.

 -- Function: color:ciexyz x y z
     Returns the CIEXYZ color composed of X, Y, Z.  If the coordinates
     do not encode a valid CIEXYZ color, then an error is signaled.

 -- Function: color->ciexyz color
     Returns the list of 3 numbers encoding COLOR in CIEXYZ.

 -- Color Space: RGB709
     BT.709-4 (03/00) `Parameter values for the HDTV standards for
     production and international programme exchange' specifies
     parameter values for chromaticity, sampling, signal format, frame
     rates, etc., of high definition television signals.

     An RGB709 color is represented by a list of three inexact numbers
     between 0.0 and 1.0.  '(0. 0. 0.) is black '(1. 1. 1.) is white.

 -- Function: rgb709->color rgb
     RGB must be a list of 3 numbers.  If RGB is valid RGB709
     coordinates, then `rgb709->color' returns the color specified by
     RGB; otherwise returns #f.

 -- Function: color:rgb709 r g b
     Returns the RGB709 color composed of R, G, B.  If the coordinates
     do not encode a valid RGB709 color, then an error is signaled.

 -- Function: color->rgb709 color
     Returns the list of 3 numbers encoding COLOR in RGB709.

Perceptual Uniformity
.....................

Although properly encoding the chromaticity, tristimulus spaces do not
match the logarithmic response of human visual systems to intensity.
Minimum detectable differences between colors correspond to a smaller
range of distances (6:1) in the L*a*b* and L*u*v* spaces than in
tristimulus spaces (80:1).  For this reason, color distances are
computed in L*a*b* (or L*C*h).

 -- Color Space: L*a*b*
     Is a CIE color space which better matches the human visual system's
     perception of color.  It is a list of three numbers:

        * 0 <= L* <= 100 (CIE "Lightness") 

        * -500 <= a* <= 500

        * -200 <= b* <= 200

 -- Function: l*a*b*->color L*a*b* white-point
     L*A*B* must be a list of 3 numbers.  If L*A*B* is valid L*a*b*
     coordinates, then `l*a*b*->color' returns the color specified by
     L*A*B*; otherwise returns #f.

 -- Function: color:l*a*b* L* a* b* white-point
     Returns the L*a*b* color composed of L*, A*, B* with WHITE-POINT.

 -- Function: color:l*a*b* L* a* b*
     Returns the L*a*b* color composed of L*, A*, B*.  If the
     coordinates do not encode a valid L*a*b* color, then an error is
     signaled.

 -- Function: color->l*a*b* color white-point
     Returns the list of 3 numbers encoding COLOR in L*a*b* with
     WHITE-POINT.

 -- Function: color->l*a*b* color
     Returns the list of 3 numbers encoding COLOR in L*a*b*.

 -- Color Space: L*u*v*
     Is another CIE encoding designed to better match the human visual
     system's perception of color.

 -- Function: l*u*v*->color L*u*v* white-point
     L*U*V* must be a list of 3 numbers.  If L*U*V* is valid L*u*v*
     coordinates, then `l*u*v*->color' returns the color specified by
     L*U*V*; otherwise returns #f.

 -- Function: color:l*u*v* L* u* v* white-point
     Returns the L*u*v* color composed of L*, U*, V* with WHITE-POINT.

 -- Function: color:l*u*v* L* u* v*
     Returns the L*u*v* color composed of L*, U*, V*.  If the
     coordinates do not encode a valid L*u*v* color, then an error is
     signaled.

 -- Function: color->l*u*v* color white-point
     Returns the list of 3 numbers encoding COLOR in L*u*v* with
     WHITE-POINT.

 -- Function: color->l*u*v* color
     Returns the list of 3 numbers encoding COLOR in L*u*v*.

Cylindrical Coordinates
.......................

HSL (Hue Saturation Lightness), HSV (Hue Saturation Value), HSI (Hue
Saturation Intensity) and HCI (Hue Chroma Intensity) are cylindrical
color spaces (with angle hue).  But these spaces are all defined in
terms device-dependent RGB spaces.

One might wonder if there is some fundamental reason why intuitive
specification of color must be device-dependent.  But take heart!  A
cylindrical system can be based on L*a*b* and is used for predicting how
close colors seem to observers.

 -- Color Space: L*C*h
     Expresses the *a and b* of L*a*b* in polar coordinates.  It is a
     list of three numbers:

        * 0 <= L* <= 100 (CIE "Lightness") 

        * C* (CIE "Chroma") is the distance from the neutral (gray)
          axis.  

        * 0 <= h <= 360 (CIE "Hue") is the angle.  

     The colors by quadrant of h are:

     0             red, orange, yellow                      90
     90            yellow, yellow-green, green              180
     180           green, cyan (blue-green), blue           270
     270           blue, purple, magenta                    360


 -- Function: l*c*h->color L*C*h white-point
     L*C*H must be a list of 3 numbers.  If L*C*H is valid L*C*h
     coordinates, then `l*c*h->color' returns the color specified by
     L*C*H; otherwise returns #f.

 -- Function: color:l*c*h L* C* h white-point
     Returns the L*C*h color composed of L*, C*, H with WHITE-POINT.

 -- Function: color:l*c*h L* C* h
     Returns the L*C*h color composed of L*, C*, H.  If the coordinates
     do not encode a valid L*C*h color, then an error is signaled.

 -- Function: color->l*c*h color white-point
     Returns the list of 3 numbers encoding COLOR in L*C*h with
     WHITE-POINT.

 -- Function: color->l*c*h color
     Returns the list of 3 numbers encoding COLOR in L*C*h.

Digital Color Spaces
....................

The color spaces discussed so far are impractical for image data because
of numerical precision and computational requirements.  In 1998 the IEC
adopted `A Standard Default Color Space for the Internet - sRGB'
(`http://www.w3.org/Graphics/Color/sRGB').  sRGB was cleverly designed
to employ the 24-bit (256x256x256) color encoding already in widespread
use; and the 2.2 gamma intrinsic to CRT monitors.

Conversion from CIEXYZ to digital (sRGB) color spaces is accomplished by
conversion first to a RGB709 tristimulus space with D65 white-point;
then each coordinate is individually subjected to the same non-linear
mapping.  Inverse operations in the reverse order create the inverse
transform.

 -- Color Space: sRGB
     Is "A Standard Default Color Space for the Internet".  Most display
     monitors will work fairly well with sRGB directly.  Systems using
     ICC profiles (1) should work very well with sRGB.


 -- Function: srgb->color rgb
     RGB must be a list of 3 numbers.  If RGB is valid sRGB coordinates,
     then `srgb->color' returns the color specified by RGB; otherwise
     returns #f.

 -- Function: color:srgb r g b
     Returns the sRGB color composed of R, G, B.  If the coordinates do
     not encode a valid sRGB color, then an error is signaled.

 -- Color Space: xRGB
     Represents the equivalent sRGB color with a single 24-bit integer.
     The most significant 8 bits encode red, the middle 8 bits blue,
     and the least significant 8 bits green.

 -- Function: color->srgb color
     Returns the list of 3 integers encoding COLOR in sRGB.

 -- Function: color->xrgb color
     Returns the 24-bit integer encoding COLOR in sRGB.

 -- Function: xrgb->color k
     Returns the sRGB color composed of the 24-bit integer K.

 -- Color Space: e-sRGB
     Is "Photography - Electronic still picture imaging - Extended sRGB
     color encoding" (PIMA 7667:2001).  It extends the gamut of sRGB;
     and its higher precision numbers provide a larger dynamic range.

     A triplet of integers represent e-sRGB colors.  Three precisions
     are supported:

    e-sRGB10
          0 to 1023

    e-sRGB12
          0 to 4095

    e-sRGB16
          0 to 65535

 -- Function: e-srgb->color precision rgb
     PRECISION must be the integer 10, 12, or 16.  RGB must be a list
     of 3 numbers.  If RGB is valid e-sRGB coordinates, then
     `e-srgb->color' returns the color specified by RGB; otherwise
     returns #f.

 -- Function: color:e-srgb 10 r g b
     Returns the e-sRGB10 color composed of integers R, G, B.

 -- Function: color:e-srgb 12 r g b
     Returns the e-sRGB12 color composed of integers R, G, B.

 -- Function: color:e-srgb 16 r g b
     Returns the e-sRGB16 color composed of integers R, G, B.  If the
     coordinates do not encode a valid e-sRGB color, then an error is
     signaled.

 -- Function: color->e-srgb precision color
     PRECISION must be the integer 10, 12, or 16.  `color->e-srgb'
     returns the list of 3 integers encoding COLOR in sRGB10, sRGB12,
     or sRGB16.

  ---------- Footnotes ----------

  (1) A comprehensive encoding of transforms between CIEXYZ and device
color spaces is the International Color Consortium profile format,
ICC.1:1998-09:

     The intent of this format is to provide a cross-platform device
     profile format.  Such device profiles can be used to translate
     color data created on one device into another device's native
     color space.


File: slib.info,  Node: Spectra,  Next: Color Difference Metrics,  Prev: Color Spaces,  Up: Color

5.11.3 Spectra
--------------

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 *Note Color Spaces::.

  `(require 'color-space)'

A spectrum may be represented as:

   * A procedure of one argument accepting real numbers from 380e-9 to
     780e-9, the wavelength in meters; or

   * A vector of real numbers representing intensity samples evenly
     spaced over some range of wavelengths overlapping the range 380e-9
     to 780e-9.

CIEXYZ values are calculated as dot-product with the X, Y (Luminance),
and Z "Spectral Tristimulus Values".  The files `cie1931.xyz' and
`cie1964.xyz' in the distribution contain these CIE-defined values.  

 -- Feature: cie1964
     Loads the Spectral Tristimulus Values `CIE 1964 Supplementary            |
     Standard Colorimetric Observer', defining CIE:X-BAR, CIE:Y-BAR,          |
     and CIE:Z-BAR.                                                           |

 -- Feature: cie1931
     Loads the Spectral Tristimulus Values `CIE 1931 Supplementary            |
     Standard Colorimetric Observer', defining CIE:X-BAR, CIE:Y-BAR,          |
     and CIE:Z-BAR.                                                           |

 -- Feature: ciexyz
     Requires Spectral Tristimulus Values, defaulting to cie1931,             |
     defining CIE:X-BAR, CIE:Y-BAR, and CIE:Z-BAR.                            |

`(require 'cie1964)' or `(require 'cie1931)' will `load-ciexyz'
specific values used by the following spectrum conversion procedures.
The spectrum conversion procedures `(require 'ciexyz)' to assure that a
set is loaded.

 -- Function: read-cie-illuminant path
     PATH must be a string naming a file consisting of 107 numbers for
     5.nm intervals from 300.nm to 830.nm.  `read-cie-illuminant' reads
     (using Scheme `read') these numbers and returns a length 107
     vector filled with them.

     (define CIE:SI-D65
       (read-CIE-illuminant (in-vicinity (library-vicinity) "ciesid65.dat")))
     (spectrum->XYZ CIE:SI-D65 300e-9 830e-9)
     => (25.108569422374994 26.418013465625001 28.764075683374993)

 -- Function: read-normalized-illuminant path
     PATH must be a string naming a file consisting of 107 numbers for
     5.nm intervals from 300.nm to 830.nm.
     `read-normalized-illuminant' reads (using Scheme `read') these
     numbers and returns a length 107 vector filled with them,
     normalized so that `spectrum->XYZ' of the illuminant returns its
     whitepoint.

  CIE Standard Illuminants A and D65 are included with SLIB:

     (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)
     => (1.098499460820401 999.9999999999998e-3 355.8173930654951e-3)
     (CIEXYZ->sRGB (spectrum->XYZ CIE:SI-A 300e-9 830e-9))
     => (255 234 133)
     (spectrum->XYZ CIE:SI-D65 300e-9 830e-9)
     => (950.4336673552745e-3 1.0000000000000002 1.0888053986649182)
     (CIEXYZ->sRGB (spectrum->XYZ CIE:SI-D65 300e-9 830e-9))
     => (255 255 255)

 -- Function: illuminant-map proc siv
     SIV must be a one-dimensional array or vector of 107 numbers.
     `illuminant-map' returns a vector of length 107 containing the
     result of applying PROC to each element of SIV.

 -- Function: illuminant-map->XYZ proc siv
     `(spectrum->XYZ (illuminant-map PROC SIV) 300e-9 830e-9)'

 -- Function: spectrum->XYZ proc
     PROC must be a function of one argument.  `spectrum->XYZ' computes
     the CIEXYZ(1931) values for the spectrum returned by PROC when
     called with arguments from 380e-9 to 780e-9, the wavelength in
     meters.

 -- Function: spectrum->XYZ spectrum x1 x2
     X1 and X2 must be positive real numbers specifying the wavelengths
     (in meters) corresponding to the zeroth and last elements of
     vector or list SPECTRUM.  `spectrum->XYZ' returns the CIEXYZ(1931)
     values for a light source with spectral values proportional to the
     elements of SPECTRUM at evenly spaced wavelengths between X1 and
     X2.

     Compute the colors of 6500.K and 5000.K blackbody radiation:

          (require 'color-space)
          (define xyz (spectrum->XYZ (blackbody-spectrum 6500)))
          (define y_n (cadr xyz))
          (map (lambda (x) (/ x y_n)) xyz)
              => (0.9687111145512467 1.0 1.1210875945303613)

          (define xyz (spectrum->XYZ (blackbody-spectrum 5000)))
          (map (lambda (x) (/ x y_n)) xyz)
              => (0.2933441826889158 0.2988931825387761 0.25783646831201573)

 -- Function: spectrum->chromaticity proc
 -- Function: spectrum->chromaticity spectrum x1 x2
     Computes the chromaticity for the given spectrum.

 -- Function: wavelength->XYZ w
     W must be a number between 380e-9 to 780e-9.  `wavelength->XYZ'
     returns (unnormalized) XYZ values for a monochromatic light source
     with wavelength W.

 -- Function: wavelength->chromaticity w
     W must be a number between 380e-9 to 780e-9.
     `wavelength->chromaticity' returns the chromaticity for a
     monochromatic light source with wavelength W.

 -- Function: blackbody-spectrum temp
 -- Function: blackbody-spectrum temp span
     Returns a procedure of one argument (wavelength in meters), which
     returns the radiance of a black body at TEMP.

     The optional argument SPAN is the wavelength analog of bandwidth.
     With the default SPAN of 1.nm (1e-9.m), the values returned by the
     procedure correspond to the power of the photons with wavelengths
     W to W+1e-9.

 -- Function: temperature->XYZ x
     The positive number X is a temperature in degrees kelvin.
     `temperature->XYZ' computes the unnormalized CIEXYZ(1931) values
     for the spectrum of a black body at temperature X.

     Compute the chromaticities of 6500.K and 5000.K blackbody
     radiation:

          (require 'color-space)
          (XYZ->chromaticity (temperature->XYZ 6500))
              => (0.3135191660557008 0.3236456786200268)

          (XYZ->chromaticity (temperature->XYZ 5000))
              => (0.34508082841161052 0.3516084965163377)

 -- Function: temperature->chromaticity x
     The positive number X is a temperature in degrees kelvin.
     `temperature->cromaticity' computes the chromaticity for the
     spectrum of a black body at temperature X.

     Compute the chromaticities of 6500.K and 5000.K blackbody
     radiation:

          (require 'color-space)
          (temperature->chromaticity 6500)
              => (0.3135191660557008 0.3236456786200268)

          (temperature->chromaticity 5000)
              => (0.34508082841161052 0.3516084965163377)

 -- Function: XYZ->chromaticity xyz
     Returns a two element list: the x and y components of XYZ
     normalized to 1 (= X + Y + Z).

 -- Function: chromaticity->CIEXYZ x y
     Returns the list of X, and Y, 1 - Y - X.

 -- Function: chromaticity->whitepoint x y
     Returns the CIEXYZ(1931) values having luminosity 1 and
     chromaticity X and Y.

Many color datasets are expressed in "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.

 -- Function: XYZ->xyY xyz
     Returns a three element list: the X and Y components of XYZ
     normalized to 1, and CIE luminance Y.

 -- Function: xyY->XYZ xyY

 -- Function: xyY:normalize-colors colors
     COLORS is a list of xyY triples.  `xyY:normalize-colors' scales
     each chromaticity so it sums to 1 or less; and divides the Y
     values by the maximum Y in the dataset, so all lie between 0 and 1.

 -- Function: xyY:normalize-colors colors n
     If N is positive real, then `xyY:normalize-colors' divides the Y
     values by N times the maximum Y in the dataset.

     If N is an exact non-positive integer, then `xyY:normalize-colors'
     divides the Y values by the maximum of the Ys in the dataset
     excepting the -N largest Y values.

     In all cases, returned Y values are limited to lie from 0 to 1.

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.

The results of measurements being what they are, `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.


File: slib.info,  Node: Color Difference Metrics,  Next: Color Conversions,  Prev: Spectra,  Up: Color

5.11.4 Color Difference Metrics
-------------------------------

`(require 'color-space)'

  The low-level metric functions operate on lists of 3 numbers, lab1,
lab2, lch1, or lch2.

  `(require 'color)'

  The wrapped functions operate on objects of type color, color1 and
color2 in the function entries.

 -- Function: L*a*b*:DE* lab1 lab2
     Returns the Euclidean distance between LAB1 and LAB2.

 -- Function: CIE:DE* color1 color2 white-point
 -- Function: CIE:DE* color1 color2
     Returns the Euclidean distance in L*a*b* space between COLOR1 and
     COLOR2.

 -- Function: L*C*h:DE*94 lch1 lch2 parametric-factors
 -- Function: L*C*h:DE*94 lch1 lch2
 -- Function: CIE:DE*94 color1 color2 parametric-factors
 -- Function: 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:

        * The specimens are homogeneous in colour.

        * The colour difference (CIELAB) is <= 5 units.

        * They are placed in direct edge contact.

        * Each specimen subtends an angle of >4 degrees to the
          assessor, whose colour vision is normal.

        * They are illuminated at 1000 lux, and viewed against a
          background of uniform grey, with L* of 50, under illumination
          simulating D65.

     The PARAMETRIC-FACTORS argument is a list of 3 quantities kL, kC
     and kH.  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.

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.

 -- Function: CMC-DE lch1 lch2 parametric-factors
 -- Function: CMC-DE lch1 lch2 l c
 -- Function: CMC-DE lch1 lch2 l
 -- Function: CMC-DE lch1 lch2
 -- Function: CMC:DE* color1 color2 l c
 -- Function: CMC:DE* color1 color2
     `CMC:DE' is a L*C*h metric.  The PARAMETRIC-FACTORS argument is a
     list of 2 numbers L and C.  L and C parameterize this metric.  1
     and 1 are recommended for perceptibility; the default, 2 and 1,
     for acceptability.


File: slib.info,  Node: Color Conversions,  Next: Color Names,  Prev: Color Difference Metrics,  Up: Color

5.11.5 Color Conversions
------------------------

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.

  `(require 'color-space)'

 -- Constant: CIEXYZ:D65
     Is the color of 6500.K (blackbody) illumination.  D65 is close to
     the average color of daylight.

 -- Constant: CIEXYZ:D50
     Is the color of 5000.K (blackbody) illumination.  D50 is the color
     of indoor lighting by incandescent bulbs.

 -- Constant: CIEXYZ:A
 -- Constant: CIEXYZ:B
 -- Constant: CIEXYZ:C
 -- Constant: CIEXYZ:E
     CIE 1931 illuminants normalized to 1 = y.

 -- Function: color:linear-transform matrix row

 -- Function: CIEXYZ->RGB709 xyz
 -- Function: RGB709->CIEXYZ srgb

 -- Function: CIEXYZ->L*u*v* xyz white-point
 -- Function: CIEXYZ->L*u*v* xyz
 -- Function: L*u*v*->CIEXYZ L*u*v* white-point
 -- Function: L*u*v*->CIEXYZ L*u*v*
     The WHITE-POINT defaults to CIEXYZ:D65.

 -- Function: CIEXYZ->L*a*b* xyz white-point
 -- Function: CIEXYZ->L*a*b* xyz
 -- Function: L*a*b*->CIEXYZ L*a*b* white-point
 -- Function: L*a*b*->CIEXYZ L*a*b*
     The XYZ WHITE-POINT defaults to CIEXYZ:D65.

 -- Function: L*a*b*->L*C*h L*a*b*
 -- Function: L*C*h->L*a*b* L*C*h

 -- Function: CIEXYZ->sRGB xyz
 -- Function: sRGB->CIEXYZ srgb

 -- Function: CIEXYZ->xRGB xyz
 -- Function: xRGB->CIEXYZ srgb

 -- Function: sRGB->xRGB xyz
 -- Function: xRGB->sRGB srgb

 -- Function: CIEXYZ->e-sRGB n xyz
 -- Function: e-sRGB->CIEXYZ n srgb

 -- Function: sRGB->e-sRGB n srgb
 -- Function: e-sRGB->sRGB n srgb
     The integer 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.

Do not convert e-sRGB precision through `e-sRGB->sRGB' then
`sRGB->e-sRGB' - values would be truncated to 8-bits!

 -- Function: e-sRGB->e-sRGB n1 srgb n2
     The integers N1 and N2 must be 10, 12, or 16.  `e-sRGB->e-sRGB'
     converts SRGB to e-sRGB of precision N2.


File: slib.info,  Node: Color Names,  Next: Daylight,  Prev: Color Conversions,  Up: Color

5.11.6 Color Names
------------------

`(require 'color-names)' 

Rather than ballast the color dictionaries with numbered grays,
`file->color-dictionary' discards them.  They are provided through the
`grey' procedure:

 -- Function: grey k
     Returns `(inexact->exact (round (* k 2.55)))', the X11 color
     grey<k>.

A color dictionary is a database table relating "canonical" color-names
to color-strings (*note External Representation: Color Data-Type.).

The column names in a color dictionary are unimportant; the first field
is the key, and the second is the color-string.

 -- Function: color-name:canonicalize name
     Returns a downcased copy of the string or symbol NAME with `_',
     `-', and whitespace removed.

 -- Function: color-name->color name table1 table2 ...
     TABLE1, TABLE2, ... must be color-dictionary tables.
     `color-name->color' searches for the canonical form of NAME in
     TABLE1, TABLE2, ... in order; returning the color-string of the
     first matching record; #f otherwise.

 -- Function: color-dictionaries->lookup table1 table2 ...
     TABLE1, TABLE2, ... must be color-dictionary tables.
     `color-dictionaries->lookup' returns a procedure which searches
     for the canonical form of its string argument in TABLE1, TABLE2,
     ...; returning the color-string of the first matching record; and
     #f otherwise.

 -- Function: color-dictionary name rdb base-table-type
     RDB must be a string naming a relational database file; and the
     symbol NAME a table therein.  The database will be opened as
     BASE-TABLE-TYPE.  `color-dictionary' returns the read-only table
     NAME in database NAME if it exists; #f otherwise.

 -- Function: color-dictionary name rdb
     RDB must be an open relational database or a string naming a
     relational database file; and the symbol NAME a table therein.
     `color-dictionary' returns the read-only table NAME in database
     NAME if it exists; #f otherwise.

 -- Function: load-color-dictionary name rdb base-table-type
 -- Function: load-color-dictionary name rdb
     RDB must be a string naming a relational database file; and the
     symbol NAME a table therein.  If the symbol BASE-TABLE-TYPE is
     provided, the database will be opened as BASE-TABLE-TYPE.
     `load-color-dictionary' creates a top-level definition of the
     symbol NAME to a lookup procedure for the color dictionary NAME in
     RDB.

     The value returned by `load-color-dictionary' is unspecified.

Dictionary Creation
...................

`(require 'color-database)' 

 -- Function: file->color-dictionary file table-name rdb base-table-type
 -- Function: file->color-dictionary file table-name rdb
     RDB must be an open relational database or a string naming a
     relational database file, TABLE-NAME a symbol, and the string FILE
     must name an existing file with colornames and their corresponding
     xRGB (6-digit hex) values.  `file->color-dictionary' creates a
     table TABLE-NAME in RDB and enters the associations found in FILE
     into it.

 -- Function: url->color-dictionary url table-name rdb base-table-type
 -- Function: url->color-dictionary url table-name rdb
     RDB must be an open relational database or a string naming a
     relational database file and TABLE-NAME a symbol.
     `url->color-dictionary' retrieves the resource named by the string
     URL using the "wget" program; then calls `file->color-dictionary'
     to enter its associations in TABLE-NAME in URL.

This section has detailed the procedures for creating and loading color
dictionaries.  So where are the dictionaries to load?

  `http://swiss.csail.mit.edu/~jaffer/Color/Dictionaries.html'

Describes and evaluates several color-name dictionaries on the web.
The following procedure creates a database containing two of these
dictionaries.

 -- Function: make-slib-color-name-db
     Creates an alist-table relational database in library-vicinity
     containing the "Resene" and "saturate" color-name dictionaries.

     If the files `resenecolours.txt', `nbs-iscc.txt', and
     `saturate.txt' exist in the library-vicinity, then they used as
     the source of color-name data.  Otherwise,
     `make-slib-color-name-db' calls url->color-dictionary with the
     URLs of appropriate source files.

The Short List
..............

`(require 'saturate)' 

 -- Function: saturate name
     Looks for NAME among the 19 saturated colors from `Approximate
     Colors on CIE Chromaticity Diagram':

     reddish orange    orange            yellowish orange  yellow
     greenish yellow   yellow green      yellowish green   green
     bluish green      blue green        greenish blue     blue
     purplish blue     bluish purple     purple            reddish purple
     red purple        purplish red      red               

     (`http://swiss.csail.mit.edu/~jaffer/Color/saturate.pdf').  If
     NAME is found, the corresponding color is returned.  Otherwise #f
     is returned.  Use saturate only for light source colors.

Resene Paints Limited, New Zealand's largest privately-owned and
operated paint manufacturing company, has generously made their `Resene
RGB Values List' available.

  `(require 'resene)' 

 -- Function: resene name
     Looks for NAME among the 1300 entries in the Resene color-name
     dictionary (`http://swiss.csail.mit.edu/~jaffer/Color/resene.pdf').
     If NAME is found, the corresponding color is returned.  Otherwise
     #f is returned.  The `Resene RGB Values List' is an excellent
     source for surface colors.

If you include the "Resene RGB Values List" in binary form in a
program, then you must include its license with your program:

     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.

       1. Any text copy made of this dictionary must include this
          copyright notice in full.

       2. Any redistribution in binary form must reproduce this
          copyright notice in the documentation or other materials
          provided with the distribution.

       3. 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.

       4. 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.

       5. These RGB colour formulations may not be used to the
          detriment of Resene Paints Ltd.


File: slib.info,  Node: Daylight,  Prev: Color Names,  Up: Color

5.11.7 Daylight
---------------

`(require 'daylight)' 

This package calculates the colors of sky as detailed in:
`http://www.cs.utah.edu/vissim/papers/sunsky/sunsky.pdf'
`A Practical Analytic Model for Daylight'
A. J. Preetham, Peter Shirley, Brian Smits

 -- Function: solar-hour julian-day hour
     Returns the solar-time in hours given the integer JULIAN-DAY in
     the range 1 to 366, and the local time in hours.

     To be meticulous, subtract 4 minutes for each degree of longitude
     west of the standard meridian of your time zone.

 -- Function: solar-declination julian-day

 -- Function: solar-polar declination latitude solar-hour
     Returns a list of THETA_S, the solar angle from the zenith, and
     PHI_S, the solar azimuth.  0 <= THETA_S measured in degrees.
     PHI_S is measured in degrees from due south; west of south being
     positive.

In the following procedures, the number 0 <= THETA_S <= 90 is the solar
angle from the zenith in degrees.

Turbidity is a measure of the fraction of scattering due to haze as
opposed to molecules.  This is a convenient quantity because it can be
estimated based on visibility of distant objects.  This model fails for
turbidity values less than 1.3.

         _______________________________________________________________
     512|-:                                                             |
        | * pure-air                                                    |
     256|-:**                                                           |
        | : ** exceptionally-clear                                      |
     128|-:   *                                                         |
        | :    **                                                       |
      64|-:      *                                                      |
        | :       ** very-clear                                         |
      32|-:         **                                                  |
        | :           **                                                |
      16|-:             *** clear                                       |
        | :               ****                                          |
       8|-:                  ****                                       |
        | :                     **** light-haze                         |
       4|-:                         ****                                |
        | :                             ******                          |
       2|-:                                  ******** haze         thin-|
        | :                                          ***********    fog |
       1|-:----------------------------------------------------*******--|
        |_:____.____:____.____:____.____:____.____:____.____:____.____:_|
          1         2         4         8        16        32        64
                   Meterorological range (km) versus Turbidity

 -- Function: sunlight-spectrum turbidity theta_s
     Returns a vector of 41 values, the spectrum of sunlight from
     380.nm to 790.nm for a given TURBIDITY and THETA_S.

 -- Function: sunlight-chromaticity turbidity theta_s
     Given TURBIDITY and THETA_S, `sunlight-chromaticity' returns the
     CIEXYZ triple for color of sunlight scaled to be just inside the
     RGB709 gamut.

 -- Function: zenith-xyy turbidity theta_s
     Returns the xyY (chromaticity and luminance) at the zenith.  The
     Luminance has units kcd/m^2.

 -- Function: overcast-sky-color-xyy turbidity theta_s
     TURBIDITY is a positive real number expressing the amount of light
     scattering.  The real number THETA_S is the solar angle from the
     zenith in degrees.

     `overcast-sky-color-xyy' returns a function of one angle THETA,
     the angle from the zenith of the viewing direction (in degrees);
     and returning the xyY value for light coming from that elevation
     of the sky.

 -- Function: clear-sky-color-xyy turbidity theta_s phi_s
 -- Function: sky-color-xyy turbidity theta_s phi_s
     TURBIDITY is a positive real number expressing the amount of light
     scattering.  The real number THETA_S is the solar angle from the
     zenith in degrees.  The real number PHI_S is the solar angle from
     south.

     `clear-sky-color-xyy' returns a function of two angles, THETA and
     PHI which specify the angles from the zenith and south meridian of
     the viewing direction (in degrees); returning the xyY value for
     light coming from that direction of the sky.

     `sky-color-xyY' calls `overcast-sky-color-xyY' for TURBIDITY <=
     20; otherwise the `clear-sky-color-xyy' function.


File: slib.info,  Node: Root Finding,  Next: Minimizing,  Prev: Color,  Up: Mathematical Packages

5.12 Root Finding
=================

`(require 'root)' 

 -- Function: newton:find-integer-root f df/dx x0
     Given integer valued procedure F, its derivative (with respect to
     its argument) DF/DX, and initial integer value X0 for which
     DF/DX(X0) is non-zero, returns an integer X for which F(X) is
     closer to zero than either of the integers adjacent to X; or
     returns `#f' if such an integer can't be found.

     To find the closest integer to a given integer's square root:

          (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) => 4

 -- Function: newton:find-root f df/dx x0 prec
     Given real valued procedures F, DF/DX of one (real) argument,
     initial real value X0 for which DF/DX(X0) is non-zero, and
     positive real number PREC, returns a real X for which `abs'(F(X))
     is less than PREC; or returns `#f' if such a real can't be found.

     If PREC is instead a negative integer, `newton:find-root' returns
     the result of -PREC iterations.

H. J. Orchard, `The Laguerre Method for Finding the Zeros of
Polynomials', IEEE Transactions on Circuits and Systems, Vol. 36, No.
11, November 1989, pp 1377-1381.

     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.

 -- Function: laguerre:find-root f df/dz ddf/dz^2 z0 prec
     Given complex valued procedure F of one (complex) argument, its
     derivative (with respect to its argument) DF/DX, its second
     derivative DDF/DZ^2, initial complex value Z0, and positive real
     number PREC, returns a complex number Z for which
     `magnitude'(F(Z)) is less than PREC; or returns `#f' if such a
     number can't be found.

     If PREC is instead a negative integer, `laguerre:find-root'
     returns the result of -PREC iterations.

 -- Function: laguerre:find-polynomial-root deg f df/dz ddf/dz^2 z0 prec
     Given polynomial procedure F of integer degree DEG of one
     argument, its derivative (with respect to its argument) DF/DX, its
     second derivative DDF/DZ^2, initial complex value Z0, and positive
     real number PREC, returns a complex number Z for which
     `magnitude'(F(Z)) is less than PREC; or returns `#f' if such a
     number can't be found.

     If PREC is instead a negative integer,
     `laguerre:find-polynomial-root' returns the result of -PREC
     iterations.

 -- Function: secant:find-root f x0 x1 prec
 -- Function: secant:find-bracketed-root f x0 x1 prec
     Given a real valued procedure F and two real valued starting
     points X0 and X1, returns a real X for which `(abs (f x))' is less
     than PREC; or returns `#f' if such a real can't be found.

     If X0 and X1 are chosen such that they bracket a root, that is
          (or (< (f x0) 0 (f x1))
              (< (f x1) 0 (f x0)))
     then the root returned will be between X0 and X1, and F will not
     be passed an argument outside of that interval.

     `secant:find-bracketed-root' will return `#f' unless X0 and X1
     bracket a root.

     The secant method is used until a bracketing interval is found, at
     which point a modified regula falsi method is used.

     If PREC is instead a negative integer, `secant:find-root' returns
     the result of -PREC iterations.

     If PREC is a procedure it should accept 5 arguments: X0 F0 X1 F1
     and COUNT, where F0 will be `(f x0)', F1 `(f x1)', and COUNT the
     number of iterations performed so far.  PREC should return
     non-false if the iteration should be stopped.


File: slib.info,  Node: Minimizing,  Next: The Limit,  Prev: Root Finding,  Up: Mathematical Packages

5.13 Minimizing
===============

`(require 'minimize)' 

The Golden Section Search (1) algorithm finds minima of functions which
are expensive to compute or for which derivatives are not available.
Although optimum for the general case, convergence is slow, requiring
nearly 100 iterations for the example (x^3-2x-5).

If the derivative is available, Newton-Raphson is probably a better
choice.  If the function is inexpensive to compute, consider
approximating the derivative.

 -- Function: golden-section-search f x0 x1 prec
     X_0 are X_1 real numbers.  The (single argument) procedure F is
     unimodal over the open interval (X_0, X_1).  That is, there is
     exactly one point in the interval for which the derivative of F is
     zero.

     `golden-section-search' returns a pair (X . F(X)) where F(X) is
     the minimum.  The PREC parameter is the stop criterion.  If PREC
     is a positive number, then the iteration continues until X is
     within PREC from the true value.  If PREC is a negative integer,
     then the procedure will iterate -PREC times or until convergence.
     If PREC is a procedure of seven arguments, X0, X1, A, B, FA, FB,
     and COUNT, then the iterations will stop when the procedure
     returns `#t'.

     Analytically, the minimum of x^3-2x-5 is 0.816497.
          (define func (lambda (x) (+ (* x (+ (* x x) -2)) -5)))
          (golden-section-search func 0 1 (/ 10000))
                ==> (816.4883855245578e-3 . -6.0886621077391165)
          (golden-section-search func 0 1 -5)
                ==> (819.6601125010515e-3 . -6.088637561916407)
          (golden-section-search func 0 1
                                 (lambda (a b c d e f g ) (= g 500)))
                ==> (816.4965933140557e-3 . -6.088662107903635)

  ---------- Footnotes ----------

  (1) David Kahaner, Cleve Moler, and Stephen Nash `Numerical Methods
and Software' Prentice-Hall, 1989, ISBN 0-13-627258-4


File: slib.info,  Node: The Limit,  Next: Commutative Rings,  Prev: Minimizing,  Up: Mathematical Packages

5.14 The Limit
==============

 -- library procedure: limit proc x1 x2 k
 -- library procedure: limit proc x1 x2
     PROC must be a procedure taking a single inexact real argument.  K
     is the number of points on which PROC will be called; it defaults
     to 8.

     If X1 is finite, then PROC must be continuous on the half-open
     interval:

     ( X1 .. X1+X2 ]

     And X2 should be chosen small enough so that PROC is expected to
     be monotonic or constant on arguments between X1 and X1 + X2.

     `Limit' computes the limit of PROC as its argument approaches X1
     from X1 + X2.  `Limit' returns a real number or real infinity or
     `#f'.

     If X1 is not finite, then X2 must be a finite nonzero real with
     the same sign as X1; in which case `limit' returns:

     `(limit (lambda (x) (proc (/ x))) 0.0 (/ X2) K)'

     `Limit' examines the magnitudes of the differences between
     successive values returned by PROC called with a succession of
     numbers from X1+X2/K to X1.

     If the magnitudes of differences are monotonically decreasing, then
     then the limit is extrapolated from the degree n polynomial passing
     through the samples returned by PROC.

     If the magnitudes of differences are increasing as fast or faster
     than a hyperbola matching at X1+X2, then a real infinity with sign
     the same as the differences is returned.

     If the magnitudes of differences are increasing more slowly than
     the hyperbola matching at X1+X2, then the limit is extrapolated
     from the quadratic passing through the three samples closest to X1.

     If the magnitudes of differences are not monotonic or are not
     completely within one of the above categories, then #f is returned.

     ;; constant
     (limit (lambda (x) (/ x x)) 0 1.0e-9)           ==> 1.0
     (limit (lambda (x) (expt 0 x)) 0 1.0e-9)        ==> 0.0
     (limit (lambda (x) (expt 0 x)) 0 -1.0e-9)       ==> +inf.0
     ;; linear
     (limit + 0 976.5625e-6)                         ==> 0.0
     (limit - 0 976.5625e-6)                         ==> 0.0
     ;; vertical point of inflection
     (limit sqrt 0 1.0e-18)                          ==> 0.0
     (limit (lambda (x) (* x (log x))) 0 1.0e-9)     ==> -102.70578127633066e-12
     (limit (lambda (x) (/ x (log x))) 0 1.0e-9)     ==> 96.12123142321669e-15
     ;; limits tending to infinity
     (limit + +inf.0 1.0e9)                          ==> +inf.0
     (limit + -inf.0 -1.0e9)                         ==> -inf.0
     (limit / 0 1.0e-9)                              ==> +inf.0
     (limit / 0 -1.0e-9)                             ==> -inf.0
     (limit (lambda (x) (/ (log x) x)) 0 1.0e-9)     ==> -inf.0
     (limit (lambda (x) (/ (magnitude (log x)) x)) 0 -1.0e-9)
                                                     ==> -inf.0
     ;; limit doesn't exist
     (limit sin +inf.0 1.0e9)                        ==> #f
     (limit (lambda (x) (sin (/ x))) 0 1.0e-9)       ==> #f
     (limit (lambda (x) (sin (/ x))) 0 -1.0e-9)      ==> #f
     (limit (lambda (x) (/ (log x) x)) 0 -1.0e-9)    ==> #f
     ;; conditionally convergent - return #f
     (limit (lambda (x) (/ (sin x) x)) +inf.0 1.0e222)
                                                     ==> #f
     ;; asymptotes
     (limit / -inf.0 -1.0e222)                       ==> 0.0
     (limit / +inf.0 1.0e222)                        ==> 0.0
     (limit (lambda (x) (expt x x)) 0 1.0e-18)       ==> 1.0
     (limit (lambda (x) (sin (/ x))) +inf.0 1.0e222) ==> 0.0
     (limit (lambda (x) (/ (+ (exp (/ x)) 1))) 0 1.0e-9)
                                                     ==> 0.0
     (limit (lambda (x) (/ (+ (exp (/ x)) 1))) 0 -1.0e-9)
                                                     ==> 1.0
     (limit (lambda (x) (real-part (expt (tan x) (cos x)))) (/ pi 2) 1.0e-9)
                                                     ==> 1.0
     ;; This example from the 1979 Macsyma manual grows so rapidly
     ;;  that x2 must be less than 41.  It correctly returns e^2.
     (limit (lambda (x) (expt (+ x (exp x) (exp (* 2 x))) (/ x))) +inf.0 40)
                                                     ==> 7.3890560989306504
     ;; LIMIT can calculate the proper answer when evaluation
     ;; of the function at the limit point does not:
     (tan (atan +inf.0))                             ==> 16.331778728383844e15
     (limit tan (atan +inf.0) -1.0e-15)              ==> +inf.0
     (tan (atan +inf.0))                             ==> 16.331778728383844e15
     (limit tan (atan +inf.0) 1.0e-15)               ==> -inf.0
     ((lambda (x) (expt (exp (/ -1 x)) x)) 0)        ==> 1.0
     (limit (lambda (x) (expt (exp (/ -1 x)) x)) 0 1.0e-9)
                                                     ==> 0.0


File: slib.info,  Node: Commutative Rings,  Next: Matrix Algebra,  Prev: The Limit,  Up: Mathematical Packages

5.15 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.

  `(require 'commutative-ring)' 

  The "commutative-ring" package makes the procedures `+', `-', `*',
`/', and `^' "careful" in the sense 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).  

     (define a 'a)
     ...
     (define z 'z)

  Or just `(require 'self-set)'.  Now try some sample expressions: 

     (+ (+ a b) (- a b)) => (* a 2)
     (* (+ a b) (+ a b)) => (^ (+ a b) 2)
     (* (+ a b) (- a b)) => (* (+ a b) (- a b))
     (* (- a b) (- a b)) => (^ (- a b) 2)
     (* (- a b) (+ a b)) => (* (+ a b) (- a b))
     (/ (+ a b) (+ c d)) => (/ (+ a b) (+ c d))
     (^ (+ a b) 3) => (^ (+ a b) 3)
     (^ (+ a 2) 3) => (^ (+ 2 a) 3)

  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:
     (set! *ruleset* (combined-rulesets distribute* distribute/))

     (* (+ a b) (+ a b)) => (+ (* 2 a b) (^ a 2) (^ b 2))
     (* (+ a b) (- a b)) => (- (^ a 2) (^ b 2))
     (* (- a b) (- a b)) => (- (+ (^ a 2) (^ b 2)) (* 2 a b))
     (* (- a b) (+ a b)) => (- (^ a 2) (^ b 2))
     (/ (+ a b) (+ c d)) => (+ (/ a (+ c d)) (/ b (+ c d)))
     (/ (+ a b) (- c d)) => (+ (/ a (- c d)) (/ b (- c d)))
     (/ (- a b) (- c d)) => (- (/ a (- c d)) (/ b (- c d)))
     (/ (- a b) (+ c d)) => (- (/ a (+ c d)) (/ b (+ c d)))
     (^ (+ a b) 3) => (+ (* 3 a (^ b 2)) (* 3 b (^ a 2)) (^ a 3) (^ b 3))
     (^ (+ a 2) 3) => (+ 8 (* a 12) (* (^ a 2) 6) (^ a 3))

  Use of this package is not restricted to simple arithmetic
expressions:

     (require 'determinant)

     (determinant '((a b c) (d e f) (g h i))) =>
     (- (+ (* a e i) (* b f g) (* c d h)) (* a f h) (* b d i) (* c e g))

  Currently, only `+', `-', `*', `/', and `^' support non-numeric
elements.  Expressions with `-' are converted to equivalent expressions
without `-', so behavior for `-' is not defined separately.  `/'
expressions are handled similarly.

  This list might be extended to include `quotient', `modulo',
`remainder', `lcm', and `gcd'; but these work only for the more
restrictive Euclidean (Unique Factorization) Domain.  

5.16 Rules and Rulesets
=======================

The "commutative-ring" package allows control of ring properties
through the use of "rulesets".

 -- Variable: *ruleset*
     Contains the set of rules currently in effect.  Rules defined by
     `cring:define-rule' are stored within the value of *ruleset* at the
     time `cring:define-rule' is called.  If *RULESET* is `#f', then no
     rules apply.

 -- Function: make-ruleset rule1 ...
 -- Function: make-ruleset name rule1 ...
     Returns a new ruleset containing the rules formed by applying
     `cring:define-rule' to each 4-element list argument RULE.  If the
     first argument to `make-ruleset' is a symbol, then the database
     table created for the new ruleset will be named NAME.  Calling
     `make-ruleset' with no rule arguments creates an empty ruleset.

 -- Function: combined-rulesets ruleset1 ...
 -- Function: combined-rulesets name ruleset1 ...
     Returns a new ruleset containing the rules contained in each
     ruleset argument RULESET.  If the first argument to
     `combined-ruleset' is a symbol, then the database table created for
     the new ruleset will be named NAME.  Calling `combined-ruleset'
     with no ruleset arguments creates an empty ruleset.

  Two rulesets are defined by this package.

 -- Constant: distribute*
     Contains the ruleset to distribute multiplication over addition and
     subtraction.

 -- Constant: distribute/
     Contains the ruleset to distribute division over addition and
     subtraction.

     Take care when using both DISTRIBUTE* and DISTRIBUTE/
     simultaneously.  It is possible to put `/' into an infinite loop.

  You can specify how sum and product expressions containing non-numeric
elements simplify by specifying the rules for `+' or `*' for cases
where expressions involving objects reduce to numbers or to expressions
involving different non-numeric elements.

 -- Function: cring:define-rule op sub-op1 sub-op2 reduction
     Defines a rule for the case when the operation represented by
     symbol OP is applied to lists whose `car's are SUB-OP1 and
     SUB-OP2, respectively.  The argument REDUCTION is a procedure
     accepting 2 arguments which will be lists whose `car's are SUB-OP1
     and SUB-OP2.

 -- Function: cring:define-rule op sub-op1 'identity reduction
     Defines a rule for the case when the operation represented by
     symbol OP is applied to a list whose `car' is SUB-OP1, and some
     other argument.  REDUCTION will be called with the list whose
     `car' is SUB-OP1 and some other argument.

     If REDUCTION returns `#f', the reduction has failed and other
     reductions will be tried.  If REDUCTION returns a non-false value,
     that value will replace the two arguments in arithmetic (`+', `-',
     and `*') calculations involving non-numeric elements.

     The operations `+' and `*' are assumed commutative; hence both
     orders of arguments to REDUCTION will be tried if necessary.

     The following rule is the definition for distributing `*' over `+'.

          (cring:define-rule
           '* '+ 'identity
           (lambda (exp1 exp2)
             (apply + (map (lambda (trm) (* trm exp2)) (cdr exp1))))))

5.17 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.

     (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))))

  Define a procedure to multiply 2 non-numeric elements of the ring.
Other multiplicatons are handled automatically.  Objects for which rules
have _not_ been defined are not changed.

     (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))))

  Test the procedures to see if they work.

     ;;; 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)) => (m a b)

  Then register the rule for multiplying type N objects by type N
objects.

     (cring:define-rule '* 'N 'N N*N))

  Now we are ready to compute!

     (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))
     -|
     (- (+ (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)))


File: slib.info,  Node: Matrix Algebra,  Prev: Commutative Rings,  Up: Mathematical Packages

5.18 Matrix Algebra
===================

`(require 'determinant)' 

A Matrix can be either a list of lists (rows) or an array.  Unlike
linear-algebra texts, this package uses 0-based coordinates.

 -- Function: matrix->lists matrix
     Returns the list-of-lists form of MATRIX.

 -- Function: matrix->array matrix
     Returns the array form of MATRIX.                                        |

 -- Function: determinant matrix
     MATRIX must be a square matrix.  `determinant' returns the
     determinant of MATRIX.

          (require 'determinant)
          (determinant '((1 2) (3 4))) => -2
          (determinant '((1 2 3) (4 5 6) (7 8 9))) => 0

 -- Function: transpose matrix
     Returns a copy of MATRIX flipped over the diagonal containing the
     1,1 element.

 -- Function: matrix:sum m1 m2
     Returns the element-wise sum of matricies M1 and M2.

 -- Function: matrix:difference m1 m2
     Returns the element-wise difference of matricies M1 and M2.

 -- Function: matrix:product m1 m2
     Returns the product of matrices M1 and M2.

 -- Function: matrix:product m1 z
     Returns matrix M1 times scalar Z.

 -- Function: matrix:product z m1
     Returns matrix M1 times scalar Z.

 -- Function: matrix:inverse matrix
     MATRIX must be a square matrix.  If MATRIX is singular, then             |
     `matrix:inverse' returns #f; otherwise `matrix:inverse' returns the
     `matrix:product' inverse of MATRIX.


File: slib.info,  Node: Database Packages,  Next: Other Packages,  Prev: Mathematical Packages,  Up: Top

6 Database Packages
*******************

* Menu:

* Relational Database::         'relational-database
* Relational Infrastructure::
* Weight-Balanced Trees::       'wt-tree


File: slib.info,  Node: Relational Database,  Next: Relational Infrastructure,  Prev: Database Packages,  Up: Database Packages

6.1 Relational Database
=======================

`(require 'relational-database)' 

  This package implements a database system inspired by the Relational
Model (`E. F. Codd, A Relational Model of Data for Large Shared Data
Banks').  An SLIB relational database implementation can be created
from any *Note Base Table:: implementation.

  Why relational database?  For motivations and design issues see
`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


File: slib.info,  Node: Using Databases,  Next: Table Operations,  Prev: Relational Database,  Up: Relational Database

6.1.1 Using Databases
---------------------

`(require 'databases)' 

This enhancement wraps a utility layer on `relational-database' which
provides:

   * Identification of open databases by filename.

   * Automatic sharing of open (immutable) databases.

   * Automatic loading of base-table package when creating a database.

   * Detection and automatic loading of the appropriate base-table
     package when opening a database.

   * Table and data definition from Scheme lists.

Database Sharing
................

"Auto-sharing" refers to a call to the procedure `open-database'
returning an already open database (procedure), rather than opening the
database file a second time.

     _Note:_ Databases returned by `open-database' do not include
     wrappers applied by packages like *Note Embedded Commands::.  But
     wrapped databases do work as arguments to these functions.

When a database is created, it is mutable by the creator and not
auto-sharable.  A database opened mutably is also not auto-sharable.
But any number of readers can (open) share a non-mutable database file.

This next set of procedures mirror the whole-database methods in *Note
Database Operations::.  Except for `create-database', each procedure
will accept either a filename or database procedure for its first
argument.

 -- Function: create-database filename base-table-type
     FILENAME should be a string naming a file; or `#f'.
     BASE-TABLE-TYPE must be a symbol naming a feature which can be
     passed to `require'.  `create-database' returns a new, open
     relational database (with base-table type BASE-TABLE-TYPE)
     associated with FILENAME, or a new ephemeral database if FILENAME
     is `#f'.

     `create-database' is the only run-time use of require in SLIB
     which crosses module boundaries.  When BASE-TABLE-TYPE is
     `require'd by `create-database'; it adds an association of
     BASE-TABLE-TYPE with its "relational-system" procedure to
     MDBM:*DATABASES*.

     alist-table is the default base-table type:

          (require 'databases)
          (define my-rdb (create-database "my.db" 'alist-table))

Only `alist-table' and base-table modules which have been `require'd
will dispatch correctly from the `open-database' procedures.
Therefore, either pass two arguments to `open-database', or require the
base-table of your database file uses before calling `open-database'
with one argument.

 -- Procedure: open-database! rdb base-table-type
     Returns _mutable_ open relational database or #f.

 -- Function: open-database rdb base-table-type
     Returns an open relational database associated with RDB.  The
     database will be opened with base-table type BASE-TABLE-TYPE).

 -- Function: open-database rdb
     Returns an open relational database associated with RDB.
     `open-database' will attempt to deduce the correct base-table-type.

 -- Function: write-database rdb filename
     Writes the mutable relational-database RDB to FILENAME.

 -- Function: sync-database rdb
     Writes the mutable relational-database RDB to the filename it was
     opened with.

 -- Function: solidify-database rdb
     Syncs RDB and makes it immutable.

 -- Function: close-database rdb
     RDB will only be closed when the count of `open-database' -
     `close-database' calls for RDB (and its filename) is 0.
     `close-database' returns #t if successful; and #f otherwise.

 -- Function: mdbm:report
     Prints a table of open database files.  The columns are the
     base-table type, number of opens, `!' for mutable, the filename,
     and the lock certificate (if locked).

     (mdbm:report)
     -|
       alist-table 003   /usr/local/lib/slib/clrnamdb.scm
       alist-table 001 ! sdram.db jaffer@aubrey.jaffer.3166:1038628199

Opening Tables
..............

 -- Function: open-table rdb table-name
     RDB must be a relational database and TABLE-NAME a symbol.

     `open-table' returns a "methods" procedure for an existing
     relational table in RDB if it exists and can be opened for
     reading, otherwise returns `#f'.

 -- Procedure: open-table! rdb table-name
     RDB must be a relational database and TABLE-NAME a symbol.

     `open-table!' returns a "methods" procedure for an existing
     relational table in RDB if it exists and can be opened in mutable
     mode, otherwise returns `#f'.

Defining Tables
...............

 -- Function: define-domains rdb row5 ...
     Adds the domain rows ROW5 ... to the `*domains-data*' table in
     RDB.  The format of the row is given in *Note Catalog
     Representation::.

          (define-domains rdb '(permittivity #f complex? c64 #f))

 -- Function: add-domain rdb row5
     Use `define-domains' instead.

 -- Function: define-tables rdb spec-0 ...
     Adds tables as specified in SPEC-0 ... to the open
     relational-database RDB.  Each SPEC has the form:

          (<name> <descriptor-name> <descriptor-name> <rows>)
     or
          (<name> <primary-key-fields> <other-fields> <rows>)

     where <name> is the table name, <descriptor-name> is the symbol
     name of a descriptor table, <primary-key-fields> and
     <other-fields> describe the primary keys and other fields
     respectively, and <rows> is a list of data rows to be added to the
     table.

     <primary-key-fields> and <other-fields> are lists of field
     descriptors of the form:

          (<column-name> <domain>)
     or
          (<column-name> <domain> <column-integrity-rule>)

     where <column-name> is the column name, <domain> is the domain of
     the column, and <column-integrity-rule> is an expression whose
     value is a procedure of one argument (which returns `#f' to signal
     an error).

     If <domain> is not a defined domain name and it matches the name of
     this table or an already defined (in one of SPEC-0 ...) single key
     field table, a foreign-key domain will be created for it.

Listing Tables
..............

 -- Function: list-table-definition rdb table-name
     If symbol TABLE-NAME exists in the open relational-database RDB,
     then returns a list of the table-name, its primary key names and
     domains, its other key names and domains, and the table's records
     (as lists).  Otherwise, returns #f.

     The list returned by `list-table-definition', when passed as an
     argument to `define-tables', will recreate the table.


File: slib.info,  Node: Table Operations,  Next: Database Interpolation,  Prev: Using Databases,  Up: Relational Database

6.1.2 Table Operations
----------------------

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:

     ((plat 'get 'processor) 'djgpp) => i386

Some operations described below require primary key arguments.  Primary
keys arguments are denoted KEY1 KEY2 ....  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.

 -- Operation on relational-table: get column-name
     Returns a procedure of arguments KEY1 KEY2 ... which returns the
     value for the COLUMN-NAME column of the row associated with
     primary keys KEY1, KEY2 ... if that row exists in the table, or
     `#f' otherwise.

          ((plat 'get 'processor) 'djgpp) => i386
          ((plat 'get 'processor) 'be-os) => #f

* Menu:

* Single Row Operations::
* Match-Keys::
* Multi-Row Operations::
* Indexed Sequential Access Methods::
* Sequential Index Operations::
* Table Administration::


File: slib.info,  Node: Single Row Operations,  Next: Match-Keys,  Prev: Table Operations,  Up: Table Operations

6.1.2.1 Single Row Operations
.............................

The term "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 `#f'.  Primary keys must not be
missing.

 -- Operation on relational-table: row:insert
     Adds the row ROW to this table.  If a row for the primary key(s)
     specified by ROW already exists in this table an error is
     signaled.  The value returned is unspecified.

     (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))

 -- Operation on relational-table: row:update
     Returns a procedure of one argument, ROW, which adds the row, ROW,
     to this table.  If a row for the primary key(s) specified by ROW
     already exists in this table, it will be overwritten.  The value
     returned is unspecified.

 -- Operation on relational-table: row:retrieve
     Returns a procedure of arguments KEY1 KEY2 ... which returns the
     row associated with primary keys KEY1, KEY2 ... if it exists, or
     `#f' otherwise.

     ((plat 'row:retrieve) 'linux) => (linux i386 linux gcc)
     ((plat 'row:retrieve) 'multics) => #f

 -- Operation on relational-table: row:remove
     Returns a procedure of arguments KEY1 KEY2 ... which removes and
     returns the row associated with primary keys KEY1, KEY2 ... if it
     exists, or `#f' otherwise.

 -- Operation on relational-table: row:delete
     Returns a procedure of arguments KEY1 KEY2 ... which deletes the
     row associated with primary keys KEY1, KEY2 ... if it exists.  The
     value returned is unspecified.


File: slib.info,  Node: Match-Keys,  Next: Multi-Row Operations,  Prev: Single Row Operations,  Up: Table Operations

6.1.2.2 Match-Keys
..................

The (optional) MATCH-KEY1 ... 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 MATCH-KEY arguments default to `#f'.

The MATCH-KEY1 ... restrict the actions of the table command to those
records whose primary keys each satisfy the corresponding MATCH-KEY
argument.  The arguments and their actions are:

    `#f'
          The false value matches any key in the corresponding position.

    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 `#f' is not.

    other values
          Any other value matches only those keys `equal?' to it.

 -- Operation on relational-table: get* column-name
     Returns a procedure of optional arguments MATCH-KEY1 ... which
     returns a list of the values for the specified column for all rows
     in this table.  The optional MATCH-KEY1 ... arguments restrict
     actions to a subset of the table.

          ((plat 'get* 'processor)) =>
          (i386 i8086 i386 i8086 i386 i386 i8086 m68000
           m68000 m68000 m68000 m68000 powerpc)

          ((plat 'get* 'processor) #f) =>
          (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?) =>
          (m68000 m68000 m68000 m68000 m68000 powerpc)

          ((plat 'get* 'name) a-key?) =>
          (atari-st-turbo-c atari-st-gcc amiga-sas/c-5.10
           amiga-aztec amiga-dice-c aix)


File: slib.info,  Node: Multi-Row Operations,  Next: Indexed Sequential Access Methods,  Prev: Match-Keys,  Up: Table Operations

6.1.2.3 Multi-Row Operations
............................

 -- Operation on relational-table: row:retrieve*
     Returns a procedure of optional arguments MATCH-KEY1 ...  which
     returns a list of all rows in this table.  The optional MATCH-KEY1
     ... arguments restrict actions to a subset of the table.  For
     details see *Note Match-Keys::.

     ((plat 'row:retrieve*) a-key?) =>
     ((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 -))

 -- Operation on relational-table: row:remove*
     Returns a procedure of optional arguments MATCH-KEY1 ... which
     removes and returns a list of all rows in this table.  The optional
     MATCH-KEY1 ... arguments restrict actions to a subset of the table.

 -- Operation on relational-table: row:delete*
     Returns a procedure of optional arguments MATCH-KEY1 ...  which
     Deletes all rows from this table.  The optional MATCH-KEY1 ...
     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.

 -- Operation on relational-table: for-each-row
     Returns a procedure of arguments PROC MATCH-KEY1 ...  which calls
     PROC with each ROW in this table.  The optional MATCH-KEY1 ...
     arguments restrict actions to a subset of the table.  For details
     see *Note Match-Keys::.

Note that `row:insert*' and `row:update*' do _not_ use match-keys.

 -- Operation on relational-table: row:insert*
     Returns a procedure of one argument, ROWS, which adds each row in
     the list of rows, ROWS, to this table.  If a row for the primary
     key specified by an element of ROWS already exists in this table,
     an error is signaled.  The value returned is unspecified.

 -- Operation on relational-table: row:update*
     Returns a procedure of one argument, ROWS, which adds each row in
     the list of rows, ROWS, to this table.  If a row for the primary
     key specified by an element of ROWS already exists in this table,
     it will be overwritten.  The value returned is unspecified.


File: slib.info,  Node: Indexed Sequential Access Methods,  Next: Sequential Index Operations,  Prev: Multi-Row Operations,  Up: Table Operations

6.1.2.4 Indexed Sequential Access Methods
.........................................

"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).  "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.

Associative memory in B-Trees is an example of a database
implementation which can support a native key ordering.  SLIB's
`alist-table' implementation uses `sort' to implement
`for-each-row-in-order', but does not support `isam-next' and
`isam-prev'.

The multi-primary-key ordering employed by these operations is the
lexicographic collation of those primary-key fields in their given
order.  For example:

     (12 a 34) < (12 a 36) < (12 b 1) < (13 a 0)


File: slib.info,  Node: Sequential Index Operations,  Next: Table Administration,  Prev: Indexed Sequential Access Methods,  Up: Table Operations

6.1.2.5 Sequential Index Operations
...................................

The following procedures are individually optional depending on the
base-table implememtation.  If an operation is _not_ supported, then
calling the table with that operation symbol will return false.

 -- Operation on relational-table: for-each-row-in-order
     Returns a procedure of arguments PROC MATCH-KEY1 ...  which calls
     PROC with each ROW in this table in the (implementation-dependent)
     natural, repeatable ordering for rows.  The optional MATCH-KEY1
     ... arguments restrict actions to a subset of the table.  For
     details see *Note Match-Keys::.

 -- Operation on relational-table: isam-next
     Returns a procedure of arguments KEY1 KEY2 ... which returns the
     key-list identifying the lowest record higher than KEY1 KEY2 ...
     which is stored in the relational-table; or false if no higher
     record is present.

 -- Operation on relational-table: isam-next column-name
     The symbol COLUMN-NAME names a key field.  In the list returned by
     `isam-next', that field, or a field to its left, will be changed.
     This allows one to skip over less significant key fields.

 -- Operation on relational-table: isam-prev
     Returns a procedure of arguments KEY1 KEY2 ... which returns the
     key-list identifying the highest record less than KEY1 KEY2 ...
     which is stored in the relational-table; or false if no lower
     record is present.

 -- Operation on relational-table: isam-prev column-name
     The symbol COLUMN-NAME names a key field.  In the list returned by
     `isam-next', that field, or a field to its left, will be changed.
     This allows one to skip over less significant key fields.

  For example, if a table has key fields:
     (col1 col2)
     (9 5)
     (9 6)
     (9 7)
     (9 8)
     (12 5)
     (12 6)
     (12 7)

  Then:
     ((table 'isam-next)       '(9 5))       => (9 6)
     ((table 'isam-next 'col2) '(9 5))       => (9 6)
     ((table 'isam-next 'col1) '(9 5))       => (12 5)
     ((table 'isam-prev)       '(12 7))      => (12 6)
     ((table 'isam-prev 'col2) '(12 7))      => (12 6)
     ((table 'isam-prev 'col1) '(12 7))      => (9 8)


File: slib.info,  Node: Table Administration,  Prev: Sequential Index Operations,  Up: Table Operations

6.1.2.6 Table Administration
............................

 -- Operation on relational-table: column-names
 -- Operation on relational-table: column-foreigns
 -- Operation on relational-table: column-domains
 -- Operation on 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.

 -- Operation on relational-table: primary-limit
     Returns the number of primary keys fields in the relations in this
     table.

 -- Operation on relational-table: close-table
     Subsequent operations to this table will signal an error.


File: slib.info,  Node: Database Interpolation,  Next: Embedded Commands,  Prev: Table Operations,  Up: Relational Database

6.1.3 Database Interpolation
----------------------------

`(require 'database-interpolate)'

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.

 -- Function: interpolate-from-table table column
     TABLE should be a relational table with one numeric primary key
     field which supports the `isam-prev' and `isam-next' operations.
     COLUMN should be a symbol or exact positive integer designating a
     numerically valued column of TABLE.

     `interpolate-from-table' calculates and returns a value
     proportionally intermediate between its values in the next and
     previous key records contained in 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.


File: slib.info,  Node: Embedded Commands,  Next: Database Macros,  Prev: Database Interpolation,  Up: Relational Database

6.1.4 Embedded Commands
-----------------------

`(require 'database-commands)'

This enhancement wraps a utility layer on `relational-database' which
provides:

   * Automatic execution of initialization commands stored in database.

   * Transparent execution of database commands stored in `*commands*'
     table in database.

  When an enhanced relational-database is called with a symbol which
matches a NAME in the `*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 `*initialize*' is special.  If present in the
`*commands*' table, `open-database' or `open-database!' will return the
value of the `*initialize*' command.  Notice that arbitrary code can be
run when the `*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 *Note Database Operations::,
this can be done by a dispatch in the closure returned by the
`*initialize*' expression rather than by entries in the `*commands*'
table if it is desired that the underlying methods remain accessible to
code in the `*commands*' table.

* Menu:

* Database Extension::
* Command Intrinsics::
* Define-tables Example::
* The *commands* Table::
* Command Service::
* Command Example::


File: slib.info,  Node: Database Extension,  Next: Command Intrinsics,  Prev: Embedded Commands,  Up: Embedded Commands

6.1.4.1 Database Extension
..........................

 -- Function: wrap-command-interface rdb
     Returns relational database RDB wrapped with additional commands
     defined in its *commands* table.

 -- Function: add-command-tables rdb
     The relational database RDB must be mutable.  ADD-COMMAND-TABLES
     adds a *command* table to RDB; then returns
     `(wrap-command-interface RDB)'.

 -- Function: define-*commands* rdb spec-0 ...
     Adds commands to the `*commands*' table as specified in SPEC-0 ...
     to the open relational-database RDB.  Each SPEC has the form:

          ((<name> <rdb>) "comment" <expression1> <expression2> ...)
     or
          ((<name> <rdb>) <expression1> <expression2> ...)

     where <name> is the command name, <rdb> is a formal passed the
     calling relational database, "comment" describes the command, and
     <expression1>, <expression1>, ... are the body of the procedure.

     `define-*commands*' adds to the `*commands*' table a command
     <name>:

          (lambda (<name> <rdb>) <expression1> <expression2> ...)


 -- Function: open-command-database filename
 -- Function: open-command-database filename base-table-type
     Returns an open enhanced relational database associated with
     FILENAME.  The database will be opened with base-table type
     BASE-TABLE-TYPE) if supplied.  If BASE-TABLE-TYPE is not supplied,
     `open-command-database' will attempt to deduce the correct
     base-table-type.  If the database can not be opened or if it lacks
     the `*commands*' table, `#f' is returned.

 -- Function: open-command-database! filename
 -- Function: open-command-database! filename base-table-type
     Returns _mutable_ open enhanced relational database ...

 -- Function: open-command-database database
     Returns DATABASE if it is an immutable relational database; #f
     otherwise.

 -- Function: open-command-database! database
     Returns DATABASE if it is a mutable relational database; #f
     otherwise.


File: slib.info,  Node: Command Intrinsics,  Next: Define-tables Example,  Prev: Database Extension,  Up: Embedded Commands

6.1.4.2 Command Intrinsics
..........................

Some commands are defined in all extended relational-databases.  The are
called just like *Note Database Operations::.

 -- Operation on relational-database: add-domain domain-row
     Adds DOMAIN-ROW to the "domains" table if there is no row in the
     domains table associated with key `(car DOMAIN-ROW)' and returns
     `#t'.  Otherwise returns `#f'.

     For the fields and layout of the domain table, *Note Catalog
     Representation::.  Currently, these fields are
        * domain-name

        * foreign-table

        * domain-integrity-rule

        * type-id

        * type-param

     The following example adds 3 domains to the `build' database.
     `Optstring' is either a string or `#f'.  `filename' is a string
     and `build-whats' is a symbol.

          (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)))

 -- Operation on relational-database: delete-domain domain-name
     Removes and returns the DOMAIN-NAME row from the "domains" table.

 -- Operation on relational-database: domain-checker domain
     Returns a procedure to check an argument for conformance to domain
     DOMAIN.


File: slib.info,  Node: Define-tables Example,  Next: The *commands* Table,  Prev: Command Intrinsics,  Up: Embedded Commands

6.1.4.3 Define-tables Example
.............................

The following example shows a new database with the name of `foo.db'
being created with tables describing processor families and
processor/os/compiler combinations.  The database is then solidified;
saved and changed to immutable.

     (require '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)


File: slib.info,  Node: The *commands* Table,  Next: Command Service,  Prev: Define-tables Example,  Up: Embedded Commands

6.1.4.4 The *commands* Table
............................

The table `*commands*' in an "enhanced" relational-database has the
fields (with domains):
     PRI name        symbol
         parameters  parameter-list
         procedure   expression
         documentation string

  The `parameters' field is a foreign key (domain `parameter-list') of
the `*catalog-data*' table and should have the value of a table
described by `*parameter-columns*'.  This `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 `parameter-list' table has the
following fields:
     PRI index       ordinal
         name        symbol
         arity       parameter-arity
         domain      domain
         defaulter   expression
         expander    expression
         documentation string

  The `arity' field can take the values:

`single'
     Requires a single parameter of the specified domain.

`optional'
     A single parameter of the specified domain or zero parameters is
     acceptable.

`boolean'
     A single boolean parameter or zero parameters (in which case `#f'
     is substituted) is acceptable.

`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.

`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.

  The `domain' field specifies the domain which a parameter or
parameters in the `index'th field must satisfy.

  The `defaulter' field is an expression whose value is either `#f' or
a procedure of one argument (the parameter-list) which returns a _list_
of the default value or values as appropriate.  Note that since the
`defaulter' procedure is called every time a default parameter is
needed for this column, "sticky" defaults can be implemented using
shared state with the domain-integrity-rule.


File: slib.info,  Node: Command Service,  Next: Command Example,  Prev: The *commands* Table,  Up: Embedded Commands

6.1.4.5 Command Service
.......................

 -- Function: 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 COMMAND in table TABLE-NAME and calls the call-back
     procedure with arguments:
    COMMAND
          The COMMAND

    COMMAND-VALUE
          The result of evaluating the expression in the PROCEDURE
          field of TABLE-NAME and calling it with RDB.

    PARAMETER-NAME
          A list of the "official" name of each parameter.  Corresponds
          to the `name' field of the COMMAND's parameter-table.

    POSITIONS
          A list of the positive integer index of each parameter.
          Corresponds to the `index' field of the COMMAND's
          parameter-table.

    ARITIES
          A list of the arities of each parameter.  Corresponds to the
          `arity' field of the COMMAND's parameter-table.  For a
          description of `arity' see table above.

    TYPES
          A list of the type name of each parameter.  Correspnds to the
          `type-id' field of the contents of the `domain' of the
          COMMAND's parameter-table.

    DEFAULTERS
          A list of the defaulters for each parameter.  Corresponds to
          the `defaulters' field of the COMMAND's parameter-table.

    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 `nary' arity parameters.

    ALIASES
          A list of lists of `(alias parameter-name)'.  There can be
          more than one alias per PARAMETER-NAME.

For information about parameters, *Note Parameter lists::.


File: slib.info,  Node: Command Example,  Prev: Command Service,  Up: Embedded Commands

6.1.4.6 Command Example
.......................

Here is an example of setting up a command with arguments and parsing
those arguments from a `getopt' style argument list (*note Getopt::).

     (require 'database-commands)
     (require 'databases)
     (require 'getopt-parameters)
     (require 'parameters)
     (require '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 => "
                 (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)                              => ("str" () (symb) () #f)
     (cmd "-f")                         => ("str" () (symb) () #t)
     (cmd "--flag")                     => ("str" () (symb) () #t)
     (cmd "-o177")                      => ("str" () (symb) (177) #f)
     (cmd "-o" "177")                   => ("str" () (symb) (177) #f)
     (cmd "--optional" "621")           => ("str" () (symb) (621) #f)
     (cmd "--optional=621")             => ("str" () (symb) (621) #f)
     (cmd "-s" "speciality")            => ("speciality" () (symb) () #f)
     (cmd "-sspeciality")               => ("speciality" () (symb) () #f)
     (cmd "--single" "serendipity")     => ("serendipity" () (symb) () #f)
     (cmd "--single=serendipity")       => ("serendipity" () (symb) () #f)
     (cmd "-n" "gravity" "piety")       => ("str" () (piety gravity) () #f)
     (cmd "-ngravity" "piety")          => ("str" () (piety gravity) () #f)
     (cmd "--nary" "chastity")          => ("str" () (chastity) () #f)
     (cmd "--nary=chastity" "")         => ("str" () ( chastity) () #f)
     (cmd "-N" "calamity")              => ("str" () (calamity) () #f)
     (cmd "-Ncalamity")                 => ("str" () (calamity) () #f)
     (cmd "--nary1" "surety")           => ("str" () (surety) () #f)
     (cmd "--nary1=surety")             => ("str" () (surety) () #f)
     (cmd "-N" "levity" "fealty")       => ("str" () (fealty levity) () #f)
     (cmd "-Nlevity" "fealty")          => ("str" () (fealty levity) () #f)
     (cmd "--nary1" "surety" "brevity") => ("str" () (brevity surety) () #f)
     (cmd "--nary1=surety" "brevity")   => ("str" () (brevity surety) () #f)
     (cmd "-?")
     -|
     Usage: cmd [OPTION ARGUMENT ...] ...

       -f, --flag
       -o, --optional[=]<number>
       -n, --nary[=]<symbols> ...
       -N, --nary1[=]<symbols> ...
       -s, --single[=]<string>

     ERROR: getopt->parameter-list "unrecognized option" "-?"


File: slib.info,  Node: Database Macros,  Next: Database Browser,  Prev: Embedded Commands,  Up: Relational Database

6.1.5 Database Macros
---------------------

`(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.

  `within-database', along with the `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:

     etags -lscheme -r'/ *(define-\(command\|table\) (\([^; \t]+\)/\2/' \
           source1.scm ...

* Menu:

* Within-database::
* Within-database Example::


File: slib.info,  Node: Within-database,  Next: Within-database Example,  Prev: Database Macros,  Up: Database Macros

6.1.5.1 Within-database
.......................

 -- Function: within-database database statement-1 ...
     `within-database' creates a lexical scope in which the commands
     `define-table' and `define-command' create tables and
     `*commands*'-table entries respectively in open relational
     database DATABASE.  The expressions in `within-database' form are
     executed in order.

     `within-database' Returns DATABASE.

 -- Syntax: define-command (<name> <rdb>) "comment" <expression1>
          <expression2> ...
 -- Syntax: define-command (<name> <rdb>) <expression1> <expression2>
          ...
     Adds to the `*commands*' table a command <name>:

          (lambda (<name> <rdb>) <expression1> <expression2> ...)


 -- Syntax: define-table <name> <descriptor-name> <descriptor-name>
          <rows>
 -- Syntax: define-table <name> <primary-key-fields> <other-fields>
          <rows>
     where <name> is the table name, <descriptor-name> is the symbol
     name of a descriptor table, <primary-key-fields> and
     <other-fields> describe the primary keys and other fields
     respectively, and <rows> is a list of data rows to be added to the
     table.

     <primary-key-fields> and <other-fields> are lists of field
     descriptors of the form:

          (<column-name> <domain>)
     or
          (<column-name> <domain> <column-integrity-rule>)

     where <column-name> is the column name, <domain> is the domain of
     the column, and <column-integrity-rule> is an expression whose
     value is a procedure of one argument (which returns `#f' to signal
     an error).

     If <domain> is not a defined domain name and it matches the name of
     this table or an already defined (in one of SPEC-0 ...) single key
     field table, a foreign-key domain will be created for it.


 -- Function: add-macro-support database
     The relational database DATABASE must be mutable.
     `add-macro-support' adds a `*macros*' table and `define-macro'
     macro to DATABASE; then DATABASE is returned.

 -- Syntax: define-macro (<name> arg1 ...) "comment" <expression1>
          <expression2> ...
 -- Syntax: define-macro (<name> arg1 ...) <expression1> <expression2>
          ...
     Adds a macro <name> to the `*macros*'.

     _Note:_ `within-database' creates lexical scope where not only
     `define-command' and `define-table', but every command and macro
     are defined, ie.:

          (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 ...
            )


File: slib.info,  Node: Within-database Example,  Prev: Within-database,  Up: Database Macros

6.1.5.2 Within-database Example
...............................

Here is an example of `within-database' macros:

     (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"))
     -|
     Welcome

     (my-rdb 'without-documentation)
     -|
     without-documentation called

     ((my-rdb 'get-processor) 'amiga-sas/c-5.10)
     => m68000

     (close-database my-rdb)


File: slib.info,  Node: Database Browser,  Prev: Database Macros,  Up: Relational Database

6.1.6 Database Browser
----------------------

(require 'database-browse)

 -- Procedure: browse database
     Prints the names of all the tables in DATABASE and sets browse's
     default to DATABASE.

 -- Procedure: browse
     Prints the names of all the tables in the default database.

 -- Procedure: browse table-name
     For each record of the table named by the symbol TABLE-NAME,
     prints a line composed of all the field values.

 -- Procedure: browse pathname
     Opens the database named by the string PATHNAME, prints the names
     of all its tables, and sets browse's default to the database.

 -- Procedure: browse database table-name
     Sets browse's default to DATABASE and prints the records of the
     table named by the symbol TABLE-NAME.

 -- Procedure: browse pathname table-name
     Opens the database named by the string PATHNAME and sets browse's
     default to it; `browse' prints the records of the table named by
     the symbol TABLE-NAME.



File: slib.info,  Node: Relational Infrastructure,  Next: Weight-Balanced Trees,  Prev: Relational Database,  Up: Database Packages

6.2 Relational Infrastructure
=============================

* Menu:

* Base Table::
* Catalog Representation::
* Relational Database Objects::
* Database Operations::


File: slib.info,  Node: Base Table,  Next: Catalog Representation,  Prev: Relational Infrastructure,  Up: Relational Infrastructure

6.2.1 Base Table
----------------

A "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. ALIST-TABLE) after requiring the symbol of
that name.

 -- Feature: alist-table
     `(require '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 "alist-table" base-table implementation is included in the
     SLIB distribution.

  "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.

 -- Feature: wb-table
     `(require 'wb-table)' 

     `wb-table' supports scheme expressions for keys and values whose
     text representations are less than 255 characters in length.
     *Note wb-table: (wb)wb-table.

 -- Feature: rwb-isam
     `(require 'rwb-isam)' 

     "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.

  This rest of this section documents the interface for a base table
implementation from which the *Note Relational Database:: package
constructs a Relational system.  It will be of interest primarily to
those wishing to port or write new base-table implementations.

 -- Variable: *base-table-implementations*
     To support automatic dispatch for `open-database', each base-table
     module adds an association to *BASE-TABLE-IMPLEMENTATIONS* when
     loaded.  This association is the list of the base-table symbol and
     the value returned by `(make-relational-system BASE-TABLE)'.

* Menu:

* The Base::
* Base Tables::
* Base Field Types::
* Composite Keys::
* Base Record Operations::
* Match Keys::
* Aggregate Base Operations::
* Base ISAM Operations::


File: slib.info,  Node: The Base,  Next: Base Tables,  Prev: Base Table,  Up: Base Table

6.2.1.1 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 `#f'
otherwise.  For example:

     (require 'alist-table)
     (define my-base (alist-table 'make-base))
     my-base         => *a procedure*
     (define foo (alist-table 'foo))
     foo             => #f

 -- Operation on base-table: make-base filename key-dimension
          column-types
     Returns a new, open, low-level database (collection of tables)
     associated with FILENAME.  This returned database has an empty
     table associated with CATALOG-ID.  The positive integer
     KEY-DIMENSION is the number of keys composed to make a PRIMARY-KEY
     for the catalog table.  The list of symbols COLUMN-TYPES describes
     the types of each column for that table.  If the database cannot
     be created as specified, `#f' is returned.

     Calling the `close-base' method on this database and possibly other
     operations will cause FILENAME to be written to.  If FILENAME is
     `#f' a temporary, non-disk based database will be created if such
     can be supported by the base table implelentation.

 -- Operation on base-table: open-base filename mutable
     Returns an open low-level database associated with FILENAME.  If
     MUTABLE is `#t', this database will have methods capable of
     effecting change to the database.  If MUTABLE is `#f', only
     methods for inquiring the database will be available.  If the
     database cannot be opened as specified `#f' is returned.

     Calling the `close-base' (and possibly other) method on a MUTABLE
     database will cause FILENAME to be written to.

 -- Operation on base-table: write-base lldb filename
     Causes the low-level database LLDB to be written to FILENAME.  If
     the write is successful, also causes LLDB to henceforth be
     associated with FILENAME.  Calling the `close-database' (and
     possibly other) method on LLDB may cause FILENAME to be written
     to.  If FILENAME is `#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, `#t' is returned.  Otherwise, `#f' is returned.

 -- Operation on base-table: sync-base lldb
     Causes the file associated with the low-level database LLDB to be
     updated to reflect its current state.  If the associated filename
     is `#f', no action is taken and `#f' is returned.  If this
     operation completes successfully, `#t' is returned.  Otherwise,
     `#f' is returned.

 -- Operation on base-table: close-base lldb
     Causes the low-level database LLDB to be written to its associated
     file (if any).  If the write is successful, subsequent operations
     to LLDB will signal an error.  If the operations complete
     successfully, `#t' is returned.  Otherwise, `#f' is returned.


File: slib.info,  Node: Base Tables,  Next: Base Field Types,  Prev: The Base,  Up: Base Table

6.2.1.2 Base Tables
...................

 -- Operation on base-table: make-table lldb key-dimension column-types
     Returns the ordinal BASE-ID for a new base table, otherwise
     returns `#f'.  The base table can then be opened using
     `(open-table LLDB BASE-ID)'.  The positive integer KEY-DIMENSION
     is the number of keys composed to make a PRIMARY-KEY for this
     table.  The list of symbols COLUMN-TYPES describes the types of
     each column.

 -- Operation on base-table: open-table lldb base-id key-dimension
          column-types
     Returns a HANDLE for an existing base table in the low-level
     database LLDB if that table exists and can be opened in the mode
     indicated by MUTABLE, otherwise returns `#f'.

     As with `make-table', the positive integer KEY-DIMENSION is the
     number of keys composed to make a PRIMARY-KEY for this table.  The
     list of symbols COLUMN-TYPES describes the types of each column.

 -- Operation on base-table: kill-table lldb base-id key-dimension
          column-types
     Returns `#t' if the base table associated with BASE-ID was removed
     from the low level database LLDB, and `#f' otherwise.

 -- Operation on base-table: catalog-id
     A constant BASE-ID ordinal suitable for passing as a parameter to
     `open-table'.  CATALOG-ID will be used as the base table for the
     system catalog.


File: slib.info,  Node: Base Field Types,  Next: Composite Keys,  Prev: Base Tables,  Up: Base Table

6.2.1.3 Base Field Types
........................

 -- Operation on base-table: supported-type? symbol
     Returns `#t' if SYMBOL names a type allowed as a column value by
     the implementation, and `#f' otherwise.  At a minimum, an
     implementation must support the types `integer', `ordinal',
     `symbol', `string', and `boolean'.

 -- Operation on base-table: supported-key-type? symbol
     Returns `#t' if SYMBOL names a type allowed as a key value by the
     implementation, and `#f' otherwise.  At a minimum, an
     implementation must support the types `ordinal', and `symbol'.

An "ordinal" is an exact positive integer.  The other types are
standard Scheme.


File: slib.info,  Node: Composite Keys,  Next: Base Record Operations,  Prev: Base Field Types,  Up: Base Table

6.2.1.4 Composite Keys
......................

 -- Operation on base-table: make-keyifier-1 type
     Returns a procedure which accepts a single argument which must be
     of type TYPE.  This returned procedure returns an object suitable
     for being a KEY argument in the functions whose descriptions
     follow.

     Any 2 arguments of the supported type passed to the returned
     function which are not `equal?' must result in returned values
     which are not `equal?'.

 -- Operation on base-table: make-list-keyifier key-dimension types
     The list of symbols TYPES must have at least KEY-DIMENSION
     elements.  Returns a procedure which accepts a list of length
     KEY-DIMENSION and whose types must corresopond to the types named
     by TYPES.  This returned procedure combines the elements of its
     list argument into an object suitable for being a 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 `equal?' must result in returned values which are not
     `equal?'.

 -- Operation on base-table: make-key-extractor key-dimension types
          column-number
     Returns a procedure which accepts objects produced by application
     of the result of `(make-list-keyifier KEY-DIMENSION TYPES)'.  This
     procedure returns a KEY which is `equal?' to the COLUMN-NUMBERth
     element of the list which was passed to create COMPOSITE-KEY.  The
     list TYPES must have at least KEY-DIMENSION elements.

 -- Operation on base-table: make-key->list key-dimension types
     Returns a procedure which accepts objects produced by application
     of the result of `(make-list-keyifier KEY-DIMENSION TYPES)'.  This
     procedure returns a list of KEYs which are elementwise `equal?' to
     the list which was passed to create COMPOSITE-KEY.


File: slib.info,  Node: Base Record Operations,  Next: Match Keys,  Prev: Composite Keys,  Up: Base Table

6.2.1.5 Base Record Operations
..............................

In the following functions, the KEY argument can always be assumed to
be the value returned by a call to a _keyify_ routine.

 -- Operation on base-table: present? handle key
     Returns a non-`#f' value if there is a row associated with KEY in
     the table opened in HANDLE and `#f' otherwise.

 -- Operation on base-table: make-getter key-dimension types
     Returns a procedure which takes arguments HANDLE and KEY.  This
     procedure returns a list of the non-primary values of the relation
     (in the base table opened in HANDLE) whose primary key is KEY if
     it exists, and `#f' otherwise.

`make-getter-1' is a new operation.  The relational-database module
works with older base-table implementations by using `make-getter'.

 -- Operation on base-table: make-getter-1 key-dimension types index
     Returns a procedure which takes arguments HANDLE and KEY.  This
     procedure returns the value of the INDEXth field (in the base
     table opened in HANDLE) whose primary key is KEY if it exists, and
     `#f' otherwise.

     INDEX must be larger than KEY-DIMENSION.

 -- Operation on base-table: make-putter key-dimension types
     Returns a procedure which takes arguments HANDLE and KEY and
     VALUE-LIST.  This procedure associates the primary key KEY with
     the values in VALUE-LIST (in the base table opened in HANDLE) and
     returns an unspecified value.

 -- Operation on base-table: delete handle key
     Removes the row associated with KEY from the table opened in
     HANDLE.  An unspecified value is returned.


File: slib.info,  Node: Match Keys,  Next: Aggregate Base Operations,  Prev: Base Record Operations,  Up: Base Table

6.2.1.6 Match Keys
..................

A MATCH-KEYS argument is a list of length equal to the number of
primary keys.  The MATCH-KEYS restrict the actions of the table command
to those records whose primary keys all satisfy the corresponding
element of the MATCH-KEYS list.  The elements and their actions are:

    `#f'
          The false value matches any key in the corresponding position.

    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 `#f' is not.

    other values
          Any other value matches only those keys `equal?' to it.


File: slib.info,  Node: Aggregate Base Operations,  Next: Base ISAM Operations,  Prev: Match Keys,  Up: Base Table

6.2.1.7 Aggregate Base Operations
.................................

The KEY-DIMENSION and COLUMN-TYPES arguments are needed to decode the
composite-keys for matching with MATCH-KEYS.

 -- Operation on base-table: delete* handle key-dimension column-types
          match-keys
     Removes all rows which satisfy MATCH-KEYS from the table opened in
     HANDLE.  An unspecified value is returned.

 -- Operation on base-table: for-each-key handle procedure
          key-dimension column-types match-keys
     Calls PROCEDURE once with each KEY in the table opened in HANDLE
     which satisfy MATCH-KEYS in an unspecified order.  An unspecified
     value is returned.

 -- Operation on base-table: map-key handle procedure key-dimension
          column-types match-keys
     Returns a list of the values returned by calling PROCEDURE once
     with each KEY in the table opened in HANDLE which satisfy
     MATCH-KEYS in an unspecified order.


File: slib.info,  Node: Base ISAM Operations,  Prev: Aggregate Base Operations,  Up: Base Table

6.2.1.8 Base ISAM Operations
............................

These operations are optional for a Base-Table implementation.

 -- Operation on base-table: ordered-for-each-key handle procedure
          key-dimension column-types match-keys
     Calls PROCEDURE once with each KEY in the table opened in HANDLE
     which satisfy MATCH-KEYS in the natural order for the types of the
     primary key fields of that table.  An unspecified value is
     returned.

 -- Operation on base-table: make-nexter handle key-dimension
          column-types index
     Returns a procedure of arguments KEY1 KEY2 ... which returns the
     key-list identifying the lowest record higher than KEY1 KEY2 ...
     which is stored in the base-table and which differs in column
     INDEX or a lower indexed key; or false if no higher record is
     present.

 -- Operation on base-table: make-prever handle key-dimension
          column-types index
     Returns a procedure of arguments KEY1 KEY2 ... which returns the
     key-list identifying the highest record less than KEY1 KEY2 ...
     which is stored in the base-table and which differs in column
     INDEX or a lower indexed key; or false if no higher record is
     present.


File: slib.info,  Node: Catalog Representation,  Next: Relational Database Objects,  Prev: Base Table,  Up: Relational Infrastructure

6.2.2 Catalog Representation
----------------------------

Each database (in an implementation) has a "system catalog" which
describes all the user accessible tables in that database (including
itself).

The system catalog base table has the following fields.  `PRI'
indicates a primary key for that table.

     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.

Descriptors for base tables (not views) are tables (pointed to by
system catalog).  Descriptor (base) tables have the fields:

     PRI column-number           sequential integers from 1
         primary-key?            boolean TRUE for primary key components
         column-name
         column-integrity-rule
         domain-name

A "primary key" is any column marked as `primary-key?' in the
corresponding descriptor table.  All the `primary-key?' columns must
have lower column numbers than any non-`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.

A "domain" is a category describing the allowable values to occur in a
column.  It is described by a (base) table with the fields:

     PRI domain-name
         foreign-table
         domain-integrity-rule
         type-id
         type-param

The "type-id" field value is a symbol.  This symbol may be used by the
underlying base table implementation in storing that field.

If the `foreign-table' field is non-`#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 TYPE-PARAM (or `#f', if allowed).  This
package currently does not support composite foreign-keys.

The types for which support is planned are:
         atom
         symbol
         string                  [<length>]
         number                  [<base>]
         money                   <currency>
         date-time
         boolean

         foreign-key             <table-name>
         expression
         virtual                 <expression>


File: slib.info,  Node: Relational Database Objects,  Next: Database Operations,  Prev: Catalog Representation,  Up: Relational Infrastructure

6.2.3 Relational Database Objects
---------------------------------

This object-oriented interface is deprecated for typical database
applications; *Note Using Databases:: provides an application programmer
interface which is easier to understand and use.

 -- Function: make-relational-system base-table-implementation
     Returns a procedure implementing a relational database using the
     BASE-TABLE-IMPLEMENTATION.

     All of the operations of a base table implementation are accessed
     through a procedure defined by `require'ing that implementation.
     Similarly, all of the operations of the relational database
     implementation are accessed through the procedure returned by
     `make-relational-system'.  For instance, a new relational database
     could be created from the procedure returned by
     `make-relational-system' by:

          (require '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"))

What follows are the descriptions of the methods available from
relational system returned by a call to `make-relational-system'.

 -- Operation on relational-system: create-database filename
     Returns an open, nearly empty relational database associated with
     FILENAME.  The only tables defined are the system catalog and
     domain table.  Calling the `close-database' method on this database
     and possibly other operations will cause FILENAME to be written
     to.  If FILENAME is `#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
     `#f' is returned.  For the fields and layout of descriptor tables,
     *Note Catalog Representation::

 -- Operation on relational-system: open-database filename mutable?
     Returns an open relational database associated with FILENAME.  If
     MUTABLE? is `#t', this database will have methods capable of
     effecting change to the database.  If MUTABLE? is `#f', only
     methods for inquiring the database will be available.  Calling the
     `close-database' (and possibly other) method on a MUTABLE?
     database will cause FILENAME to be written to.  If the database
     cannot be opened as specified `#f' is returned.


File: slib.info,  Node: Database Operations,  Prev: Relational Database Objects,  Up: Relational Infrastructure

6.2.4 Database Operations
-------------------------

This object-oriented interface is deprecated for typical database
applications; *Note Using Databases:: provides an application programmer
interface which is easier to understand and use.

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:

     (define my-database
             (create-alist-database "mydata.db"))
     (define telephone-table-desc
             ((my-database 'create-table) 'telephone-table-desc))

 -- Operation on 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, `#t' is returned.  Otherwise, `#f' is returned.

 -- Operation on relational-database: write-database filename
     Causes the relational database to be written to FILENAME.  If the
     write is successful, also causes the database to henceforth be
     associated with FILENAME.  Calling the `close-database' (and
     possibly other) method on this database will cause FILENAME to be
     written to.  If FILENAME is `#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, `#t' is returned.  Otherwise, `#f' is
     returned.

 -- Operation on relational-database: sync-database
     Causes any pending updates to the database file to be written out.
     If the operations completed successfully, `#t' is returned.
     Otherwise, `#f' is returned.

 -- Operation on 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 `#t' is returned.  Otherwise, `#f' is
     returned.

 -- Operation on relational-database: table-exists? table-name
     Returns `#t' if TABLE-NAME exists in the system catalog, otherwise
     returns `#f'.

 -- Operation on relational-database: open-table table-name mutable?
     Returns a "methods" procedure for an existing relational table in
     this database if it exists and can be opened in the mode indicated
     by MUTABLE?, otherwise returns `#f'.

These methods will be present only in mutable databases.

 -- Operation on relational-database: delete-table table-name
     Removes and returns the TABLE-NAME row from the system catalog if
     the table or view associated with TABLE-NAME gets removed from the
     database, and `#f' otherwise.

 -- Operation on 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 `#f'.  For the fields and layout of descriptor
     tables, *Note Catalog Representation::.

 -- Operation on relational-database: create-table table-name
          table-desc-name
     Returns a methods procedure for a new (open) relational table with
     columns as described by TABLE-DESC-NAME, otherwise returns `#f'.

 -- Operation on relational-database: create-view ??
 -- Operation on relational-database: project-table ??
 -- Operation on relational-database: restrict-table ??
 -- Operation on relational-database: cart-prod-tables ??
     Not yet implemented.


File: slib.info,  Node: Weight-Balanced Trees,  Prev: Relational Infrastructure,  Up: Database Packages

6.3 Weight-Balanced Trees
=========================

`(require 'wt-tree)' 

  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:

   * 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.

   * 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.

   * Operations to find and remove minimum element make weight balanced
     trees simple to use for priority queues.

   * The implementation is _functional_ rather than _imperative_.  This
     means that operations like `inserting' an association in a tree do
     not destroy the old tree, in much the same way that `(+ 1 x)'
     modifies neither the constant 1 nor the value bound to `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.


  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 _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.

  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 `()',
`#t' or `#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 `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,
`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
`wt-tree/member?' rather than `wt-tree/defined-at?'.

  The weight balanced tree implementation is a run-time-loadable option.
To use weight balanced trees, execute

     (load-option 'wt-tree)
  
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::


File: slib.info,  Node: Construction of Weight-Balanced Trees,  Next: Basic Operations on Weight-Balanced Trees,  Prev: Weight-Balanced Trees,  Up: Weight-Balanced Trees

6.3.1 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 _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.

 -- procedure+: make-wt-tree-type key<?
     This procedure creates and returns a new tree type based on the
     ordering predicate KEY<?.  KEY<? must be a total ordering, having
     the property that for all key values `a', `b' and `c':

          (key<? a a)                         => #f
          (and (key<? a b) (key<? b a))       => #f
          (if (and (key<? a b) (key<? b c))
              (key<? a c)
              #t)                             => #t

     Two key values are assumed to be equal if neither is less than the
     other by KEY<?.

     Each call to `make-wt-tree-type' returns a distinct value, and
     trees are only compatible if their tree types are `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 `make-wt-tree-type'.

 -- variable+: number-wt-type
     A standard tree type for trees with numeric keys.  `Number-wt-type'
     could have been defined by

          (define number-wt-type (make-wt-tree-type  <))

 -- variable+: string-wt-type
     A standard tree type for trees with string keys.  `String-wt-type'
     could have been defined by

          (define string-wt-type (make-wt-tree-type  string<?))

 -- 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.  WT-TREE-TYPE is a weight balanced tree type
     obtained by calling `make-wt-tree-type'; the returned tree has
     this type.

 -- 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
     DATUM with KEY.  WT-TREE-TYPE is a weight balanced tree type
     obtained by calling `make-wt-tree-type'; the returned tree has
     this type.

 -- procedure+: alist->wt-tree tree-type alist
     Returns a newly allocated weight-balanced tree that contains the
     same associations as ALIST.  This procedure is equivalent to:

          (lambda (type alist)
            (let ((tree (make-wt-tree type)))
              (for-each (lambda (association)
                          (wt-tree/add! tree
                                        (car association)
                                        (cdr association)))
                        alist)
              tree))


File: slib.info,  Node: Basic Operations on Weight-Balanced Trees,  Next: Advanced Operations on Weight-Balanced Trees,  Prev: Construction of Weight-Balanced Trees,  Up: Weight-Balanced Trees

6.3.2 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.

 -- procedure+: wt-tree/empty? wt-tree
     Returns `#t' if WT-TREE contains no associations, otherwise
     returns `#f'.

 -- procedure+: wt-tree/size wt-tree
     Returns the number of associations in WT-TREE, an exact
     non-negative integer.  This operation takes constant time.

 -- procedure+: wt-tree/add wt-tree key datum
     Returns a new tree containing all the associations in WT-TREE and
     the association of DATUM with KEY.  If WT-TREE already had an
     association for 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
     WT-TREE.

 -- procedure+: wt-tree/add! wt-tree key datum
     Associates DATUM with KEY in WT-TREE and returns an unspecified
     value.  If WT-TREE already has an association for 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 WT-TREE.

 -- procedure+: wt-tree/member? key wt-tree
     Returns `#t' if WT-TREE contains an association for KEY, otherwise
     returns `#f'.  The average and worst-case times required by this
     operation are proportional to the logarithm of the number of
     associations in WT-TREE.

 -- procedure+: wt-tree/lookup wt-tree key default
     Returns the datum associated with KEY in WT-TREE.  If WT-TREE
     doesn't contain an association for KEY, DEFAULT is returned.  The
     average and worst-case times required by this operation are
     proportional to the logarithm of the number of associations in
     WT-TREE.

 -- procedure+: wt-tree/delete wt-tree key
     Returns a new tree containing all the associations in WT-TREE,
     except that if WT-TREE contains an association for 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 WT-TREE.

 -- procedure+: wt-tree/delete! wt-tree key
     If WT-TREE contains an association for 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 WT-TREE.


File: slib.info,  Node: Advanced Operations on Weight-Balanced Trees,  Next: Indexing Operations on Weight-Balanced Trees,  Prev: Basic Operations on Weight-Balanced Trees,  Up: Weight-Balanced Trees

6.3.3 Advanced Operations on Weight-Balanced Trees
--------------------------------------------------

In the following the _size_ of a tree is the number of associations
that the tree contains, and a _smaller_ tree contains fewer
associations.

 -- procedure+: wt-tree/split< wt-tree bound
     Returns a new tree containing all and only the associations in
     WT-TREE which have a key that is less than BOUND in the ordering
     relation of the tree type of WT-TREE.  The average and worst-case
     times required by this operation are proportional to the logarithm
     of the size of WT-TREE.

 -- procedure+: wt-tree/split> wt-tree bound
     Returns a new tree containing all and only the associations in
     WT-TREE which have a key that is greater than BOUND in the
     ordering relation of the tree type of WT-TREE.  The average and
     worst-case times required by this operation are proportional to the
     logarithm of size of WT-TREE.

 -- 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
     WT-TREE-2 with the key.  Thus if the trees are viewed as discrete
     maps then `wt-tree/union' computes the map override of WT-TREE-1 by
     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.

 -- procedure+: wt-tree/intersection wt-tree-1 wt-tree-2
     Returns a new tree containing all and only those associations from
     WT-TREE-1 which have keys appearing as the key of an association
     in WT-TREE-2.  Thus the associated data in the result are those
     from 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, `wt-tree/intersection' computes the domain restriction
     of WT-TREE-1 to (the domain of) WT-TREE-2.  The time required by
     this operation is never worse that proportional to the sum of the
     sizes of the trees.

 -- procedure+: wt-tree/difference wt-tree-1 wt-tree-2
     Returns a new tree containing all and only those associations from
     WT-TREE-1 which have keys that _do not_ appear as the key of an
     association in 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
     WT-TREE-1 to the complement of (the domain of) WT-TREE-2.  The
     time required by this operation is never worse that proportional to
     the sum of the sizes of the trees.

 -- procedure+: wt-tree/subset? wt-tree-1 wt-tree-2
     Returns `#t' iff the key of each association in WT-TREE-1 is the
     key of some association in WT-TREE-2, otherwise returns `#f'.
     Viewed as a set operation, `wt-tree/subset?' is the improper subset
     predicate.  A proper subset predicate can be constructed:

          (define (proper-subset? s1 s2)
            (and (wt-tree/subset? s1 s2)
                 (< (wt-tree/size s1) (wt-tree/size s2))))

     As a discrete map operation, `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
     WT-TREE-1.

 -- procedure+: wt-tree/set-equal? wt-tree-1 wt-tree-2
     Returns `#t' iff for every association in WT-TREE-1 there is an
     association in WT-TREE-2 that has the same key, and _vice versa_.

     Viewing the arguments as sets `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

          (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)))

     In the worst-case the time required by this operation is
     proportional to the size of the smaller tree.

 -- procedure+: wt-tree/fold combiner initial wt-tree
     This procedure reduces WT-TREE by combining all the associations,
     using an reverse in-order traversal, so the associations are
     visited in reverse order.  COMBINER is a procedure of three
     arguments: a key, a datum and the accumulated result so far.
     Provided COMBINER takes time bounded by a constant, `wt-tree/fold'
     takes time proportional to the size of WT-TREE.

     A sorted association list can be derived simply:

          (wt-tree/fold  (lambda (key datum list)
                           (cons (cons key datum) list))
                         '()
                         WT-TREE))

     The data in the associations can be summed like this:

          (wt-tree/fold  (lambda (key datum sum) (+ sum datum))
                         0
                         WT-TREE)

 -- procedure+: wt-tree/for-each action wt-tree
     This procedure traverses the tree in-order, applying ACTION to
     each association.  The associations are processed in increasing
     order of their keys.  ACTION is a procedure of two arguments which
     take the key and datum respectively of the association.  Provided
     ACTION takes time bounded by a constant, `wt-tree/for-each' takes
     time proportional to in the size of WT-TREE.  The example prints
     the tree:

          (wt-tree/for-each (lambda (key value)
                              (display (list key value)))
                            WT-TREE))


File: slib.info,  Node: Indexing Operations on Weight-Balanced Trees,  Prev: Advanced Operations on Weight-Balanced Trees,  Up: Weight-Balanced Trees

6.3.4 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.

 -- procedure+: wt-tree/index wt-tree index
 -- procedure+: wt-tree/index-datum wt-tree index
 -- procedure+: wt-tree/index-pair wt-tree index
     Returns the 0-based INDEXth association of WT-TREE in the sorted
     sequence under the tree's ordering relation on the keys.
     `wt-tree/index' returns the INDEXth key, `wt-tree/index-datum'
     returns the datum associated with the INDEXth key and
     `wt-tree/index-pair' returns a new pair `(KEY . DATUM)' which is
     the `cons' of the INDEXth 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
     INDEX`<0', or if 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:

     median:  (wt-tree/index WT-TREE (quotient (wt-tree/size WT-TREE) 2))

     maximum: (wt-tree/index WT-TREE (-1+ (wt-tree/size WT-TREE)))

 -- procedure+: wt-tree/rank wt-tree key
     Determines the 0-based position of KEY in the sorted sequence of
     the keys under the tree's ordering relation, or `#f' if the tree
     has no association with for KEY.  This procedure returns either an
     exact non-negative integer or `#f'.  The average and worst-case
     times required by this operation are proportional to the logarithm
     of the number of associations in the tree.

 -- procedure+: wt-tree/min wt-tree
 -- procedure+: wt-tree/min-datum wt-tree
 -- procedure+: wt-tree/min-pair wt-tree
     Returns the association of WT-TREE that has the least key under
     the tree's ordering relation.  `wt-tree/min' returns the least key,
     `wt-tree/min-datum' returns the datum associated with the least key
     and `wt-tree/min-pair' returns a new pair `(key . datum)' which is
     the `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
          (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))

 -- procedure+: wt-tree/delete-min wt-tree
     Returns a new tree containing all of the associations in WT-TREE
     except the association with the least key under the 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

          (wt-tree/delete WT-TREE (wt-tree/min WT-TREE))

 -- procedure+: wt-tree/delete-min! wt-tree
     Removes the association with the least key under the 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

          (wt-tree/delete! WT-TREE (wt-tree/min WT-TREE))


File: slib.info,  Node: Other Packages,  Next: About SLIB,  Prev: Database Packages,  Up: Top

7 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.


File: slib.info,  Node: Data Structures,  Next: Sorting and Searching,  Prev: Other Packages,  Up: Other Packages

7.1 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


File: slib.info,  Node: Arrays,  Next: Subarrays,  Prev: Data Structures,  Up: Data Structures

7.1.1 Arrays
------------

`(require 'array)' or `(require 'srfi-63)' 

 -- Function: array? obj
     Returns `#t' if the OBJ is an array, and `#f' if not.

_Note:_ Arrays are not disjoint from other Scheme types.  Vectors and
possibly strings also satisfy `array?'.  A disjoint array predicate can
be written:

     (define (strict-array? obj)
       (and (array? obj) (not (string? obj)) (not (vector? obj))))

 -- Function: equal? obj1 obj2
     Returns `#t' if OBJ1 and OBJ2 have the same rank and dimensions
     and the corresponding elements of OBJ1 and OBJ2 are `equal?'.

     `equal?' recursively compares the contents of pairs, vectors,
     strings, and _arrays_, applying `eqv?' on other objects such as
     numbers and symbols.  A rule of thumb is that objects are
     generally `equal?' if they print the same.  `equal?' may fail to
     terminate if its arguments are circular data structures.

          (equal? 'a 'a)                             =>  #t
          (equal? '(a) '(a))                         =>  #t
          (equal? '(a (b) c)
                  '(a (b) c))                        =>  #t
          (equal? "abc" "abc")                       =>  #t
          (equal? 2 2)                               =>  #t
          (equal? (make-vector 5 'a)
                  (make-vector 5 'a))                =>  #t
          (equal? (make-array (A:fixN32b 4) 5 3)
                  (make-array (A:fixN32b 4) 5 3))    =>  #t
          (equal? (make-array '#(foo) 3 3)
                  (make-array '#(foo) 3 3))          =>  #t
          (equal? (lambda (x) x)
                  (lambda (y) y))                    =>  _unspecified_

 -- Function: array-rank obj
     Returns the number of dimensions of OBJ.  If OBJ is not an array,
     0 is returned.

 -- Function: array-dimensions array
     Returns a list of dimensions.

          (array-dimensions (make-array '#() 3 5))
             => (3 5)

 -- Function: make-array prototype k1 ...
     Creates and returns an array of type PROTOTYPE with dimensions K1,
     ...  and filled with elements from PROTOTYPE.  PROTOTYPE must be
     an array, vector, or string.  The implementation-dependent type of
     the returned array will be the same as the type of PROTOTYPE;
     except if that would be a vector or string with rank not equal to
     one, in which case some variety of array will be returned.

     If the PROTOTYPE has no elements, then the initial contents of the
     returned array are unspecified.  Otherwise, the returned array
     will be filled with the element at the origin of PROTOTYPE.

 -- Function: create-array prototype k1 ...
     `create-array' is an alias for `make-array'.

 -- Function: make-shared-array array mapper k1 ...
     `make-shared-array' can be used to create shared subarrays of other
     arrays.  The MAPPER is a function that translates coordinates in
     the new array into coordinates in the old array.  A MAPPER must be
     linear, and its range must stay within the bounds of the old
     array, but it can be otherwise arbitrary.  A simple example:

          (define fred (make-array '#(#f) 8 8))
          (define freds-diagonal
            (make-shared-array fred (lambda (i) (list i i)) 8))
          (array-set! freds-diagonal 'foo 3)
          (array-ref fred 3 3)
             => FOO
          (define freds-center
            (make-shared-array fred (lambda (i j) (list (+ 3 i) (+ 3 j)))
                               2 2))
          (array-ref freds-center 0 0)
             => FOO

 -- Function: list->array rank proto list
     LIST must be a rank-nested list consisting of all the elements, in
     row-major order, of the array to be created.

     `list->array' returns an array of rank RANK and type PROTO
     consisting of all the elements, in row-major order, of LIST.  When
     RANK is 0, LIST is the lone array element; not necessarily a list.

          (list->array 2 '#() '((1 2) (3 4)))
                          => #2A((1 2) (3 4))
          (list->array 0 '#() 3)
                          => #0A 3

 -- Function: array->list array
     Returns a rank-nested list consisting of all the elements, in
     row-major order, of ARRAY.  In the case of a rank-0 array,
     `array->list' returns the single element.

          (array->list #2A((ho ho ho) (ho oh oh)))
                          => ((ho ho ho) (ho oh oh))
          (array->list #0A ho)
                          => ho

 -- Function: vector->array vect proto dim1 ...
     VECT must be a vector of length equal to the product of exact
     nonnegative integers DIM1, ....

     `vector->array' returns an array of type PROTO consisting of all
     the elements, in row-major order, of VECT.  In the case of a
     rank-0 array, VECT has a single element.

          (vector->array #(1 2 3 4) #() 2 2)
                          => #2A((1 2) (3 4))
          (vector->array '#(3) '#())
                          => #0A 3

 -- Function: array->vector array
     Returns a new vector consisting of all the elements of ARRAY in
     row-major order.

          (array->vector #2A ((1 2)( 3 4)))
                          => #(1 2 3 4)
          (array->vector #0A ho)
                          => #(ho)

 -- Function: array-in-bounds? array index1 ...
     Returns `#t' if its arguments would be acceptable to `array-ref'.

 -- Function: array-ref array k1 ...
     Returns the (K1, ...) element of ARRAY.

 -- Procedure: array-set! array obj k1 ...
     Stores OBJ in the (K1, ...) element of ARRAY.  The value returned
     by `array-set!' is unspecified.

These functions return a prototypical uniform-array enclosing the
optional argument (which must be of the correct type).  If the
uniform-array type is supported by the implementation, then it is
returned; defaulting to the next larger precision type; resorting
finally to vector.

 -- Function: A:floC128b z
 -- Function: A:floC128b
     Returns an inexact 128.bit flonum complex uniform-array prototype.

 -- Function: A:floC64b z
 -- Function: A:floC64b
     Returns an inexact 64.bit flonum complex uniform-array prototype.

 -- Function: A:floC32b z
 -- Function: A:floC32b
     Returns an inexact 32.bit flonum complex uniform-array prototype.

 -- Function: A:floC16b z
 -- Function: A:floC16b
     Returns an inexact 16.bit flonum complex uniform-array prototype.

 -- Function: A:floR128b x
 -- Function: A:floR128b
     Returns an inexact 128.bit flonum real uniform-array prototype.

 -- Function: A:floR64b x
 -- Function: A:floR64b
     Returns an inexact 64.bit flonum real uniform-array prototype.

 -- Function: A:floR32b x
 -- Function: A:floR32b
     Returns an inexact 32.bit flonum real uniform-array prototype.

 -- Function: A:floR16b x
 -- Function: A:floR16b
     Returns an inexact 16.bit flonum real uniform-array prototype.

 -- Function: A:floR128d q
 -- Function: A:floR128d
     Returns an exact 128.bit decimal flonum rational uniform-array
     prototype.

 -- Function: A:floR64d q
 -- Function: A:floR64d
     Returns an exact 64.bit decimal flonum rational uniform-array
     prototype.

 -- Function: A:floR32d q
 -- Function: A:floR32d
     Returns an exact 32.bit decimal flonum rational uniform-array
     prototype.

 -- Function: A:fixZ64b n
 -- Function: A:fixZ64b
     Returns an exact binary fixnum uniform-array prototype with at
     least 64 bits of precision.

 -- Function: A:fixZ32b n
 -- Function: A:fixZ32b
     Returns an exact binary fixnum uniform-array prototype with at
     least 32 bits of precision.

 -- Function: A:fixZ16b n
 -- Function: A:fixZ16b
     Returns an exact binary fixnum uniform-array prototype with at
     least 16 bits of precision.

 -- Function: A:fixZ8b n
 -- Function: A:fixZ8b
     Returns an exact binary fixnum uniform-array prototype with at
     least 8 bits of precision.

 -- Function: A:fixN64b k
 -- Function: A:fixN64b
     Returns an exact non-negative binary fixnum uniform-array
     prototype with at least 64 bits of precision.

 -- Function: A:fixN32b k
 -- Function: A:fixN32b
     Returns an exact non-negative binary fixnum uniform-array
     prototype with at least 32 bits of precision.

 -- Function: A:fixN16b k
 -- Function: A:fixN16b
     Returns an exact non-negative binary fixnum uniform-array
     prototype with at least 16 bits of precision.

 -- Function: A:fixN8b k
 -- Function: A:fixN8b
     Returns an exact non-negative binary fixnum uniform-array
     prototype with at least 8 bits of precision.

 -- Function: A:bool bool
 -- Function: A:bool
     Returns a boolean uniform-array prototype.


File: slib.info,  Node: Subarrays,  Next: Array Mapping,  Prev: Arrays,  Up: Data Structures

7.1.2 Subarrays
---------------

`(require 'subarray)' 

 -- Function: subarray array select ...
     selects a subset of an array.  For ARRAY of rank n, there must be
     at least n SELECTS arguments.  For 0 <= j < n, SELECTSj is either
     an integer, a list of two integers within the range for the jth
     index, or #f.

     When SELECTSj is a list of two integers, then the jth index is
     restricted to that subrange in the returned array.

     When SELECTSj is #f, then the full range of the jth index is
     accessible in the returned array.  An elided argument is
     equivalent to #f.

     When SELECTSj is an integer, then the rank of the returned array is
     less than ARRAY, and only elements whose jth index equals SELECTSj
     are shared.

          > (define ra '#2A((a b c) (d e f)))
          #<unspecified>
          > (subarray ra 0 #f)
          #1A(a b c)
          > (subarray ra 1 #f)
          #1A(d e f)
          > (subarray ra #f 1)
          #1A(b e)
          > (subarray ra '(0 1) #f)
          #2A((a b c) (d e f))
          > (subarray ra #f '(0 1))
          #2A((a b) (d e))
          > (subarray ra #f '(1 2))
          #2A((b c) (e f))
          > (subarray ra #f '(2 1))
          #2A((c b) (f e))

     Arrays can be reflected (reversed) using `subarray':

          > (subarray '#1A(a b c d e) '(4 0))
          #1A(e d c b a)

 -- Function: array-trim array trim ...
     Returns a subarray sharing contents with ARRAY except for slices
     removed from either side of each dimension.  Each of the TRIMS is
     an exact integer indicating how much to trim.  A positive S trims
     the data from the lower end and reduces the upper bound of the
     result; a negative S trims from the upper end and increases the
     lower bound.

     For example:
          (array-trim '#(0 1 2 3 4) 1)  => #1A(1 2 3 4)
          (array-trim '#(0 1 2 3 4) -1) => #1A(0 1 2 3)

          (require 'array-for-each)
          (define (centered-difference ra)
            (array-map ra - (array-trim ra 1) (array-trim ra -1)))

          (centered-difference '#(0 1 3 5 9 22))
            => #(1 2 2 4 13)


File: slib.info,  Node: Array Mapping,  Next: Array Interpolation,  Prev: Subarrays,  Up: Data Structures

7.1.3 Array Mapping
-------------------

`(require 'array-for-each)' 

 -- Procedure: array-map! array0 proc array1 ...
     ARRAY1, ... must have the same number of dimensions as ARRAY0 and
     have a range for each index which includes the range for the
     corresponding index in ARRAY0.  PROC is applied to each tuple of
     elements of ARRAY1 ... and the result is stored as the
     corresponding element in ARRAY0.  The value returned is
     unspecified.  The order of application is unspecified.

 -- Function: array-map prototype proc array1 array2 ...
     ARRAY2, ... must have the same number of dimensions as ARRAY1 and
     have a range for each index which includes the range for the
     corresponding index in ARRAY1.  PROC is applied to each tuple of
     elements of ARRAY1, ARRAY2, ... and the result is stored as the
     corresponding element in a new array of type PROTOTYPE.  The new
     array is returned.  The order of application is unspecified.

 -- Function: array-for-each proc array0 ...
     PROC is applied to each tuple of elements of ARRAY0 ...  in
     row-major order.  The value returned is unspecified.

 -- Function: array-indexes array
     Returns an array of lists of indexes for ARRAY such that, if LI is
     a list of indexes for which ARRAY is defined, (equal?  LI (apply
     array-ref (array-indexes ARRAY) LI)).

 -- Function: array-index-for-each array proc
     applies PROC to the indices of each element of ARRAY in turn.  The
     value returned and the order of application are unspecified.

     One can implement ARRAY-INDEX-MAP! as
          (define (array-index-map! ra fun)
            (array-index-for-each
             ra
             (lambda is (apply array-set! ra (apply fun is) is))))

 -- Procedure: array-index-map! array proc
     applies PROC to the indices of each element of ARRAY in turn,
     storing the result in the corresponding element.  The value
     returned and the order of application are unspecified.

     One can implement ARRAY-INDEXES as
          (define (array-indexes array)
              (let ((ra (apply make-array '#() (array-dimensions array))))
                (array-index-map! ra (lambda x x))
                ra))
     Another example:
          (define (apl:index-generator n)
              (let ((v (make-vector n 1)))
                (array-index-map! v (lambda (i) i))
                v))

 -- Procedure: array:copy! destination source
     Copies every element from vector or array SOURCE to the
     corresponding element of DESTINATION.  DESTINATION must have the
     same rank as SOURCE, and be at least as large in each dimension.
     The order of copying is unspecified.


File: slib.info,  Node: Array Interpolation,  Next: Association Lists,  Prev: Array Mapping,  Up: Data Structures

7.1.4 Array Interpolation
-------------------------

`(require 'array-interpolate)'

 -- Function: interpolate-array-ref ra x1 ... xj
     RA must be an array of rank j containing numbers.
     `interpolate-array-ref' returns a value interpolated from the
     nearest j-dimensional cube of elements of RA.

          (interpolate-array-ref '#2A:fixZ32b((1 2 3) (4 5 6)) 1 0.1)
                                        ==> 4.1
          (interpolate-array-ref '#2A:fixZ32b((1 2 3) (4 5 6)) 0.5 0.25)
                                        ==> 2.75

 -- Procedure: resample-array! ra1 ra2
     RA1 and RA2 must be numeric arrays of equal rank.
     `resample-array!' sets RA1 to values interpolated from RA2 such
     that the values of elements at the corners of RA1 and RA2 are
     equal.

          (define ra (make-array (A:fixZ32b) 2 2))
          (resample-array! ra '#2A:fixZ32b((1 2 3) (4 5 6)))
          ra              ==>  #2A:fixZ32b((1 3) (4 6))
          (define ra (make-array (A:floR64b) 3 2))
          (resample-array! ra '#2A:fixZ32b((1 2 3) (4 5 6)))
          ra              ==>  #2A:floR64b((1.0 3.0) (2.5 4.5) (4.0 6.0))


File: slib.info,  Node: Association Lists,  Next: Byte,  Prev: Array Interpolation,  Up: Data Structures

7.1.5 Association Lists
-----------------------

`(require 'alist)' 

  Alist functions provide utilities for treating a list of key-value
pairs as an associative database.  These functions take an equality
predicate, PRED, as an argument.  This predicate should be repeatable,
symmetric, and transitive.

  Alist functions can be used with a secondary index method such as hash
tables for improved performance.

 -- Function: predicate->asso pred
     Returns an "association function" (like `assq', `assv', or `assoc')
     corresponding to PRED.  The returned function returns a key-value
     pair whose key is `pred'-equal to its first argument or `#f' if no
     key in the alist is PRED-equal to the first argument.

 -- Function: alist-inquirer pred
     Returns a procedure of 2 arguments, ALIST and KEY, which returns
     the value associated with KEY in ALIST or `#f' if KEY does not
     appear in ALIST.

 -- Function: alist-associator pred
     Returns a procedure of 3 arguments, ALIST, KEY, and VALUE, which
     returns an alist with KEY and VALUE associated.  Any previous
     value associated with KEY will be lost.  This returned procedure
     may or may not have side effects on its ALIST argument.  An
     example of correct usage is:

          (define put (alist-associator string-ci=?))
          (define alist '())
          (set! alist (put alist "Foo" 9))

 -- Function: alist-remover pred
     Returns a procedure of 2 arguments, ALIST and KEY, which returns
     an alist with an association whose KEY is key removed.  This
     returned procedure may or may not have side effects on its ALIST
     argument.  An example of correct usage is:

          (define rem (alist-remover string-ci=?))
          (set! alist (rem alist "foo"))

 -- Function: alist-map proc alist
     Returns a new association list formed by mapping PROC over the
     keys and values of ALIST.   PROC must be a function of 2 arguments
     which returns the new value part.

 -- Function: alist-for-each proc alist
     Applies PROC to each pair of keys and values of ALIST.  PROC must
     be a function of 2 arguments.  The returned value is unspecified.


File: slib.info,  Node: Byte,  Next: Byte/Number Conversions,  Prev: Association Lists,  Up: Data Structures

7.1.6 Byte
----------

`(require 'byte)' 

Some algorithms are expressed in terms of arrays of small integers.
Using Scheme strings to implement these arrays is not portable vis-a-vis
the correspondence between integers and characters and non-ascii
character sets.  These functions abstract the notion of a "byte".  

 -- Function: byte-ref bytes k
     K must be a valid index of BYTES.  `byte-ref' returns byte K of
     BYTES using zero-origin indexing.

 -- Procedure: byte-set! bytes k byte
     K must be a valid index of BYTES, and BYTE must be a small
     nonnegative integer.  `byte-set!' stores BYTE in element K of
     BYTES and returns an unspecified value.

 -- Function: make-bytes k byte
 -- Function: make-bytes k
     `make-bytes' returns a newly allocated byte-array of length K.  If
     BYTE is given, then all elements of the byte-array are initialized
     to BYTE, otherwise the contents of the byte-array are unspecified.

 -- Function: bytes-length bytes
     `bytes-length' returns length of byte-array BYTES.

 -- Function: bytes byte ...
     Returns a newly allocated byte-array composed of the small
     nonnegative arguments.
                                                                              |
 -- Function: list->bytes bytes
     `list->bytes' returns a newly allocated byte-array formed from the
     small nonnegative integers in the list BYTES.

 -- Function: bytes->list bytes                                               |
     `bytes->list' returns a newly allocated list of the bytes that           |
     make up the given byte-array.                                            |
                                                                              |
`Bytes->list' and `list->bytes' are inverses so far as `equal?' is
concerned.  

 -- Function: bytes->string bytes                                             |
     Returns a new string formed from applying `integer->char' to each        |
     byte in `bytes->string'.  Note that this may signal an error for         |
     bytes having values between 128 and 255.                                 |
                                                                              |
 -- Function: string->bytes string                                            |
     Returns a new byte-array formed from applying `char->integer' to         |
     each character in `string->bytes'.  Note that this may signal an         |
     error if an integer is larger than 255.                                  |
                                                                              |
 -- Function: bytes-copy bytes
     Returns a newly allocated copy of the given BYTES.

 -- Function: subbytes bytes start end
     BYTES must be a bytes, and START and END must be exact integers
     satisfying

                 0 <= START <= END <= (bytes-length BYTES).

     `subbytes' returns a newly allocated bytes formed from the bytes of
     BYTES beginning with index START (inclusive) and ending with index
     END (exclusive).

 -- Procedure: bytes-reverse! bytes
     Reverses the order of byte-array BYTES.

 -- Function: bytes-reverse bytes
     Returns a newly allocated bytes-array consisting of the elements of
     BYTES in reverse order.

Input and output of bytes should be with ports opened in "binary" mode
(*note Input/Output::).  Calling `open-file' with 'rb or 'wb modes
argument will return a binary port if the Scheme implementation
supports it.

 -- Function: write-byte byte port
 -- Function: write-byte byte
     Writes the byte BYTE (not an external representation of the byte)
     to the given PORT and returns an unspecified value.  The PORT
     argument may be omitted, in which case it defaults to the value
     returned by `current-output-port'.  

 -- Function: read-byte port
 -- Function: read-byte
     Returns the next byte available from the input PORT, updating the
     PORT to point to the following byte.  If no more bytes are
     available, an end-of-file object is returned.  PORT may be
     omitted, in which case it defaults to the value returned by
     `current-input-port'.  

When reading and writing binary numbers with `read-bytes' and
`write-bytes', the sign of the length argument determines the
endianness (order) of bytes.  Positive treats them as big-endian, the
first byte input or output is highest order.  Negative treats them as
little-endian, the first byte input or output is the lowest order.

Once read in, SLIB treats byte sequences as big-endian.  The multi-byte
sequences produced and used by number conversion routines *note
Byte/Number Conversions:: are always big-endian.

 -- Function: read-bytes n port
 -- Function: read-bytes n
     `read-bytes' returns a newly allocated bytes-array filled with
     `(abs N)' bytes read from PORT.  If N is positive, then the first
     byte read is stored at index 0; otherwise the last byte read is
     stored at index 0.  Note that the length of the returned                 |
     byte-array will be less than `(abs N)' if PORT reaches end-of-file.      |

     PORT may be omitted, in which case it defaults to the value
     returned by `current-input-port'.

 -- Function: write-bytes bytes n port
 -- Function: write-bytes bytes n
     `write-bytes' writes `(abs N)' bytes to output-port PORT.  If N is
     positive, then the first byte written is index 0 of BYTES;
     otherwise the last byte written is index 0 of BYTES.
     `write-bytes' returns an unspecified value.

     PORT may be omitted, in which case it defaults to the value
     returned by `current-output-port'.

`subbytes-read!' and `subbytes-write' provide lower-level procedures
for reading and writing blocks of bytes.  The relative size of START
and END determines the order of writing.

 -- Procedure: subbytes-read! bts start end port                              |
 -- Procedure: subbytes-read! bts start end                                   |
     Fills BTS with up to `(abs (- START END))' bytes read from PORT.         |
     The first byte read is stored at index BTS.  `subbytes-read!'            |
     returns the number of bytes read.                                        |

     PORT may be omitted, in which case it defaults to the value
     returned by `current-input-port'.

 -- Function: subbytes-write bts start end port                               |
 -- Function: subbytes-write bts start end                                    |
     `subbytes-write' writes `(abs (- START END))' bytes to output-port
     PORT.  The first byte written is index START of BTS.                     |
     `subbytes-write' returns the number of bytes written.

     PORT may be omitted, in which case it defaults to the value
     returned by `current-output-port'.


File: slib.info,  Node: Byte/Number Conversions,  Next: MAT-File Format,  Prev: Byte,  Up: Data Structures

7.1.7 Byte/Number Conversions
-----------------------------

`(require 'byte-number)' 

The multi-byte sequences produced and used by numeric conversion
routines are always big-endian.  Endianness can be changed during
reading and writing bytes using `read-bytes' and `write-bytes' *Note
read-bytes: Byte.

The sign of the length argument to bytes/integer conversion procedures
determines the signedness of the number.

 -- Function: bytes->integer bytes n
     Converts the first `(abs N)' bytes of big-endian BYTES array to an
     integer.  If N is negative then the integer coded by the bytes are
     treated as two's-complement (can be negative).

          (bytes->integer (bytes   0   0   0  15) -4)   =>          15
          (bytes->integer (bytes   0   0   0  15)  4)   =>          15
          (bytes->integer (bytes 255 255 255 255) -4)   =>          -1
          (bytes->integer (bytes 255 255 255 255)  4)   =>  4294967295
          (bytes->integer (bytes 128   0   0   0) -4)   => -2147483648
          (bytes->integer (bytes 128   0   0   0)  4)   =>  2147483648

 -- Function: integer->bytes n len
     Converts the integer N to a byte-array of `(abs N)' bytes.  If N
     and LEN are both negative, then the bytes in the returned array
     are coded two's-complement.

          (bytes->list (integer->bytes          15 -4))   => (0 0 0 15)
          (bytes->list (integer->bytes          15  4))   => (0 0 0 15)
          (bytes->list (integer->bytes          -1 -4))   => (255 255 255 255)
          (bytes->list (integer->bytes  4294967295  4))   => (255 255 255 255)
          (bytes->list (integer->bytes -2147483648 -4))   => (128 0 0 0)
          (bytes->list (integer->bytes  2147483648  4))   => (128 0 0 0)

 -- Function: bytes->ieee-float bytes
     BYTES must be a 4-element byte-array.  `bytes->ieee-float'
     calculates and returns the value of BYTES interpreted as a
     big-endian IEEE 4-byte (32-bit) number.

     (bytes->ieee-float (bytes    0    0 0 0))  =>  0.0
     (bytes->ieee-float (bytes #x80    0 0 0))  => -0.0
     (bytes->ieee-float (bytes #x40    0 0 0))  =>  2.0
     (bytes->ieee-float (bytes #x40 #xd0 0 0))  =>  6.5
     (bytes->ieee-float (bytes #xc0 #xd0 0 0))  => -6.5

     (bytes->ieee-float (bytes    0 #x80 0 0))  => 11.754943508222875e-39
     (bytes->ieee-float (bytes    0 #x40 0 0))  =>  5.877471754111437e-39
     (bytes->ieee-float (bytes    0    0 0 1))  =>  1.401298464324817e-45

     (bytes->ieee-float (bytes #xff #x80 0 0))  => -inf.0
     (bytes->ieee-float (bytes #x7f #x80 0 0))  => +inf.0
     (bytes->ieee-float (bytes #x7f #x80 0 1))  =>  0/0
     (bytes->ieee-float (bytes #x7f #xc0 0 0))  =>  0/0

 -- Function: bytes->ieee-double bytes
     BYTES must be a 8-element byte-array.  `bytes->ieee-double'
     calculates and returns the value of BYTES interpreted as a
     big-endian IEEE 8-byte (64-bit) number.

     (bytes->ieee-double (bytes    0    0 0 0 0 0 0 0))  =>  0.0
     (bytes->ieee-double (bytes #x80    0 0 0 0 0 0 0))  => -0.0
     (bytes->ieee-double (bytes #x40    0 0 0 0 0 0 0))  =>  2.0
     (bytes->ieee-double (bytes #x40 #x1A 0 0 0 0 0 0))  =>  6.5
     (bytes->ieee-double (bytes #xC0 #x1A 0 0 0 0 0 0))  => -6.5

     (bytes->ieee-double (bytes 0 8 0 0 0 0 0 0)) => 11.125369292536006e-309
     (bytes->ieee-double (bytes 0 4 0 0 0 0 0 0)) =>  5.562684646268003e-309
     (bytes->ieee-double (bytes 0 0 0 0 0 0 0 1)) =>  4.0e-324

     (bytes->ieee-double (bytes #xFF #xF0 0 0 0 0 0 0))  => -inf.0
     (bytes->ieee-double (bytes #x7F #xF0 0 0 0 0 0 0))  => +inf.0
     (bytes->ieee-double (bytes #x7F #xF8 0 0 0 0 0 0))  =>  0/0

 -- Function: ieee-float->bytes x
     Returns a 4-element byte-array encoding the IEEE single-precision
     floating-point of X.

     (bytes->list (ieee-float->bytes  0.0))                    => (0     0 0 0)
     (bytes->list (ieee-float->bytes -0.0))                    => (128   0 0 0)
     (bytes->list (ieee-float->bytes  2.0))                    => (64    0 0 0)
     (bytes->list (ieee-float->bytes  6.5))                    => (64  208 0 0)
     (bytes->list (ieee-float->bytes -6.5))                    => (192 208 0 0)

     (bytes->list (ieee-float->bytes 11.754943508222875e-39))  => (  0 128 0 0)
     (bytes->list (ieee-float->bytes  5.877471754111438e-39))  => (  0  64 0 0)
     (bytes->list (ieee-float->bytes  1.401298464324817e-45))  => (  0   0 0 1)

     (bytes->list (ieee-float->bytes -inf.0))                  => (255 128 0 0)
     (bytes->list (ieee-float->bytes +inf.0))                  => (127 128 0 0)
     (bytes->list (ieee-float->bytes  0/0))                    => (127 192 0 0)

 -- Function: ieee-double->bytes x
     Returns a 8-element byte-array encoding the IEEE double-precision
     floating-point of X.

     (bytes->list (ieee-double->bytes  0.0)) => (0     0 0 0 0 0 0 0)
     (bytes->list (ieee-double->bytes -0.0)) => (128   0 0 0 0 0 0 0)
     (bytes->list (ieee-double->bytes  2.0)) => (64    0 0 0 0 0 0 0)
     (bytes->list (ieee-double->bytes  6.5)) => (64   26 0 0 0 0 0 0)
     (bytes->list (ieee-double->bytes -6.5)) => (192  26 0 0 0 0 0 0)

     (bytes->list (ieee-double->bytes 11.125369292536006e-309))
                                             => (  0   8 0 0 0 0 0 0)
     (bytes->list (ieee-double->bytes  5.562684646268003e-309))
                                             => (  0   4 0 0 0 0 0 0)
     (bytes->list (ieee-double->bytes  4.0e-324))
                                             => (  0   0 0 0 0 0 0 1)

     (bytes->list (ieee-double->bytes -inf.0)) => (255 240 0 0 0 0 0 0)
     (bytes->list (ieee-double->bytes +inf.0)) => (127 240 0 0 0 0 0 0)
     (bytes->list (ieee-double->bytes  0/0)) => (127 248 0 0 0 0 0 0)

Byte Collation Order
....................

The `string<?' ordering of big-endian byte-array representations of
fixed and IEEE floating-point numbers agrees with the numerical
ordering only when those numbers are non-negative.

Straighforward modification of these formats can extend the
byte-collating order to work for their entire ranges.  This agreement
enables the full range of numbers as keys in
"indexed-sequential-access-method" databases.  

 -- Procedure: integer-byte-collate! byte-vector
     Modifies sign bit of BYTE-VECTOR so that `string<?' ordering of
     two's-complement byte-vectors matches numerical order.
     `integer-byte-collate!' returns BYTE-VECTOR and is its own
     functional inverse.

 -- Function: integer-byte-collate byte-vector
     Returns copy of BYTE-VECTOR with sign bit modified so that
     `string<?' ordering of two's-complement byte-vectors matches
     numerical order.  `integer-byte-collate' is its own functional
     inverse.

 -- Procedure: ieee-byte-collate! byte-vector
     Modifies BYTE-VECTOR so that `string<?' ordering of IEEE
     floating-point byte-vectors matches numerical order.
     `ieee-byte-collate!' returns BYTE-VECTOR.

 -- Procedure: ieee-byte-decollate! byte-vector
     Given BYTE-VECTOR modified by `ieee-byte-collate!', reverses the
     BYTE-VECTOR modifications.

 -- Function: ieee-byte-collate byte-vector
     Returns copy of BYTE-VECTOR encoded so that `string<?' ordering of
     IEEE floating-point byte-vectors matches numerical order.

 -- Function: ieee-byte-decollate byte-vector
     Given BYTE-VECTOR returned by `ieee-byte-collate', reverses the
     BYTE-VECTOR modifications.


File: slib.info,  Node: MAT-File Format,  Next: Portable Image Files,  Prev: Byte/Number Conversions,  Up: Data Structures

7.1.8 MAT-File Format
---------------------

`(require 'matfile)' 

`http://www.mathworks.com/access/helpdesk/help/pdf_doc/matlab/matfile_format.pdf'

This package reads MAT-File Format version 4 (MATLAB) binary data
files.  MAT-files written from big-endian or little-endian computers
having IEEE format numbers are currently supported.  Support for files
written from VAX or Cray machines could also be added.

The numeric and text matrix types handled; support for "sparse" matrices
awaits a sample file.

 -- Function: matfile:read filename
     FILENAME should be a string naming an existing file containing a
     MATLAB Version 4 MAT-File.  The `matfile:read' procedure reads
     matrices from the file and returns a list of the results; a list
     of the name string and array for each matrix.

 -- Function: matfile:load filename
     FILENAME should be a string naming an existing file containing a
     MATLAB Version 4 MAT-File.  The `matfile:load' procedure reads
     matrices from the file and defines the `string-ci->symbol' for
     each matrix to its corresponding array.  `matfile:load' returns a
     list of the symbols defined.


File: slib.info,  Node: Portable Image Files,  Next: Collections,  Prev: MAT-File Format,  Up: Data Structures

7.1.9 Portable Image Files
--------------------------

`(require 'pnm)' 

 -- Function: pnm:type-dimensions path
     The string PATH must name a "portable bitmap graphics" file.  `pnm:type-dimensions'
     returns a list of 4 items:
       1. A symbol describing the type of the file named by PATH.

       2. The image width in pixels.

       3. The image height in pixels.

       4. The maximum value of pixels assume in the file.

     The current set of file-type symbols is:
    pbm
    pbm-raw
          Black-and-White image; pixel values are 0 or 1.

    pgm
    pgm-raw
          Gray (monochrome) image; pixel values are from 0 to MAXVAL
          specified in file header.

    ppm
    ppm-raw
          RGB (full color) image; red, green, and blue interleaved
          pixel values are from 0 to MAXVAL

 -- Function: pnm:image-file->array path array
     Reads the "portable bitmap graphics" file named by PATH into ARRAY.
     ARRAY must be the correct size and type for PATH.  ARRAY is
     returned.

 -- Function: pnm:image-file->array path
     `pnm:image-file->array' creates and returns an array with the
     "portable bitmap graphics" file named by PATH read into it.  

 -- Function: pnm:array-write type array maxval path comment ...
     Writes the contents of ARRAY to a TYPE image file named PATH.  The
     file will have pixel values between 0 and MAXVAL, which must be
     compatible with TYPE.  For `pbm' files, MAXVAL must be `1'.
     COMMENTs are included in the file header.


File: slib.info,  Node: Collections,  Next: Dynamic Data Type,  Prev: Portable Image Files,  Up: Data Structures

7.1.10 Collections
------------------

`(require 'collect)' 

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
"elements" indexed by corresponding "keys", although the keys may be
implicit (as with lists).

New types of collections may be defined as YASOS objects (*note
Yasos::).  They must support the following operations:

   * `(collection? SELF)' (always returns `#t');

   * `(size SELF)' returns the number of elements in the collection;

   * `(print SELF PORT)' is a specialized print operation for the
     collection which prints a suitable representation on the given
     PORT or returns it as a string if PORT is `#t';

   * `(gen-elts SELF)' returns a thunk which on successive invocations
     yields elements of SELF in order or gives an error if it is
     invoked more than `(size SELF)' times;

   * `(gen-keys SELF)' is like `gen-elts', but yields the collection's
     keys in order.

They might support specialized `for-each-key' and `for-each-elt'
operations.

 -- Function: collection? obj
     A predicate, true initially of lists, vectors and strings.  New
     sorts of collections must answer `#t' to `collection?'.

 -- Procedure: map-elts proc collection1 ...
 -- Procedure: do-elts proc collection1 ...
     PROC is a procedure taking as many arguments as there are
     COLLECTIONS (at least one).  The COLLECTIONS are iterated over in
     their natural order and 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 COLLECTIONS appear.
     `do-elts' is used when only side-effects of PROC are of interest
     and its return value is unspecified.  `map-elts' returns a
     collection (actually a vector) of the results of the applications
     of PROC.

     Example:
          (map-elts + (list 1 2 3) (vector 1 2 3))
             => #(2 4 6)

 -- Procedure: map-keys proc collection1 ...
 -- Procedure: do-keys proc collection1 ...
     These are analogous to `map-elts' and `do-elts', but each
     iteration is over the COLLECTIONS' _keys_ rather than their
     elements.

     Example:
          (map-keys + (list 1 2 3) (vector 1 2 3))
             => #(0 2 4)

 -- Procedure: for-each-key collection proc
 -- Procedure: for-each-elt collection proc
     These are like `do-keys' and `do-elts' but only for a single
     collection; they are potentially more efficient.

 -- Function: reduce proc seed collection1 ...
     A generalization of the list-based `reduce-init' (*note Lists as
     sequences::) to collections.

     Examples:
          (reduce + 0 (vector 1 2 3))
             => 6
          (reduce union '() '((a b c) (b c d) (d a)))
             => (c b d a).

     `Reduce' called with two arguments will work as does the procedure
     of the same name from *Note Common List Functions::).  

 -- Function: any? pred collection1 ...
     A generalization of the list-based `some' (*note Lists as
     sequences::) to collections.

     Example:
          (any? odd? (list 2 3 4 5))
             => #t

 -- Function: every? pred collection1 ...
     A generalization of the list-based `every' (*note Lists as
     sequences::) to collections.

     Example:
          (every? collection? '((1 2) #(1 2)))
             => #t

 -- Function: empty? collection
     Returns `#t' iff there are no elements in COLLECTION.

     `(empty? COLLECTION) == (zero? (size COLLECTION))'

 -- Function: size collection
     Returns the number of elements in COLLECTION.

 -- Function: Setter list-ref
     See *Note Setters:: for a definition of "setter".  N.B.  `(setter
     list-ref)' doesn't work properly for element 0 of a list.

  Here is a sample collection: `simple-table' which is also a `table'.
     (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)))
                ) ) )
            ))
          ;; 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)
           ) ) ) )


File: slib.info,  Node: Dynamic Data Type,  Next: Hash Tables,  Prev: Collections,  Up: Data Structures

7.1.11 Dynamic Data Type
------------------------

`(require 'dynamic)' 

 -- Function: make-dynamic obj
     Create and returns a new "dynamic" whose global value is OBJ.

 -- Function: dynamic? obj
     Returns true if and only if OBJ is a dynamic.  No object
     satisfying `dynamic?' satisfies any of the other standard type
     predicates.

 -- Function: dynamic-ref dyn
     Return the value of the given dynamic in the current dynamic
     environment.

 -- Procedure: dynamic-set! dyn obj
     Change the value of the given dynamic to OBJ in the current
     dynamic environment.  The returned value is unspecified.

 -- Function: 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 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.

  The `dynamic-bind' macro is not implemented.


File: slib.info,  Node: Hash Tables,  Next: Object,  Prev: Dynamic Data Type,  Up: Data Structures

7.1.12 Hash Tables
------------------

`(require 'hash-table)' 

 -- Function: predicate->hash pred
     Returns a hash function (like `hashq', `hashv', or `hash')
     corresponding to the equality predicate PRED.  PRED should be
     `eq?', `eqv?', `equal?', `=', `char=?', `char-ci=?', `string=?', or
     `string-ci=?'.

A hash table is a vector of association lists.

 -- Function: make-hash-table k
     Returns a vector of K empty (association) lists.

Hash table functions provide utilities for an associative database.
These functions take an equality predicate, PRED, as an argument.  PRED
should be `eq?', `eqv?', `equal?', `=', `char=?', `char-ci=?',
`string=?', or `string-ci=?'.

 -- Function: predicate->hash-asso pred
     Returns a hash association function of 2 arguments, KEY and
     HASHTAB, corresponding to PRED.  The returned function returns a
     key-value pair whose key is PRED-equal to its first argument or
     `#f' if no key in HASHTAB is PRED-equal to the first argument.

 -- Function: hash-inquirer pred
     Returns a procedure of 2 arguments, HASHTAB and KEY, which returns
     the value associated with KEY in HASHTAB or `#f' if KEY does not
     appear in HASHTAB.

 -- Function: hash-associator pred
     Returns a procedure of 3 arguments, HASHTAB, KEY, and VALUE, which
     modifies HASHTAB so that KEY and VALUE associated.  Any previous
     value associated with KEY will be lost.

 -- Function: hash-remover pred
     Returns a procedure of 2 arguments, HASHTAB and KEY, which
     modifies HASHTAB so that the association whose key is KEY is
     removed.

 -- Function: hash-map proc hash-table
     Returns a new hash table formed by mapping PROC over the keys and
     values of HASH-TABLE.  PROC must be a function of 2 arguments
     which returns the new value part.

 -- Function: hash-for-each proc hash-table
     Applies PROC to each pair of keys and values of HASH-TABLE.  PROC
     must be a function of 2 arguments.  The returned value is
     unspecified.

 -- Function: hash-rehasher pred
     `hash-rehasher' accepts a hash table predicate and returns a
     function of two arguments HASHTAB and NEW-K which is specialized
     for that predicate.

     This function is used for nondestrutively resizing a hash table.
     HASHTAB should be an existing hash-table using PRED, NEW-K is the
     size of a new hash table to be returned.  The new hash table will
     have all of the associations of the old hash table.


File: slib.info,  Node: Object,  Next: Priority Queues,  Prev: Hash Tables,  Up: Data Structures

7.1.13 Macroless Object System
------------------------------

`(require 'object)' 

  This is the Macroless Object System written by Wade Humeniuk
(whumeniu@datap.ca).  Conceptual Tributes: *Note Yasos::, MacScheme's
%object, CLOS, Lack of R4RS macros.

7.1.14 Concepts
---------------

OBJECT
     An object is an ordered association-list (by `eq?') of methods
     (procedures).  Methods can be added (`make-method!'), deleted
     (`unmake-method!') and retrieved (`get-method').  Objects may
     inherit methods from other objects.  The object binds to the
     environment it was created in, allowing closures to be used to
     hide private procedures and data.

GENERIC-METHOD
     A generic-method associates (in terms of `eq?') object's method.
     This allows scheme function style to be used for objects.  The
     calling scheme for using a generic method is `(generic-method
     object param1 param2 ...)'.

METHOD
     A method is a procedure that exists in the object.  To use a method
     get-method must be called to look-up the method.  Generic methods
     implement the get-method functionality.  Methods may be added to an
     object associated with any scheme obj in terms of eq?

GENERIC-PREDICATE
     A generic method that returns a boolean value for any scheme obj.

PREDICATE
     A object's method asscociated with a generic-predicate. Returns
     `#t'.

7.1.15 Procedures
-----------------

 -- Function: make-object ancestor ...
     Returns an object.  Current object implementation is a tagged
     vector.  ANCESTORs are optional and must be objects in terms of
     object?.  ANCESTORs methods are included in the object.  Multiple
     ANCESTORs might associate the same generic-method with a method.
     In this case the method of the ANCESTOR first appearing in the
     list is the one returned by `get-method'.

 -- Function: object? obj
     Returns boolean value whether OBJ was created by make-object.

 -- Function: make-generic-method exception-procedure
     Returns a procedure which be associated with an object's methods.
     If EXCEPTION-PROCEDURE is specified then it is used to process
     non-objects.

 -- Function: make-generic-predicate
     Returns a boolean procedure for any scheme object.

 -- Function: make-method! object generic-method method
     Associates METHOD to the GENERIC-METHOD in the object.  The METHOD
     overrides any previous association with the GENERIC-METHOD within
     the object.  Using `unmake-method!' will restore the object's
     previous association with the GENERIC-METHOD.  METHOD must be a
     procedure.

 -- Function: make-predicate! object generic-preciate
     Makes a predicate method associated with the GENERIC-PREDICATE.

 -- Function: unmake-method! object generic-method
     Removes an object's association with a GENERIC-METHOD .

 -- Function: get-method object generic-method
     Returns the object's method associated (if any) with the
     GENERIC-METHOD.  If no associated method exists an error is
     flagged.

7.1.16 Examples
---------------

     (require 'object)
     
     (define instantiate (make-generic-method))

     (define (make-instance-object . ancestors)
       (define self (apply make-object
                           (map (lambda (obj) (instantiate obj)) ancestors)))
       (make-method! self instantiate (lambda (self) self))
       self)

     (define who (make-generic-method))
     (define imigrate! (make-generic-method))
     (define emigrate! (make-generic-method))
     (define describe (make-generic-method))
     (define name (make-generic-method))
     (define address (make-generic-method))
     (define members (make-generic-method))

     (define society
       (let ()
         (define self (make-instance-object))
         (define population '())
         (make-method! self imigrate!
                       (lambda (new-person)
                         (if (not (eq? new-person self))
                             (set! population (cons new-person population)))))
         (make-method! self emigrate!
                       (lambda (person)
                         (if (not (eq? person self))
                             (set! population
                                   (comlist:remove-if (lambda (member)
                                                        (eq? member person))
                                                      population)))))
         (make-method! self describe
                       (lambda (self)
                         (map (lambda (person) (describe person)) population)))
         (make-method! self who
                       (lambda (self) (map (lambda (person) (name person))
                                           population)))
         (make-method! self members (lambda (self) population))
         self))

     (define (make-person %name %address)
       (define self (make-instance-object society))
       (make-method! self name (lambda (self) %name))
       (make-method! self address (lambda (self) %address))
       (make-method! self who (lambda (self) (name self)))
       (make-method! self instantiate
                     (lambda (self)
                       (make-person (string-append (name self) "-son-of")
                                    %address)))
       (make-method! self describe
                     (lambda (self) (list (name self) (address self))))
       (imigrate! self)
       self)

7.1.16.1 Inverter Documentation
...............................

Inheritance:
             <inverter>::(<number> <description>)
  Generic-methods
             <inverter>::value      => <number>::value
             <inverter>::set-value! => <number>::set-value!
             <inverter>::describe   => <description>::describe
             <inverter>::help
             <inverter>::invert
             <inverter>::inverter?

7.1.16.2 Number Documention
...........................

Inheritance
             <number>::()
  Slots
             <number>::<x>
  Generic Methods
             <number>::value
             <number>::set-value!

7.1.16.3 Inverter code
......................

     (require 'object)
     
     (define value (make-generic-method (lambda (val) val)))
     (define set-value! (make-generic-method))
     (define invert (make-generic-method
                     (lambda (val)
                       (if (number? val)
                           (/ 1 val)
                           (error "Method not supported:" val)))))
     (define noop (make-generic-method))
     (define inverter? (make-generic-predicate))
     (define describe (make-generic-method))
     (define help (make-generic-method))

     (define (make-number x)
       (define self (make-object))
       (make-method! self value (lambda (this) x))
       (make-method! self set-value!
                     (lambda (this new-value) (set! x new-value)))
       self)

     (define (make-description str)
       (define self (make-object))
       (make-method! self describe (lambda (this) str))
       (make-method! self help (lambda (this) "Help not available"))
       self)

     (define (make-inverter)
       (let* ((self (make-object
                     (make-number 1)
                     (make-description "A number which can be inverted")))
              (<value> (get-method self value)))
         (make-method! self invert (lambda (self) (/ 1 (<value> self))))
         (make-predicate! self inverter?)
         (unmake-method! self help)
         (make-method! self help
                       (lambda (self)
                         (display "Inverter Methods:") (newline)
                         (display "  (value inverter) ==> n") (newline)))
         self))

     ;;;; Try it out

     (define invert! (make-generic-method))

     (define x (make-inverter))

     (make-method! x invert! (lambda (x) (set-value! x (/ 1 (value x)))))

     (value x)                       => 1
     (set-value! x 33)               => undefined
     (invert! x)                     => undefined
     (value x)                       => 1/33

     (unmake-method! x invert!)      => undefined

     (invert! x)                     error-->  ERROR: Method not supported: x


File: slib.info,  Node: Priority Queues,  Next: Queues,  Prev: Object,  Up: Data Structures

7.1.17 Priority Queues
----------------------

`(require 'priority-queue)' 

This algorithm for priority queues is due to `Introduction to
Algorithms' by T. Cormen, C. Leiserson, R. Rivest.  1989 MIT Press.

 -- Function: make-heap pred<?
     Returns a binary heap suitable which can be used for priority queue
     operations.

 -- Function: heap-length heap
     Returns the number of elements in HEAP.

 -- Procedure: heap-insert! heap item
     Inserts ITEM into HEAP.  ITEM can be inserted multiple times.  The
     value returned is unspecified.

 -- Procedure: heap-extract-max! heap
     Returns the item which is larger than all others according to the
     PRED<? argument to `make-heap'.  If there are no items in HEAP, an
     error is signaled.


File: slib.info,  Node: Queues,  Next: Records,  Prev: Priority Queues,  Up: Data Structures

7.1.18 Queues
-------------

`(require 'queue)' 

  A "queue" is a list where elements can be added to both the front and
rear, and removed from the front (i.e., they are what are often called
"dequeues").  A queue may also be used like a stack.  

 -- Function: make-queue
     Returns a new, empty queue.

 -- Function: queue? obj
     Returns `#t' if OBJ is a queue.

 -- Function: queue-empty? q
     Returns `#t' if the queue Q is empty.

 -- Procedure: queue-push! q datum
     Adds DATUM to the front of queue Q.

 -- Procedure: enqueue! q datum
     Adds DATUM to the rear of queue Q.

 -- Procedure: dequeue! q
 -- Procedure: queue-pop! q
     Both of these procedures remove and return the datum at the front
     of the queue.  `queue-pop!' is used to suggest that the queue is
     being used like a stack.

  All of the following functions raise an error if the queue Q is empty.

 -- Procedure: dequeue-all! q
     Removes and returns (the list) of all contents of queue Q.

 -- Function: queue-front q
     Returns the datum at the front of the queue Q.

 -- Function: queue-rear q
     Returns the datum at the rear of the queue Q.


File: slib.info,  Node: Records,  Prev: Queues,  Up: Data Structures

7.1.19 Records
--------------

`(require 'record)' 

  The Record package provides a facility for user to define their own
record data types.

 -- Function: make-record-type type-name field-names
     Returns a "record-type descriptor", a value representing a new data
     type disjoint from all others.  The 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
     FIELD-NAMES argument is a list of symbols naming the "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.

 -- Function: record-constructor rtd [field-names]
     Returns a procedure for constructing new members of the type
     represented by RTD.  The returned procedure accepts exactly as
     many arguments as there are symbols in the given list,
     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 FIELD-NAMES argument defaults to the list of
     field names in the call to `make-record-type' that created the
     type represented by RTD; if the FIELD-NAMES argument is provided,
     it is an error if it contains any duplicates or any symbols not in
     the default list.

 -- Function: record-predicate rtd
     Returns a procedure for testing membership in the type represented
     by 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.

 -- Function: record-accessor rtd field-name
     Returns a procedure for reading the value of a particular field of
     a member of the type represented by 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 FIELD-NAME in that record.  The symbol FIELD-NAME
     must be a member of the list of field-names in the call to
     `make-record-type' that created the type represented by RTD.

 -- Function: record-modifier rtd field-name
     Returns a procedure for writing the value of a particular field of
     a member of the type represented by 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 FIELD-NAME in that record to contain the given
     value.  The returned value of the modifier procedure is
     unspecified.  The symbol FIELD-NAME must be a member of the list
     of field-names in the call to `make-record-type' that created the
     type represented by RTD.

  In May of 1996, as a product of discussion on the `rrrs-authors'
mailing list, I rewrote `record.scm' to portably implement type
disjointness for record data types.

  As long as an implementation's procedures are opaque and the `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 `record?', `record-type-descriptor',
`record-type-name'.and `record-type-field-names' are no longer
supported.


File: slib.info,  Node: Sorting and Searching,  Next: Procedures,  Prev: Data Structures,  Up: Other Packages

7.2 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


File: slib.info,  Node: Common List Functions,  Next: Tree Operations,  Prev: Sorting and Searching,  Up: Sorting and Searching

7.2.1 Common List Functions
---------------------------

`(require '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::


File: slib.info,  Node: List construction,  Next: Lists as sets,  Prev: Common List Functions,  Up: Common List Functions

7.2.1.1 List construction
.........................

 -- Function: make-list k
 -- Function: make-list k init
     `make-list' creates and returns a list of K elements.  If INIT is
     included, all elements in the list are initialized to INIT.

     Example:
          (make-list 3)
             => (#<unspecified> #<unspecified> #<unspecified>)
          (make-list 5 'foo)
             => (foo foo foo foo foo)

 -- Function: list* obj1 obj2 ...
     Works like `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 `cons*'.  E.g.:

          (list* 1)
             => 1
          (list* 1 2 3)
             => (1 2 . 3)
          (list* 1 2 '(3 4))
             => (1 2 3 4)
          (list* ARGS '())
             == (list ARGS)

 -- Function: copy-list lst
     `copy-list' makes a copy of 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 `eq?' to the corresponding
     elements of the original; the copy is, however, not `eq?' to the
     original, but is `equal?' to it.

     Example:
          (copy-list '(foo foo foo))
             => (foo foo foo)
          (define q '(foo bar baz bang))
          (define p q)
          (eq? p q)
             => #t
          (define r (copy-list q))
          (eq? q r)
             => #f
          (equal? q r)
             => #t
          (define bar '(bar))
          (eq? bar (car (copy-list (list bar 'foo))))
          => #t


File: slib.info,  Node: Lists as sets,  Next: Lists as sequences,  Prev: List construction,  Up: Common List Functions

7.2.1.2 Lists as sets
.....................

`eqv?' is used to test for membership by procedures which treat lists
as sets.

 -- Function: adjoin e l
     `adjoin' returns the adjoint of the element E and the list L.
     That is, if E is in L, `adjoin' returns L, otherwise, it returns
     `(cons E L)'.

     Example:
          (adjoin 'baz '(bar baz bang))
             => (bar baz bang)
          (adjoin 'foo '(bar baz bang))
             => (foo bar baz bang)

 -- Function: union l1 l2
     `union' returns a list of all elements that are in L1 or L2.
     Duplicates between L1 and L2 are culled.  Duplicates within L1 or
     within L2 may or may not be removed.

     Example:
          (union '(1 2 3 4) '(5 6 7 8))
             => (1 2 3 4 5 6 7 8)
          (union '(0 1 2 3 4) '(3 4 5 6))
             => (5 6 0 1 2 3 4)

 -- Function: intersection l1 l2
     `intersection' returns a list of all elements that are in both L1
     and L2.

     Example:
          (intersection '(1 2 3 4) '(3 4 5 6))
             => (3 4)
          (intersection '(1 2 3 4) '(5 6 7 8))
             => ()

 -- Function: set-difference l1 l2
     `set-difference' returns a list of all elements that are in L1 but
     not in L2.

     Example:
          (set-difference '(1 2 3 4) '(3 4 5 6))
             => (1 2)
          (set-difference '(1 2 3 4) '(1 2 3 4 5 6))
             => ()

 -- Function: subset? list1 list2
     Returns `#t' if every element of LIST1 is `eqv?' an element of
     LIST2; otherwise returns `#f'.

     Example:
          (subset? '(1 2 3 4) '(3 4 5 6))
             => #f
          (subset? '(1 2 3 4) '(6 5 4 3 2 1 0))
             => #t

 -- Function: member-if pred lst
     `member-if' returns the list headed by the first element of LST to
     satisfy `(PRED ELEMENT)'.  `Member-if' returns `#f' if PRED
     returns `#f' for every ELEMENT in LST.

     Example:
          (member-if vector? '(a 2 b 4))
             => #f
          (member-if number? '(a 2 b 4))
             => (2 b 4)

 -- Function: some pred lst1 lst2 ...
     PRED is a boolean function of as many arguments as there are list
     arguments to `some' i.e., LST plus any optional arguments.  PRED
     is applied to successive elements of the list arguments in order.
     `some' returns `#t' as soon as one of these applications returns
     `#t', and is `#f' if none returns `#t'.  All the lists should have
     the same length.

     Example:
          (some odd? '(1 2 3 4))
             => #t

          (some odd? '(2 4 6 8))
             => #f

          (some > '(1 3) '(2 4))
             => #f

 -- Function: every pred lst1 lst2 ...
     `every' is analogous to `some' except it returns `#t' if every
     application of PRED is `#t' and `#f' otherwise.

     Example:
          (every even? '(1 2 3 4))
             => #f

          (every even? '(2 4 6 8))
             => #t

          (every > '(2 3) '(1 4))
             => #f

 -- Function: notany pred lst1 ...
     `notany' is analogous to `some' but returns `#t' if no application
     of PRED returns `#t' or `#f' as soon as any one does.

 -- Function: notevery pred lst1 ...
     `notevery' is analogous to `some' but returns `#t' as soon as an
     application of PRED returns `#f', and `#f' otherwise.

     Example:
          (notevery even? '(1 2 3 4))
             => #t

          (notevery even? '(2 4 6 8))
             => #f

 -- Function: list-of?? predicate
     Returns a predicate which returns true if its argument is a list
     every element of which satisfies PREDICATE.

 -- Function: list-of?? predicate low-bound high-bound
     LOW-BOUND and HIGH-BOUND are non-negative integers.  `list-of??'
     returns a predicate which returns true if its argument is a list
     of length between LOW-BOUND and HIGH-BOUND (inclusive); every
     element of which satisfies PREDICATE.

 -- Function: list-of?? predicate bound
     BOUND is an integer.  If BOUND is negative, `list-of??' returns a
     predicate which returns true if its argument is a list of length
     greater than `(- BOUND)'; every element of which satisfies
     PREDICATE.  Otherwise, `list-of??'  returns a predicate which
     returns true if its argument is a list of length less than or
     equal to BOUND; every element of which satisfies PREDICATE.

 -- Function: find-if pred lst
     `find-if' searches for the first ELEMENT in LST such that `(PRED
     ELEMENT)' returns `#t'.  If it finds any such ELEMENT in LST,
     ELEMENT is returned.  Otherwise, `#f' is returned.

     Example:
          (find-if number? '(foo 1 bar 2))
             => 1

          (find-if number? '(foo bar baz bang))
             => #f

          (find-if symbol? '(1 2 foo bar))
             => foo

 -- Function: remove elt lst
     `remove' removes all occurrences of ELT from LST using `eqv?' to
     test for equality and returns everything that's left.  N.B.: other
     implementations (Chez, Scheme->C and T, at least) use `equal?' as
     the equality test.

     Example:
          (remove 1 '(1 2 1 3 1 4 1 5))
             => (2 3 4 5)

          (remove 'foo '(bar baz bang))
             => (bar baz bang)

 -- Function: remove-if pred lst
     `remove-if' removes all ELEMENTs from LST where `(PRED ELEMENT)'
     is `#t' and returns everything that's left.

     Example:
          (remove-if number? '(1 2 3 4))
             => ()

          (remove-if even? '(1 2 3 4 5 6 7 8))
             => (1 3 5 7)

 -- Function: remove-if-not pred lst
     `remove-if-not' removes all ELEMENTs from LST for which `(PRED
     ELEMENT)' is `#f' and returns everything that's left.

     Example:
          (remove-if-not number? '(foo bar baz))
             => ()
          (remove-if-not odd? '(1 2 3 4 5 6 7 8))
             => (1 3 5 7)

 -- Function: has-duplicates? lst
     returns `#t' if 2 members of LST are `equal?', `#f' otherwise.

     Example:
          (has-duplicates? '(1 2 3 4))
             => #f

          (has-duplicates? '(2 4 3 4))
             => #t

  The procedure `remove-duplicates' uses `member' (rather than `memv').

 -- Function: remove-duplicates lst
     returns a copy of LST with its duplicate members removed.
     Elements are considered duplicate if they are `equal?'.

     Example:
          (remove-duplicates '(1 2 3 4))
             => (1 2 3 4)

          (remove-duplicates '(2 4 3 4))
             => (2 4 3)


File: slib.info,  Node: Lists as sequences,  Next: Destructive list operations,  Prev: Lists as sets,  Up: Common List Functions

7.2.1.3 Lists as sequences
..........................

 -- Function: position obj lst
     `position' returns the 0-based position of OBJ in LST, or `#f' if
     OBJ does not occur in LST.

     Example:
          (position 'foo '(foo bar baz bang))
             => 0
          (position 'baz '(foo bar baz bang))
             => 2
          (position 'oops '(foo bar baz bang))
             => #f

 -- Function: reduce p lst
     `reduce' combines all the elements of a sequence using a binary
     operation (the combination is left-associative).  For example,
     using `+', one can add up all the elements.  `reduce' allows you to
     apply a function which accepts only two arguments to more than 2
     objects.  Functional programmers usually refer to this as "foldl".
     `collect:reduce' (*note Collections::) provides a version of
     `collect' generalized to collections.

     Example:
          (reduce + '(1 2 3 4))
             => 10
          (define (bad-sum . l) (reduce + l))
          (bad-sum 1 2 3 4)
             == (reduce + (1 2 3 4))
             == (+ (+ (+ 1 2) 3) 4)
          => 10
          (bad-sum)
             == (reduce + ())
             => ()
          (reduce string-append '("hello" "cruel" "world"))
             == (string-append (string-append "hello" "cruel") "world")
             => "hellocruelworld"
          (reduce anything '())
             => ()
          (reduce anything '(x))
             => x

     What follows is a rather non-standard implementation of `reverse'
     in terms of `reduce' and a combinator elsewhere called "C".

          ;;; 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)))

 -- Function: reduce-init p init lst
     `reduce-init' is the same as reduce, except that it implicitly
     inserts INIT at the start of the list.  `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 "foldl".

     Example:
          (define (sum . l) (reduce-init + 0 l))
          (sum 1 2 3 4)
             == (reduce-init + 0 (1 2 3 4))
             == (+ (+ (+ (+ 0 1) 2) 3) 4)
             => 10
          (sum)
             == (reduce-init + 0 '())
             => 0

          (reduce-init string-append "@" '("hello" "cruel" "world"))
          ==
          (string-append (string-append (string-append "@" "hello")
                                         "cruel")
                         "world")
          => "@hellocruelworld"

     Given a differentiation of 2 arguments, `diff', the following will
     differentiate by any number of variables.
          (define (diff* exp . vars)
            (reduce-init diff exp vars))

     Example:
          ;;; 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)
             == (reduce-init insert () (3 1 4 1 5))
             == (insert (insert (insert (insert (insert () 3) 1) 4) 1) 5)
             == (insert (insert (insert (insert (3)) 1) 4) 1) 5)
             == (insert (insert (insert (1 3) 4) 1) 5)
             == (insert (insert (1 3 4) 1) 5)
             == (insert (1 1 3 4) 5)
             => (1 1 3 4 5)

 -- Function: last lst n
     `last' returns the last N elements of LST.  N must be a
     non-negative integer.

     Example:
          (last '(foo bar baz bang) 2)
             => (baz bang)
          (last '(1 2 3) 0)
             => 0

 -- Function: butlast lst n
     `butlast' returns all but the last N elements of LST.

     Example:
          (butlast '(a b c d) 3)
             => (a)
          (butlast '(a b c d) 4)
             => ()

`last' and `butlast' split a list into two parts when given identical
arguments.
     (last '(a b c d e) 2)
        => (d e)
     (butlast '(a b c d e) 2)
        => (a b c)

 -- Function: nthcdr n lst
     `nthcdr' takes N `cdr's of LST and returns the result.  Thus
     `(nthcdr 3 LST)' == `(cdddr LST)'

     Example:
          (nthcdr 2 '(a b c d))
             => (c d)
          (nthcdr 0 '(a b c d))
             => (a b c d)

 -- Function: butnthcdr n lst
     `butnthcdr' returns all but the nthcdr N elements of LST.

     Example:
          (butnthcdr 3 '(a b c d))
             => (a b c)
          (butnthcdr 4 '(a b c d))
             => (a b c d)

`nthcdr' and `butnthcdr' split a list into two parts when given
identical arguments.
     (nthcdr 2 '(a b c d e))
        => (c d e)
     (butnthcdr 2 '(a b c d e))
        => (a b)


File: slib.info,  Node: Destructive list operations,  Next: Non-List functions,  Prev: Lists as sequences,  Up: Common List Functions

7.2.1.4 Destructive list operations
...................................

These procedures may mutate the list they operate on, but any such
mutation is undefined.

 -- Procedure: nconc args
     `nconc' destructively concatenates its arguments.  (Compare this
     with `append', which copies arguments rather than destroying them.)
     Sometimes called `append!' (*note Rev2 Procedures::).

     Example:  You want to find the subsets of a set.  Here's the
     obvious way:

          (define (subsets set)
            (if (null? set)
                '(())
                (append (map (lambda (sub) (cons (car set) sub))
                             (subsets (cdr set)))
                        (subsets (cdr set)))))
     But that does way more consing than you need.  Instead, you could
     replace the `append' with `nconc', since you don't have any need
     for all the intermediate results.

     Example:
          (define x '(a b c))
          (define y '(d e f))
          (nconc x y)
             => (a b c d e f)
          x
             => (a b c d e f)

     `nconc' is the same as `append!' in `sc2.scm'.

 -- Procedure: nreverse lst
     `nreverse' reverses the order of elements in LST by mutating
     `cdr's of the list.  Sometimes called `reverse!'.

     Example:
          (define foo '(a b c))
          (nreverse foo)
             => (c b a)
          foo
             => (a)

     Some people have been confused about how to use `nreverse',
     thinking that it doesn't return a value.  It needs to be pointed
     out that

          (set! lst (nreverse lst))
     is the proper usage, not
          (nreverse lst)
     The example should suffice to show why this is the case.

 -- Procedure: delete elt lst
 -- Procedure: delete-if pred lst
 -- Procedure: delete-if-not pred lst
     Destructive versions of `remove' `remove-if', and `remove-if-not'.

     Example:
          (define lst (list 'foo 'bar 'baz 'bang))
          (delete 'foo lst)
             => (bar baz bang)
          lst
             => (foo bar baz bang)

          (define lst (list 1 2 3 4 5 6 7 8 9))
          (delete-if odd? lst)
             => (2 4 6 8)
          lst
             => (1 2 4 6 8)

     Some people have been confused about how to use `delete',
     `delete-if', and `delete-if', thinking that they don't return a
     value.  It needs to be pointed out that

          (set! lst (delete el lst))
     is the proper usage, not
          (delete el lst)
     The examples should suffice to show why this is the case.


File: slib.info,  Node: Non-List functions,  Prev: Destructive list operations,  Up: Common List Functions

7.2.1.5 Non-List functions
..........................

 -- Function: and? arg1 ...
     `and?' checks to see if all its arguments are true.  If they are,
     `and?' returns `#t', otherwise, `#f'.  (In contrast to `and', this
     is a function, so all arguments are always evaluated and in an
     unspecified order.)

     Example:
          (and? 1 2 3)
             => #t
          (and #f 1 2)
             => #f

 -- Function: or? arg1 ...
     `or?' checks to see if any of its arguments are true.  If any is
     true, `or?' returns `#t', and `#f' otherwise.  (To `or' as `and?'
     is to `and'.)

     Example:
          (or? 1 2 #f)
             => #t
          (or? #f #f #f)
             => #f

 -- Function: atom? object
     Returns `#t' if OBJECT is not a pair and `#f' if it is pair.
     (Called `atom' in Common LISP.)
          (atom? 1)
             => #t
          (atom? '(1 2))
             => #f
          (atom? #(1 2))   ; dubious!
             => #t


File: slib.info,  Node: Tree Operations,  Next: Chapter Ordering,  Prev: Common List Functions,  Up: Sorting and Searching

7.2.2 Tree operations
---------------------

`(require 'tree)' 

  These are operations that treat lists a representations of trees.

 -- Function: subst new old tree
 -- Function: substq new old tree
 -- Function: substv new old tree
 -- Function: subst new old tree equ?
     `subst' makes a copy of TREE, substituting NEW for every subtree
     or leaf of TREE which is `equal?' to OLD and returns a modified
     tree.  The original TREE is unchanged, but may share parts with
     the result.

     `substq' and `substv' are similar, but test against OLD using
     `eq?' and `eqv?' respectively.  If `subst' is called with a fourth
     argument, EQU? is the equality predicate.

     Examples:
          (substq 'tempest 'hurricane '(shakespeare wrote (the hurricane)))
             => (shakespeare wrote (the tempest))
          (substq 'foo '() '(shakespeare wrote (twelfth night)))
             => (shakespeare wrote (twelfth night . foo) . foo)
          (subst '(a . cons) '(old . pair)
                 '((old . spice) ((old . shoes) old . pair) (old . pair)))
             => ((old . spice) ((old . shoes) a . cons) (a . cons))

 -- Function: copy-tree tree
     Makes a copy of the nested list structure TREE using new pairs and
     returns it.  All levels are copied, so that none of the pairs in
     the tree are `eq?' to the original ones - only the leaves are.

     Example:
          (define bar '(bar))
          (copy-tree (list bar 'foo))
             => ((bar) foo)
          (eq? bar (car (copy-tree (list bar 'foo))))
             => #f


File: slib.info,  Node: Chapter Ordering,  Next: Sorting,  Prev: Tree Operations,  Up: Sorting and Searching

7.2.3 Chapter Ordering
----------------------

`(require 'chapter-order)' 

  The `chap:' functions deal with strings which are ordered like
chapter numbers (or letters) in a book.  Each section of the string
consists of consecutive numeric or consecutive aphabetic characters of
like case.

 -- Function: chap:string<? string1 string2
     Returns #t if the first non-matching run of alphabetic upper-case
     or the first non-matching run of alphabetic lower-case or the first
     non-matching run of numeric characters of STRING1 is `string<?'
     than the corresponding non-matching run of characters of STRING2.

          (chap:string<? "a.9" "a.10")                    => #t
          (chap:string<? "4c" "4aa")                      => #t
          (chap:string<? "Revised^{3.99}" "Revised^{4}")  => #t

 -- Function: chap:string>? string1 string2
 -- Function: chap:string<=? string1 string2
 -- Function: chap:string>=? string1 string2
     Implement the corresponding chapter-order predicates.

 -- Function: chap:next-string string
     Returns the next string in the _chapter order_.  If STRING has no
     alphabetic or numeric characters, `(string-append STRING "0")' is
     returnd.  The argument to chap:next-string will always be
     `chap:string<?' than the result.

          (chap:next-string "a.9")                => "a.10"
          (chap:next-string "4c")                 => "4d"
          (chap:next-string "4z")                 => "4aa"
          (chap:next-string "Revised^{4}")        => "Revised^{5}"


File: slib.info,  Node: Sorting,  Next: Topological Sort,  Prev: Chapter Ordering,  Up: Sorting and Searching

7.2.4 Sorting
-------------

`(require 'sort)' or `(require 'srfi-95)' 

  [by Richard A. O'Keefe, 1991]

  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).

  The code of `merge' and `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 `null?' test per iteration.)

  I gave serious consideration to producing Common-LISP-compatible
functions.  However, Common LISP's `sort' is our `sort!' (well, in fact
Common LISP's `stable-sort' is our `sort!'; merge sort is _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 _order_ of the
arguments.

  The standard functions `<', `>', `char<?', `char>?', `char-ci<?',
`char-ci>?', `string<?', `string>?', `string-ci<?', and `string-ci>?'
are suitable for use as comparison functions.  Think of `(less? x y)'
as saying when `x' must _not_ precede `y'.

  [Addendum by Aubrey Jaffer, 2006]

  These procedures are stable when called with predicates which return
`#f' when applied to identical arguments.

  The `sorted?', `merge', and `merge!' procedures consume asymptotic
time and space no larger than O(N), where N is the sum of the lengths
of the sequence arguments.  The `sort' and `sort!' procedures consume
asymptotic time and space no larger than O(N*log(N)), where N is the
length of the sequence argument.

  All five functions take an optional KEY argument corresponding to a
CL-style `&key' argument.  A LESS?  predicate with a KEY argument
behaves like:

     (lambda (x y) (LESS? (KEY x) (KEY y)))

  All five functions will call the KEY argument at most once per
element.

  The `!' variants sort in place; `sort!' returns its SEQUENCE argument.

 -- Function: sorted? sequence less?
 -- Function: sorted? sequence less? key
     Returns `#t' when the sequence argument is in non-decreasing order
     according to LESS? (that is, there is no adjacent pair `... x y
     ...' for which `(less? y x)').

     Returns `#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).

 -- Function: merge list1 list2 less?
 -- Function: merge list1 list2 less? key
     Merges two sorted lists, returning a freshly allocated list as its
     result.

 -- Function: merge! list1 list2 less?
 -- Function: merge! list1 list2 less? key
     Merges two sorted lists, re-using the pairs of LIST1 and LIST2 to
     build the result.  The result will be either LIST1 or LIST2.

 -- Function: sort sequence less?
 -- Function: sort sequence less? key
     Accepts a list or array (including vectors and strings) for
     SEQUENCE; and returns a completely new sequence which is sorted
     according to LESS?.  The returned sequence is the same type as the
     argument SEQUENCE.  Given valid arguments, it is always the case
     that:

          (sorted? (sort SEQUENCE LESS?) LESS?) => #t

 -- Function: sort! sequence less?
 -- Function: sort! sequence less? key
     Returns list, array, vector, or string SEQUENCE which has been
     mutated to order its elements according to LESS?.  Given valid
     arguments, it is always the case that:

          (sorted? (sort! SEQUENCE LESS?) LESS?) => #t


File: slib.info,  Node: Topological Sort,  Next: Hashing,  Prev: Sorting,  Up: Sorting and Searching

7.2.5 Topological Sort
----------------------

`(require 'topological-sort)' or `(require 'tsort)' 

The algorithm is inspired by Cormen, Leiserson and Rivest (1990)
`Introduction to Algorithms', chapter 23.

 -- Function: tsort dag pred
 -- Function: topological-sort dag pred
     where
    DAG
          is a list of sublists.  The car of each sublist is a vertex.
          The cdr is the adjacency list of that vertex, i.e. a list of
          all vertices to which there exists an edge from the car
          vertex.

    PRED
          is one of `eq?', `eqv?', `equal?', `=', `char=?',
          `char-ci=?', `string=?', or `string-ci=?'.

     Sort the directed acyclic graph DAG so that for every edge from
     vertex U to V, U will come before V in the resulting list of
     vertices.

     Time complexity: O (|V| + |E|)

     Example (from Cormen):

          Prof. Bumstead topologically sorts his clothing when getting
          dressed.  The first argument to `tsort' describes which
          garments he needs to put on before others.  (For example,
          Prof Bumstead needs to put on his shirt before he puts on his
          tie or his belt.)  `tsort' gives the correct order of
          dressing:

          (require 'tsort)
          (tsort '((shirt tie belt)
                   (tie jacket)
                   (belt jacket)
                   (watch)
                   (pants shoes belt)
                   (undershorts pants shoes)
                   (socks shoes))
                 eq?)
          =>
          (socks undershorts pants shoes watch shirt belt tie jacket)


File: slib.info,  Node: Hashing,  Next: Space-Filling Curves,  Prev: Topological Sort,  Up: Sorting and Searching

7.2.6 Hashing
-------------

`(require 'hash)' 

  These hashing functions are for use in quickly classifying objects.
Hash tables use these functions.

 -- Function: hashq obj k
 -- Function: hashv obj k
 -- Function: hash obj k
     Returns an exact non-negative integer less than K.  For each
     non-negative integer less than K there are arguments OBJ for which
     the hashing functions applied to OBJ and K returns that integer.

     For `hashq', `(eq? obj1 obj2)' implies `(= (hashq obj1 k) (hashq
     obj2))'.

     For `hashv', `(eqv? obj1 obj2)' implies `(= (hashv obj1 k) (hashv
     obj2))'.

     For `hash', `(equal? obj1 obj2)' implies `(= (hash obj1 k) (hash
     obj2))'.

     `hash', `hashv', and `hashq' return in time bounded by a constant.
     Notice that items having the same `hash' implies the items have
     the same `hashv' implies the items have the same `hashq'.


File: slib.info,  Node: Space-Filling Curves,  Next: Soundex,  Prev: Hashing,  Up: Sorting and Searching

7.2.7 Space-Filling Curves
--------------------------

* Menu:

* Hilbert Space-Filling Curve::  Non-negative coordinates
* Peano Space-Filling Curve::   Integer coordinates
* Sierpinski Curve::


File: slib.info,  Node: Hilbert Space-Filling Curve,  Next: Peano Space-Filling Curve,  Prev: Space-Filling Curves,  Up: Space-Filling Curves

7.2.7.1 Hilbert Space-Filling Curve
...................................

`(require 'hilbert-fill)' 

The "Hilbert Space-Filling Curve" is a one-to-one mapping between a
unit line segment and an N-dimensional unit cube.  This implementation
treats the nonnegative integers either as fractional bits of a given
width or as nonnegative integers.

The integer procedures map the non-negative integers to an arbitrarily
large N-dimensional cube with its corner at the origin and all
coordinates are non-negative.

For any exact nonnegative integer SCALAR and exact integer RANK > 2,

     (= SCALAR (hilbert-coordinates->integer
                (integer->hilbert-coordinates SCALAR RANK)))
                                            => #t

  When treating integers as K fractional bits,

     (= SCALAR (hilbert-coordinates->integer
                (integer->hilbert-coordinates SCALAR RANK K)) K)
                                            => #t

 -- Function: integer->hilbert-coordinates scalar rank
     Returns a list of RANK integer coordinates corresponding to exact
     non-negative integer SCALAR.  The lists returned by
     `integer->hilbert-coordinates' for SCALAR arguments 0 and 1 will
     differ in the first element.

 -- Function: integer->hilbert-coordinates scalar rank k
     SCALAR must be a nonnegative integer of no more than `RANK*K' bits.

     `integer->hilbert-coordinates' Returns a list of RANK K-bit
     nonnegative integer coordinates corresponding to exact
     non-negative integer SCALAR.  The curves generated by
     `integer->hilbert-coordinates' have the same alignment independent
     of K.

 -- Function: hilbert-coordinates->integer coords
 -- Function: hilbert-coordinates->integer coords k
     Returns an exact non-negative integer corresponding to COORDS, a
     list of non-negative integer coordinates.

7.2.7.2 Gray code
.................

A "Gray code" is an ordering of non-negative integers in which exactly
one bit differs between each pair of successive elements.  There are
multiple Gray codings.  An n-bit Gray code corresponds to a Hamiltonian
cycle on an n-dimensional hypercube.

Gray codes find use communicating incrementally changing values between
asynchronous agents.  De-laminated Gray codes comprise the coordinates
of Hilbert space-filling curves.

 -- Function: integer->gray-code k
     Converts K to a Gray code of the same `integer-length' as K.

 -- Function: gray-code->integer k
     Converts the Gray code K to an integer of the same
     `integer-length' as K.

     For any non-negative integer K,
          (eqv? k (gray-code->integer (integer->gray-code k)))

 -- Function: = k1 k2
 -- Function: gray-code<? k1 k2
 -- Function: gray-code>? k1 k2
 -- Function: gray-code<=? k1 k2
 -- Function: gray-code>=? k1 k2
     These procedures return #t if their Gray code arguments are
     (respectively): equal, monotonically increasing, monotonically
     decreasing, monotonically nondecreasing, or monotonically
     nonincreasing.

     For any non-negative integers K1 and K2, the Gray code predicate
     of `(integer->gray-code k1)' and `(integer->gray-code k2)' will
     return the same value as the corresponding predicate of K1 and K2.

7.2.7.3 Bitwise Lamination
..........................

 -- Function: delaminate-list count ks
     Returns a list of COUNT integers comprised of the Jth bit of the
     integers KS where J ranges from COUNT-1 to 0.

          (map (lambda (k) (number->string k 2))
               (delaminate-list 4 '(7 6 5 4 0 0 0 0)))
              => ("0" "11110000" "11000000" "10100000")

     `delaminate-list' is its own inverse:
          (delaminate-list 8 (delaminate-list 4 '(7 6 5 4 0 0 0 0)))
              => (7 6 5 4 0 0 0 0)


File: slib.info,  Node: Peano Space-Filling Curve,  Next: Sierpinski Curve,  Prev: Hilbert Space-Filling Curve,  Up: Space-Filling Curves

7.2.7.4 Peano Space-Filling Curve
.................................

`(require 'peano-fill)' 

 -- Function: natural->peano-coordinates scalar rank
     Returns a list of RANK nonnegative integer coordinates
     corresponding to exact nonnegative integer SCALAR.  The lists
     returned by `natural->peano-coordinates' for SCALAR arguments 0
     and 1 will differ in the first element.

 -- Function: peano-coordinates->natural coords
     Returns an exact nonnegative integer corresponding to COORDS, a
     list of nonnegative integer coordinates.

 -- Function: integer->peano-coordinates scalar rank
     Returns a list of RANK integer coordinates corresponding to exact
     integer SCALAR.  The lists returned by
     `integer->peano-coordinates' for SCALAR arguments 0 and 1 will
     differ in the first element.

 -- Function: peano-coordinates->integer coords
     Returns an exact integer corresponding to COORDS, a list of integer
     coordinates.


File: slib.info,  Node: Sierpinski Curve,  Prev: Peano Space-Filling Curve,  Up: Space-Filling Curves

7.2.7.5 Sierpinski Curve
........................

`(require 'sierpinski)' 

 -- Function: make-sierpinski-indexer max-coordinate
     Returns a procedure (eg hash-function) of 2 numeric arguments which
     preserves _nearness_ in its mapping from NxN to N.

     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]:
          (define space-key (make-sierpinski-indexer 100))
     Now let's compute the index of some points:
          (space-key 24 78)               => 9206
          (space-key 23 80)               => 9172

     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 _tends_ to be so.

     Example applications:
        * Sort points by Sierpinski index to get heuristic solution to
          _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.

        * 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.)



File: slib.info,  Node: Soundex,  Next: String Search,  Prev: Space-Filling Curves,  Up: Sorting and Searching

7.2.8 Soundex
-------------

`(require 'soundex)' 

 -- Function: soundex name
     Computes the _soundex_ hash of 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 `Sorting and searching', pp 391-2

     To manage unusual inputs, `soundex' omits all non-alphabetic
     characters.  Consequently, in this implementation:

          (soundex <string of blanks>)    => ""
          (soundex "")                    => ""

     Examples from Knuth:

          (map soundex '("Euler" "Gauss" "Hilbert" "Knuth"
                                 "Lloyd" "Lukasiewicz"))
                  => ("E460" "G200" "H416" "K530" "L300" "L222")

          (map soundex '("Ellery" "Ghosh" "Heilbronn" "Kant"
                                  "Ladd" "Lissajous"))
                  => ("E460" "G200" "H416" "K530" "L300" "L222")

     Some cases in which the algorithm fails (Knuth):

          (map soundex '("Rogers" "Rodgers"))     => ("R262" "R326")

          (map soundex '("Sinclair" "St. Clair")) => ("S524" "S324")

          (map soundex '("Tchebysheff" "Chebyshev")) => ("T212" "C121")


File: slib.info,  Node: String Search,  Next: Sequence Comparison,  Prev: Soundex,  Up: Sorting and Searching

7.2.9 String Search
-------------------

`(require 'string-search)' 

 -- Procedure: string-index string char
 -- Procedure: string-index-ci string char
     Returns the index of the first occurence of CHAR within STRING, or
     `#f' if the STRING does not contain a character CHAR.

 -- Procedure: string-reverse-index string char
 -- Procedure: string-reverse-index-ci string char
     Returns the index of the last occurence of CHAR within STRING, or
     `#f' if the STRING does not contain a character CHAR.

 -- Procedure: substring? pattern string
 -- Procedure: substring-ci? pattern string
     Searches STRING to see if some substring of STRING is equal to
     PATTERN.  `substring?' returns the index of the first character of
     the first substring of STRING that is equal to PATTERN; or `#f' if
     STRING does not contain PATTERN.

          (substring? "rat" "pirate") =>  2
          (substring? "rat" "outrage") =>  #f
          (substring? "" any-string) =>  0

 -- Procedure: find-string-from-port? str in-port max-no-chars
     Looks for a string STR within the first MAX-NO-CHARS chars of the
     input port IN-PORT.

 -- 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.

 -- Procedure: find-string-from-port? str in-port char
     Searches up to the first occurrence of character CHAR in STR.

 -- Procedure: find-string-from-port? str in-port proc
     Searches up to the first occurrence of the procedure PROC
     returning non-false when called with a character (from IN-PORT)
     argument.

     When the STR is found, `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 STR) The
     function returns `#f' when the STR isn't found.

     `find-string-from-port?' reads the port _strictly_ sequentially,
     and does not perform any buffering.  So `find-string-from-port?'
     can be used even if the IN-PORT is open to a pipe or other
     communication channel.

 -- Function: string-subst txt old1 new1 ...
     Returns a copy of string TXT with all occurrences of string OLD1
     in TXT replaced with NEW1; then OLD2 replaced with NEW2 ....
     Matches are found from the left.  Matches do not overlap.

 -- Function: count-newlines str
     Returns the number of `#\newline' characters in string STR.


File: slib.info,  Node: Sequence Comparison,  Prev: String Search,  Up: Sorting and Searching

7.2.10 Sequence Comparison
--------------------------

`(require 'diff)' 

`diff:edit-length' implements the algorithm:

     S. Wu, E. Myers, U. Manber, and W. Miller,
        "An O(NP) Sequence Comparison Algorithm,"
        Information Processing Letters 35, 6 (1990), 317-323.
        `http://www.cs.arizona.edu/people/gene/PAPERS/np_diff.ps'

The values returned by `diff:edit-length' can be used to gauge the
degree of match between two sequences.

`diff:edits' and `diff:longest-common-subsequence' combine the
algorithm with the divide-and-conquer method outlined in:

     E. Myers and W. Miller,
        "Optimal alignments in linear space",
        Computer Application in the Biosciences (CABIOS), 4(1):11-17, 1988.
        `http://www.cs.arizona.edu/people/gene/PAPERS/linear.ps'

If the items being sequenced are text lines, then the computed
edit-list is equivalent to the output of the "diff" utility program.
If the items being sequenced are words, then it is like the lesser
known "spiff" program.  

 -- Function: diff:longest-common-subsequence array1 array2 p-lim
 -- Function: diff:longest-common-subsequence array1 array2
     ARRAY1 and ARRAY2 are one-dimensional arrays.

     The non-negative integer P-LIM, if provided, is maximum number of
     deletions of the shorter sequence to allow.
     `diff:longest-common-subsequence' will return `#f' if more
     deletions would be necessary.

     `diff:longest-common-subsequence' returns a one-dimensional array
     of length `(quotient (- (+ len1 len2) (diff:edit-length ARRAY1
     ARRAY2)) 2)' holding the longest sequence common to both ARRAYs.

 -- Function: diff:edits array1 array2 p-lim
 -- Function: diff:edits array1 array2
     ARRAY1 and ARRAY2 are one-dimensional arrays.

     The non-negative integer P-LIM, if provided, is maximum number of
     deletions of the shorter sequence to allow.  `diff:edits' will
     return `#f' if more deletions would be necessary.

     `diff:edits' returns a vector of length `(diff:edit-length ARRAY1
     ARRAY2)' composed of a shortest sequence of edits transformaing
     ARRAY1 to ARRAY2.

     Each edit is an integer:
    K > 0
          Inserts `(array-ref ARRAY1 (+ -1 J))' into the sequence.

    K < 0
          Deletes `(array-ref ARRAY2 (- -1 K))' from the sequence.

 -- Function: diff:edit-length array1 array2 p-lim
 -- Function: diff:edit-length array1 array2
     ARRAY1 and ARRAY2 are one-dimensional arrays.

     The non-negative integer P-LIM, if provided, is maximum number of
     deletions of the shorter sequence to allow.  `diff:edit-length'
     will return `#f' if more deletions would be necessary.

     `diff:edit-length' returns the length of the shortest sequence of
     edits transformaing ARRAY1 to ARRAY2.

     (diff:longest-common-subsequence "fghiejcklm" "fgehijkpqrlm")
     => "fghijklm"

     (diff:edit-length "fghiejcklm" "fgehijkpqrlm")
     => 6

     (diff:edits "fghiejcklm" "fgehijkpqrlm")
     => #A:fixZ32b(3 -5 -7 8 9 10)
            ; e  c  h p q  r


File: slib.info,  Node: Procedures,  Next: Standards Support,  Prev: Sorting and Searching,  Up: Other Packages

7.3 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.


File: slib.info,  Node: Type Coercion,  Next: String-Case,  Prev: Procedures,  Up: Procedures

7.3.1 Type Coercion
-------------------

`(require 'coerce)' 

 -- Function: type-of obj
     Returns a symbol name for the type of OBJ.

 -- Function: coerce obj result-type
     Converts and returns OBJ of type `char', `number', `string',
     `symbol', `list', or `vector' to RESULT-TYPE (which must be one of
     these symbols).


File: slib.info,  Node: String-Case,  Next: String Ports,  Prev: Type Coercion,  Up: Procedures

7.3.2 String-Case
-----------------

`(require 'string-case)' 

 -- Procedure: string-upcase str
 -- Procedure: string-downcase str
 -- Procedure: string-capitalize str
     The obvious string conversion routines.  These are non-destructive.

 -- Function: string-upcase! str
 -- Function: string-downcase! str
 -- Function: string-capitalize! str
     The destructive versions of the functions above.

 -- Function: string-ci->symbol str
     Converts string STR to a symbol having the same case as if the
     symbol had been `read'.

 -- Function: symbol-append obj1 ...
     Converts OBJ1 ... 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).

 -- Function: StudlyCapsExpand str delimiter
 -- Function: StudlyCapsExpand str
     DELIMITER must be a string or character.  If absent, DELIMITER
     defaults to `-'.  `StudlyCapsExpand' returns a copy of STR where
     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.

          (StudlyCapsExpand "aX" " ")   => "a X"
          (StudlyCapsExpand "aX" "..")  => "a..X"
          (StudlyCapsExpand "AX")       => "AX"
          (StudlyCapsExpand "Ax")       => "Ax"
          (StudlyCapsExpand "AXLE")     => "AXLE"
          (StudlyCapsExpand "aAXACz")   => "a-AXA-Cz"
          (StudlyCapsExpand "AaXACz")   => "Aa-XA-Cz"
          (StudlyCapsExpand "AAaXACz")  => "A-Aa-XA-Cz"
          (StudlyCapsExpand "AAaXAC")   => "A-Aa-XAC"



File: slib.info,  Node: String Ports,  Next: Line I/O,  Prev: String-Case,  Up: Procedures

7.3.3 String Ports
------------------

`(require 'string-port)' 

 -- Procedure: call-with-output-string proc
     PROC must be a procedure of one argument.  This procedure calls
     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.

 -- Procedure: call-with-input-string string proc
     PROC must be a procedure of one argument.  This procedure calls
     PROC with one argument: an (newly created) input port from which
     STRING's contents may be read.  When PROC returns, the port is
     closed and the value yielded by the procedure PROC is returned.


File: slib.info,  Node: Line I/O,  Next: Multi-Processing,  Prev: String Ports,  Up: Procedures

7.3.4 Line I/O
--------------

`(require 'line-i/o)' 

 -- Function: read-line
 -- Function: read-line port
     Returns a string of the characters up to, but not including a
     newline or end of file, updating PORT to point to the character
     following the newline.  If no characters are available, an end of
     file object is returned.  The PORT argument may be omitted, in
     which case it defaults to the value returned by
     `current-input-port'.

 -- Procedure: read-line! string
 -- Procedure: read-line! string port
     Fills STRING with characters up to, but not including a newline or
     end of file, updating the PORT to point to the last character read
     or following the newline if it was read.  If no characters are
     available, an end of file object is returned.  If a newline or end
     of file was found, the number of characters read is returned.
     Otherwise, `#f' is returned.  The PORT argument may be omitted, in
     which case it defaults to the value returned by
     `current-input-port'.

 -- Function: write-line string
 -- Function: write-line string port
     Writes STRING followed by a newline to the given PORT and returns
     an unspecified value.  The PORT argument may be omitted, in which
     case it defaults to the value returned by `current-input-port'.

 -- Function: system->line command tmp
 -- Function: system->line command
     COMMAND must be a string.  The string TMP, if supplied, is a path
     to use as a temporary file.  `system->line' calls `system' with
     COMMAND as argument, redirecting stdout to file TMP.
     `system->line' returns a string containing the first line of
     output from TMP.

     `system->line' is intended to be a portable method for getting
     one-line results from programs like `pwd', `whoami', `hostname',
     `which', `identify', and `cksum'.  Its behavior when called with
     programs which generate lots of output is unspecified.


File: slib.info,  Node: Multi-Processing,  Next: Metric Units,  Prev: Line I/O,  Up: Procedures

7.3.5 Multi-Processing
----------------------

`(require 'process)' 

  This module implements asynchronous (non-polled) time-sliced
multi-processing in the SCM Scheme implementation using procedures
`alarm' and `alarm-interrupt'.  Until this is ported to another
implementation, consider it an example of writing schedulers in Scheme.

 -- Procedure: add-process! proc
     Adds proc, which must be a procedure (or continuation) capable of
     accepting accepting one argument, to the `process:queue'.  The
     value returned is unspecified.  The argument to PROC should be
     ignored.  If PROC returns, the process is killed.

 -- Procedure: process:schedule!
     Saves the current process on `process:queue' and runs the next
     process from `process:queue'.  The value returned is unspecified.

 -- Procedure: kill-process!
     Kills the current process and runs the next process from
     `process:queue'.  If there are no more processes on
     `process:queue', `(slib:exit)' is called (*note System::).


File: slib.info,  Node: Metric Units,  Prev: Multi-Processing,  Up: Procedures

7.3.6 Metric Units
------------------

`(require 'metric-units)' 

  `http://swiss.csail.mit.edu/~jaffer/MIXF'

  "Metric Interchange Format" is a character string encoding for
numerical values and units which:

   * is unambiguous in all locales;

   * uses only [TOG] "Portable Character Set" characters matching "Basic
     Latin" characters in Plane 0 of the Universal Character Set [UCS];

   * is transparent to [UTF-7] and [UTF-8] UCS transformation formats;

   * is human readable and writable;

   * is machine readable and writable;

   * incorporates SI prefixes and units;

   * incorporates [ISO 6093] numbers; and

   * incorporates [IEC 60027-2] binary prefixes.

  In the expression for the value of a quantity, the unit symbol is
placed after the numerical value.  A dot (PERIOD, `.') 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, `.') placed between them.

  Unit symbols formed from other unit symbols by division are indicated
by means of a SOLIDUS (`/') 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 (`(' and `)') 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 (`^').
Exponents may be positive or negative.  Fractional exponents must be
parenthesized.

7.3.6.1 SI Prefixes
...................

            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

7.3.6.2 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).

                     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

7.3.6.3 Unit Symbols
....................

         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

  * The formulas are:

   * r/rad = 8 * atan(1)

   * o/r = 1 / 360

   * db/Np = ln(10) / 20

 -- Function: si:conversion-factor to-unit from-unit
     If the strings FROM-UNIT and TO-UNIT express valid unit
     expressions for quantities of the same unit-dimensions, then the
     value returned by `si:conversion-factor' will be such that
     multiplying a numerical value expressed in FROM-UNITs by the
     returned conversion factor yields the numerical value expressed in
     TO-UNITs.

     Otherwise, `si:conversion-factor' returns:

    -3
          if neither FROM-UNIT nor TO-UNIT is a syntactically valid
          unit.

    -2
          if FROM-UNIT is not a syntactically valid unit.

    -1
          if TO-UNIT is not a syntactically valid unit.

    0
          if linear conversion (by a factor) is not possible.


     (si:conversion-factor "km/s" "m/s" ) => 0.001
     (si:conversion-factor "N"    "m/s" ) => 0
     (si:conversion-factor "moC"  "oC"  ) => 1000
     (si:conversion-factor "mK"   "oC"  ) => 0
     (si:conversion-factor "rad"  "o"   ) => 0.0174533
     (si:conversion-factor "K"    "o"   ) => 0
     (si:conversion-factor "K"    "K"   ) => 1
     (si:conversion-factor "oK"   "oK"  ) => -3
     (si:conversion-factor ""     "s/s" ) => 1
     (si:conversion-factor "km/h" "mph" ) => -2


File: slib.info,  Node: Standards Support,  Next: Session Support,  Prev: Procedures,  Up: Other Packages

7.4 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


File: slib.info,  Node: RnRS,  Next: With-File,  Prev: Standards Support,  Up: Standards Support

7.4.1 RnRS
----------

The `r2rs', `r3rs', `r4rs', and `r5rs' features attempt to provide
procedures and macros to bring a Scheme implementation to the desired
version of Scheme.

 -- Feature: r2rs
     Requires features implementing procedures and optional procedures
     specified by `Revised^2 Report on the Algorithmic Language Scheme';
     namely `rev3-procedures' and `rev2-procedures'.

 -- Feature: r3rs
     Requires features implementing procedures and optional procedures
     specified by `Revised^3 Report on the Algorithmic Language Scheme';
     namely `rev3-procedures'.

     _Note:_ SLIB already mandates the `r3rs' procedures which can be
     portably implemented in `r4rs' implementations.

 -- Feature: r4rs
     Requires features implementing procedures and optional procedures
     specified by `Revised^4 Report on the Algorithmic Language Scheme';
     namely `rev4-optional-procedures'.

 -- Feature: r5rs
     Requires features implementing procedures and optional procedures
     specified by `Revised^5 Report on the Algorithmic Language Scheme';
     namely `values', `macro', and `eval'.


File: slib.info,  Node: With-File,  Next: Transcripts,  Prev: RnRS,  Up: Standards Support

7.4.2 With-File
---------------

`(require 'with-file)' 

 -- Function: with-input-from-file file thunk
 -- Function: with-output-to-file file thunk
     Description found in R4RS.


File: slib.info,  Node: Transcripts,  Next: Rev2 Procedures,  Prev: With-File,  Up: Standards Support

7.4.3 Transcripts
-----------------

`(require 'transcript)' 

 -- Function: transcript-on filename
 -- Function: transcript-off filename
     Redefines `read-char', `read', `write-char', `write', `display',
     and `newline'.


File: slib.info,  Node: Rev2 Procedures,  Next: Rev4 Optional Procedures,  Prev: Transcripts,  Up: Standards Support

7.4.4 Rev2 Procedures
---------------------

`(require 'rev2-procedures)' 

  The procedures below were specified in the `Revised^2 Report on
Scheme'.  *N.B.*: The symbols `1+' and `-1+' are not `R4RS' syntax.
Scheme->C, for instance, chokes on this module.

 -- Procedure: substring-move-left! string1 start1 end1 string2 start2
 -- Procedure: substring-move-right! string1 start1 end1 string2 start2
     STRING1 and STRING2 must be a strings, and START1, START2 and END1
     must be exact integers satisfying

          0 <= START1 <= END1 <= (string-length STRING1)
          0 <= START2 <= END1 - START1 + START2 <= (string-length STRING2)

     `substring-move-left!' and `substring-move-right!' store
     characters of STRING1 beginning with index START1 (inclusive) and
     ending with index END1 (exclusive) into STRING2 beginning with
     index START2 (inclusive).

     `substring-move-left!' stores characters in time order of
     increasing indices.  `substring-move-right!' stores characters in
     time order of increasing indeces.

 -- Procedure: substring-fill! string start end char
     Fills the elements START-END of STRING with the character CHAR.

 -- Function: string-null? str
     == `(= 0 (string-length STR))'

 -- Procedure: append! pair1 ...
     Destructively appends its arguments.  Equivalent to `nconc'.

 -- Function: 1+ n
     Adds 1 to N.

 -- Function: -1+ n
     Subtracts 1 from N.

 -- Function: <?
 -- Function: <=?
 -- Function: =?
 -- Function: >?
 -- Function: >=?
     These are equivalent to the procedures of the same name but
     without the trailing `?'.


File: slib.info,  Node: Rev4 Optional Procedures,  Next: Multi-argument / and -,  Prev: Rev2 Procedures,  Up: Standards Support

7.4.5 Rev4 Optional Procedures
------------------------------

`(require 'rev4-optional-procedures)' 

  For the specification of these optional procedures, *Note Standard
procedures: (r4rs)Standard procedures.

 -- Function: list-tail l p

 -- Function: string-copy

 -- Procedure: string-fill! s obj

 -- Procedure: vector-fill! s obj


File: slib.info,  Node: Multi-argument / and -,  Next: Multi-argument Apply,  Prev: Rev4 Optional Procedures,  Up: Standards Support

7.4.6 Multi-argument / and -
----------------------------

`(require 'multiarg/and-)' 

  For the specification of these optional forms, *Note Numerical
operations: (r4rs)Numerical operations.

 -- Function: / dividend divisor1 ...

 -- Function: - minuend subtrahend1 ...


File: slib.info,  Node: Multi-argument Apply,  Next: Rationalize,  Prev: Multi-argument / and -,  Up: Standards Support

7.4.7 Multi-argument Apply
--------------------------

`(require 'multiarg-apply)' 

For the specification of this optional form, *Note Control features:
(r4rs)Control features.

 -- Function: apply proc arg1 ...


File: slib.info,  Node: Rationalize,  Next: Promises,  Prev: Multi-argument Apply,  Up: Standards Support

7.4.8 Rationalize
-----------------

`(require 'rationalize)' 

 -- Function: rationalize x e
     Computes the correct result for exact arguments (provided the
     implementation supports exact rational numbers of unlimited
     precision); and produces a reasonable answer for inexact arguments
     when inexact arithmetic is implemented using floating-point.


  `Rationalize' has limited use in implementations lacking exact
(non-integer) rational numbers.  The following procedures return a list
of the numerator and denominator.

 -- Function: find-ratio x e
     `find-ratio' returns the list of the _simplest_ numerator and
     denominator whose quotient differs from X by no more than E.

     (find-ratio 3/97 .0001)             => (3 97)
     (find-ratio 3/97 .001)              => (1 32)

 -- Function: find-ratio-between x y
     `find-ratio-between' returns the list of the _simplest_ numerator
     and denominator between X and Y.

     (find-ratio-between 2/7 3/5)        => (1 2)
     (find-ratio-between -3/5 -2/7)      => (-1 2)


File: slib.info,  Node: Promises,  Next: Dynamic-Wind,  Prev: Rationalize,  Up: Standards Support

7.4.9 Promises
--------------

`(require 'promise)' 

 -- Function: make-promise proc

 -- Function: force promise

  `(require 'delay)' provides `force' and `delay':

 -- Macro: delay obj
     Change occurrences of `(delay EXPRESSION)' to

          (make-promise (lambda () EXPRESSION))


  (*note Control features: (r4rs)Control features.).


File: slib.info,  Node: Dynamic-Wind,  Next: Eval,  Prev: Promises,  Up: Standards Support

7.4.10 Dynamic-Wind
-------------------

`(require 'dynamic-wind)' 

  This facility is a generalization of Common LISP `unwind-protect',
designed to take into account the fact that continuations produced by
`call-with-current-continuation' may be reentered.

 -- Procedure: dynamic-wind thunk1 thunk2 thunk3
     The arguments THUNK1, THUNK2, and THUNK3 must all be procedures of
     no arguments (thunks).

     `dynamic-wind' calls THUNK1, THUNK2, and then THUNK3.  The value
     returned by THUNK2 is returned as the result of `dynamic-wind'.
     THUNK3 is also called just before control leaves the dynamic
     context of THUNK2 by calling a continuation created outside that
     context.  Furthermore, THUNK1 is called before reentering the
     dynamic context of THUNK2 by calling a continuation created inside
     that context.  (Control is inside the context of THUNK2 if THUNK2
     is on the current return stack).

     *Warning:* There is no provision for dealing with errors or
     interrupts.  If an error or interrupt occurs while using
     `dynamic-wind', the dynamic environment will be that in effect at
     the time of the error or interrupt.


File: slib.info,  Node: Eval,  Next: Values,  Prev: Dynamic-Wind,  Up: Standards Support

7.4.11 Eval
-----------

`(require 'eval)' 

 -- Function: eval expression environment-specifier
     Evaluates EXPRESSION in the specified environment and returns its
     value.  EXPRESSION must be a valid Scheme expression represented
     as data, and ENVIRONMENT-SPECIFIER must be a value returned by one
     of the three procedures described below.  Implementations may
     extend `eval' to allow non-expression programs (definitions) as
     the first argument and to allow other values as environments, with
     the restriction that `eval' is not allowed to create new bindings
     in the environments associated with `null-environment' or
     `scheme-report-environment'.

          (eval '(* 7 3) (scheme-report-environment 5))
                                                             =>  21

          (let ((f (eval '(lambda (f x) (f x x))
                         (null-environment))))
            (f + 10))
                                                             =>  20

 -- Function: scheme-report-environment version
 -- Function: null-environment version
 -- Function: null-environment
     VERSION must be an exact non-negative integer N corresponding to a
     version of one of the Revised^N Reports on Scheme.
     `Scheme-report-environment' returns a specifier for an environment
     that contains the set of bindings specified in the corresponding
     report that the implementation supports.  `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 N of
     the Revised^N Reports on Scheme must accept version N.  An error
     is signalled if the specified version is not available.

     The effect of assigning (through the use of `eval') a variable
     bound in a `scheme-report-environment' (for example `car') is
     unspecified. Thus the environments specified by
     `scheme-report-environment' may be immutable.


 -- Function: 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.

Here are some more `eval' examples:

     (require 'eval)
     => #<unspecified>
     (define car 'volvo)
     => #<unspecified>
     car
     => volvo
     (eval 'car (interaction-environment))
     => volvo
     (eval 'car (scheme-report-environment 5))
     => #<primitive-procedure car>
     (eval '(eval 'car (interaction-environment))
           (scheme-report-environment 5))
     => volvo
     (eval '(eval '(set! car 'buick) (interaction-environment))
           (scheme-report-environment 5))
     => #<unspecified>
     car
     => buick
     (eval 'car (scheme-report-environment 5))
     => #<primitive-procedure car>
     (eval '(eval 'car (interaction-environment))
           (scheme-report-environment 5))
     => buick


File: slib.info,  Node: Values,  Next: SRFI,  Prev: Eval,  Up: Standards Support

7.4.12 Values
-------------

`(require 'values)' 

 -- Function: values obj ...
     `values' takes any number of arguments, and passes (returns) them
     to its continuation.

 -- Function: call-with-values thunk proc
     THUNK must be a procedure of no arguments, and PROC must be a
     procedure.  `call-with-values' calls THUNK with a continuation
     that, when passed some values, calls PROC with those values as
     arguments.

     Except for continuations created by the `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 `call-with-values' procedure is
     unspecified.


File: slib.info,  Node: SRFI,  Prev: Values,  Up: Standards Support

7.4.13 SRFI
-----------

`(require 'srfi)' 

Implements "Scheme Request For Implementation" (SRFI) as described at
`http://srfi.schemers.org/'

 -- Macro: cond-expand <clause1> <clause2> ...
     _Syntax:_ Each <clause> should be of the form

     (<feature> <expression1> ...)

     where <feature> is a boolean expression composed of symbols and
     `and', `or', and `not' of boolean expressions.  The last <clause>
     may be an "else clause," which has the form

     (else <expression1> <expression2> ...).

     The first clause whose feature expression is satisfied is expanded.
     If no feature expression is satisfied and there is no else clause,
     an error is signaled.

     SLIB `cond-expand' is an extension of SRFI-0,
     `http://srfi.schemers.org/srfi-0/srfi-0.html'.

* Menu:

* SRFI-1::                      list-processing

   * SRFI-2 *Note Guarded LET* special form:: 

   * SRFI-8 *Note Binding to multiple values:: 

   * SRFI-9 *Note Define-Record-Type:: 

   * SRFI-11 *Note Binding to multiple values:: 

   * SRFI-23 `(define error slib:error)' 

   * SRFI-28 *Note Format:: 

   * SRFI-47 *Note Arrays:: 

   * SRFI-59 *Note Vicinity:: 

   * SRFI-60 *Note Bit-Twiddling:: 

   * SRFI-61 *Note Guarded COND Clause:: 

   * SRFI-63 *Note Arrays:: 

   * SRFI-94 *Note Irrational Integer Functions:: and *Note Irrational
     Real Functions:: 

   * SRFI-95 *Note Sorting:: 

   * SRFI-96 *Note Universal SLIB Procedures::                                |
                                                                              |

File: slib.info,  Node: SRFI-1,  Prev: SRFI,  Up: SRFI

7.4.13.1 SRFI-1
...............

`(require 'srfi-1)' 

Implements the "SRFI-1" "list-processing library" as described at
`http://srfi.schemers.org/srfi-1/srfi-1.html'

Constructors
------------

 -- Function: xcons d a
     `(define (xcons d a) (cons a d))'.

 -- Function: list-tabulate len proc
     Returns a list of length LEN.  Element I is `(PROC I)' for 0 <= I
     < LEN.

 -- Function: cons* obj1 obj2

 -- Function: list-copy flist

 -- Function: iota count start step
 -- Function: iota count start
 -- Function: iota count
     Returns a list of COUNT numbers: (START, START+STEP, ...,
     START+(COUNT-1)*STEP).

 -- Function: circular-list obj1 obj2 ...
     Returns a circular list of OBJ1, OBJ2, ....

Predicates
----------

 -- Function: proper-list? obj

 -- Function: circular-list? x

 -- Function: dotted-list? obj

 -- Function: null-list? obj

 -- Function: not-pair? obj

 -- Function: list= =pred list ...

Selectors
---------

 -- Function: first pair

 -- Function: second pair

 -- Function: third pair

 -- Function: fourth pair

 -- Function: fifth pair
 -- Function: sixth pair
 -- Function: seventh pair
 -- Function: eighth pair
 -- Function: ninth pair
 -- Function: tenth pair

 -- Function: car+cdr pair

 -- Function: drop lst k
 -- Function: take lst k
 -- Function: take! lst k

 -- Function: take-right lst k

 -- Function: drop-right lst k

 -- Procedure: drop-right! lst k

 -- Function: split-at lst k
 -- Function: split-at! lst k

 -- Function: last lst k ...

Miscellaneous
-------------

 -- Function: length+ clist

 -- Function: concatenate lists
 -- Function: concatenate! lists

 -- Procedure: reverse! lst

 -- Function: append-reverse rev-head tail
 -- Function: append-reverse! rev-head tail

 -- Function: zip list1 list2 ...

 -- Function: unzip1 lst
 -- Function: unzip2 lst
 -- Function: unzip3 lst
 -- Function: unzip4 lst
 -- Function: unzip5 lst

 -- Function: count pred list1 list2 ...

Fold and Unfold
---------------

 -- Function: fold kons knil clist1 clist2 ...

 -- Function: fold-right kons knil clist1 clist2 ...

 -- Function: pair-fold kons knil clist1 clist2 ...

 -- Function: pair-fold-right kons knil clist1 clist2 ...

 -- Function: reduce arg ...

 -- Procedure: map! f clist1 clist2 ...

 -- Function: pair-for-each f clist1 clist2 ...

Filtering and Partitioning
--------------------------

 -- Function: filter pred list

 -- Procedure: filter! pred list

 -- Function: partition pred list

 -- Function: remove pred list

 -- Procedure: partition! pred list

 -- Procedure: remove! pred list

Searching
---------

 -- Function: find pred clist

 -- Function: find-tail pred clist

 -- Function: span pred list

 -- Procedure: span! pred list

 -- Function: break pred list

 -- Procedure: break! pred list

 -- Function: any pred clist1 clist2 ...

 -- Function: list-index pred clist1 clist2 ...

 -- Function: member obj list =
 -- Function: member obj list

Deleting
--------

 -- Function: delete-duplicates x list =
 -- Function: delete-duplicates x list

 -- Procedure: delete-duplicates! x list =
 -- Procedure: delete-duplicates! x list

Association lists
-----------------

 -- Function: assoc obj alist pred
 -- Function: assoc obj alist

 -- Function: alist-cons key datum alist

 -- Function: alist-copy alist

 -- Function: alist-delete key alist =
 -- Function: alist-delete key alist

 -- Procedure: alist-delete! key alist =
 -- Procedure: alist-delete! key alist

Set operations
--------------

 -- Function: lset<= = list1 ...
     Determine if a  transitive subset relation exists between the
     lists LIST1 ..., using = to determine equality of list members.

 -- Function: lset= = list1 list2 ...

 -- Function: lset-adjoin list elt1 ...

 -- Function: lset-union = list1 ...

 -- Function: lset-intersection = list1 list2 ...

 -- Function: lset-difference = list1 list2 ...

 -- Function: lset-xor = list1 ...

 -- Function: lset-diff+intersection = list1 list2 ...

These are linear-update variants.  They are allowed, but not required,
to use the cons cells in their first list parameter to construct their
answer.  `lset-union!' is permitted to recycle cons cells from any of
its list arguments.

 -- Procedure: lset-intersection! = list1 list2 ...

 -- Procedure: lset-difference! = list1 list2 ...

 -- Procedure: lset-union! = list1 ...

 -- Procedure: lset-xor! = list1 ...

 -- Procedure: lset-diff+intersection! = list1 list2 ...


File: slib.info,  Node: Session Support,  Next: System Interface,  Prev: Standards Support,  Up: Other Packages

7.5 Session Support
===================

If `(provided? 'abort)':

 -- Function: abort
     Resumes the top level Read-Eval-Print loop.  If provided, `abort'
     is used by the `break' and `debug' packages.

* Menu:

* Repl::                        Macros at top-level
* Quick Print::                 Loop-safe Output
* Debug::                       To err is human ...
* Breakpoints::                 Pause execution
* Trace::                       'trace


File: slib.info,  Node: Repl,  Next: Quick Print,  Prev: Session Support,  Up: Session Support

7.5.1 Repl
----------

`(require 'repl)' 

  Here is a read-eval-print-loop which, given an eval, evaluates forms.

 -- Procedure: repl:top-level repl:eval
     `read's, `repl:eval's and `write's expressions from
     `(current-input-port)' to `(current-output-port)' until an
     end-of-file is encountered.  `load', `slib:eval', `slib:error',
     and `repl:quit' dynamically bound during `repl:top-level'.

 -- Procedure: repl:quit
     Exits from the invocation of `repl:top-level'.

  The `repl:' procedures establish, as much as is possible to do
portably, a top level environment supporting macros.  `repl:top-level'
uses `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 `slib:error'.  It will
display its arguments and reenter `repl:top-level'.  `slib:error'
dynamically bound by `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:
     (require 'macro)
     (require 'repl)
     (repl:top-level macro:eval)


File: slib.info,  Node: Quick Print,  Next: Debug,  Prev: Repl,  Up: Session Support

7.5.2 Quick Print
-----------------

`(require 'qp)' 

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.

     Notice that the neccessity for truncating output eliminates
     Common-Lisp's *Note Format:: from consideration; even when
     variables `*print-level*' and `*print-level*' are set, huge
     strings and bit-vectors are _not_ limited.

 -- Procedure: qp arg1 ...
 -- Procedure: qpn arg1 ...
 -- Procedure: qpr arg1 ...
     `qp' writes its arguments, separated by spaces, to
     `(current-output-port)'.  `qp' compresses printing by substituting
     `...' for substructure it does not have sufficient room to print.
     `qpn' is like `qp' but outputs a newline before returning.  `qpr'
     is like `qpn' except that it returns its last argument.

 -- Variable: *qp-width*
     *QP-WIDTH* is the largest number of characters that `qp' should
     use.  If *QP-WIDTH* is #f, then all items will be `write'n.  If
     *QP-WIDTH* is 0, then all items except procedures will be
     `write'n; procedures will be indicated by `#[proc]'.


File: slib.info,  Node: Debug,  Next: Breakpoints,  Prev: Quick Print,  Up: Session Support

7.5.3 Debug
-----------

`(require 'debug)' 

Requiring `debug' automatically requires `trace' and `break'.

An application with its own datatypes may want to substitute its own
printer for `qp'.  This example shows how to do this:

     (define qpn (lambda args) ...)
     (provide 'qp)
     (require 'debug)
     

 -- Procedure: trace-all file ...
     Traces (*note Trace::) all procedures `define'd at top-level in
     `file' ....

 -- Procedure: track-all file ...
     Tracks (*note Trace::) all procedures `define'd at top-level in
     `file' ....

 -- Procedure: stack-all file ...
     Stacks (*note Trace::) all procedures `define'd at top-level in
     `file' ....

 -- Procedure: break-all file ...
     Breakpoints (*note Breakpoints::) all procedures `define'd at
     top-level in `file' ....


File: slib.info,  Node: Breakpoints,  Next: Trace,  Prev: Debug,  Up: Session Support

7.5.4 Breakpoints
-----------------

`(require 'break)' 

 -- Function: init-debug
     If your Scheme implementation does not support `break' or `abort',
     a message will appear when you `(require 'break)' or `(require
     'debug)' telling you to type `(init-debug)'.  This is in order to
     establish a top-level continuation.  Typing `(init-debug)' at top
     level sets up a continuation for `break'.

 -- Function: breakpoint arg1 ...
     Returns from the top level continuation and pushes the
     continuation from which it was called on a continuation stack.

 -- Function: continue
     Pops the topmost continuation off of the continuation stack and
     returns an unspecified value to it.

 -- Function: continue arg1 ...
     Pops the topmost continuation off of the continuation stack and
     returns ARG1 ... to it.

 -- Macro: break proc1 ...
     Redefines the top-level named procedures given as arguments so that
     `breakpoint' is called before calling PROC1 ....

 -- Macro: 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.

 -- Macro: unbreak proc1 ...
     Turns breakpoints off for its arguments.

 -- Macro: unbreak
     With no arguments, unbreaks all currently broken identifiers and
     returns a list of these formerly broken identifiers.

  These are _procedures_ for breaking.  If defmacros are not natively
supported by your implementation, these might be more convenient to use.

 -- Function: breakf proc
 -- Function: breakf proc name
     To break, type
          (set! SYMBOL (breakf SYMBOL))
     or
          (set! SYMBOL (breakf SYMBOL 'SYMBOL))
     or
          (define SYMBOL (breakf FUNCTION))
     or
          (define SYMBOL (breakf FUNCTION 'SYMBOL))

 -- Function: unbreakf proc
     To unbreak, type
          (set! SYMBOL (unbreakf SYMBOL))


File: slib.info,  Node: Trace,  Prev: Breakpoints,  Up: Session Support

7.5.5 Tracing
-------------

`(require 'trace)' 

This feature provides three ways to monitor procedure invocations:

stack
     Pushes the procedure-name when the procedure is called; pops when
     it returns.

track
     Pushes the procedure-name and arguments when the procedure is
     called; pops when it returns.

trace
     Pushes the procedure-name and prints `CALL PROCEDURE-NAME ARG1
     ...' when the procdure is called; pops and prints `RETN
     PROCEDURE-NAME VALUE' when the procedure returns.

 -- Variable: 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 DEBUG:MAX-COUNT.

 -- Function: print-call-stack
 -- Function: print-call-stack port
     Prints the call-stack to PORT or the current-error-port.

 -- Macro: trace proc1 ...
     Traces the top-level named procedures given as arguments.

 -- Macro: 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.

 -- Macro: track proc1 ...
     Traces the top-level named procedures given as arguments.

 -- Macro: 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.

 -- Macro: stack proc1 ...
     Traces the top-level named procedures given as arguments.

 -- Macro: 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.

 -- Macro: untrace proc1 ...
     Turns tracing, tracking, and  off for its arguments.

 -- Macro: untrace
     With no arguments, untraces all currently traced identifiers and
     returns a list of these formerly traced identifiers.

 -- Macro: untrack proc1 ...
     Turns tracing, tracking, and  off for its arguments.

 -- Macro: untrack
     With no arguments, untracks all currently tracked identifiers and
     returns a list of these formerly tracked identifiers.

 -- Macro: unstack proc1 ...
     Turns tracing, stacking, and  off for its arguments.

 -- Macro: unstack
     With no arguments, unstacks all currently stacked identifiers and
     returns a list of these formerly stacked identifiers.

  These are _procedures_ for tracing.  If defmacros are not natively
supported by your implementation, these might be more convenient to use.

 -- Function: tracef proc
 -- Function: tracef proc name
 -- Function: trackf proc
 -- Function: trackf proc name
 -- Function: stackf proc
 -- Function: stackf proc name
     To trace, type
          (set! SYMBOL (tracef SYMBOL))
     or
          (set! SYMBOL (tracef SYMBOL 'SYMBOL))
     or
          (define SYMBOL (tracef FUNCTION))
     or
          (define SYMBOL (tracef FUNCTION 'SYMBOL))

 -- Function: untracef proc
     Removes tracing, tracking, or stacking for PROC.  To untrace, type
          (set! SYMBOL (untracef SYMBOL))


File: slib.info,  Node: System Interface,  Next: Extra-SLIB Packages,  Prev: Session Support,  Up: Other Packages

7.6 System Interface
====================

If `(provided? 'getenv)': 

 -- Function: getenv name
     Looks up NAME, a string, in the program environment.  If NAME is
     found a string of its value is returned.  Otherwise, `#f' is
     returned.

If `(provided? 'system)': 

 -- Function: system command-string
     Executes the COMMAND-STRING on the computer and returns the
     integer status code.

If `(provided? 'program-arguments)':                                          |
                                                                              |
 -- Function: program-arguments                                               |
     Returns a list of strings, the first of which is the program name        |
     followed by the command-line arguments.                                  |
                                                                              |
* Menu:

* Directories::
* Transactions::
* CVS::


File: slib.info,  Node: Directories,  Next: Transactions,  Prev: System Interface,  Up: System Interface

7.6.1 Directories
-----------------

`(require 'directory)' 

 -- Function: current-directory
     `current-directory' returns a string containing the absolute file
     name representing the current working directory.  If this string
     cannot be obtained, #f is returned.

     If `current-directory' cannot be supported by the platform, then
     #f is returned.

 -- Function: make-directory name
     Creates a sub-directory NAME of the current-directory.  If
     successful, `make-directory' returns #t; otherwise #f.

 -- Function: directory-for-each proc directory
     PROC must be a procedure taking one argument.
     `Directory-For-Each' applies PROC to the (string) name of each
     file in DIRECTORY.  The dynamic order in which PROC is applied to
     the filenames is unspecified.  The value returned by
     `directory-for-each' is unspecified.

 -- Function: directory-for-each proc directory pred
     Applies PROC only to those filenames for which the procedure PRED
     returns a non-false value.

 -- Function: directory-for-each proc directory match
     Applies PROC only to those filenames for which `(filename:match??
     MATCH)' would return a non-false value (*note Filenames:
     (slib)Filenames.).

          (require 'directory)
          (directory-for-each print "." "[A-Z]*.scm")
          -|
          "Bev2slib.scm"
          "Template.scm"


File: slib.info,  Node: Transactions,  Next: CVS,  Prev: Directories,  Up: System Interface

7.6.2 Transactions
------------------

If `system' is provided by the Scheme implementation, the "transact"
package provides functions for file-locking and file-replacement
transactions.

  `(require 'transact)' 

File Locking
............

Unix file-locking is focussed on write permissions for segments of a
existing file.  While this might be employed for (binary) database
access, it is not used for everyday contention (between users) for text
files.

Microsoft has several file-locking protocols.  Their model denies write
access to a file if any reader has it open.  This is too restrictive.
Write access is denied even when the reader has reached end-of-file.
And tracking read access (which is much more common than write access)
causes havoc when remote hosts crash or disconnect.

It is bizarre that the concept of multi-user contention for modifying
files has not been adequately addressed by either of the large
operating system development efforts.  There is further irony that both
camps support contention detection and resolution only through weak
conventions of some their document editing programs.

The "file-lock" procedures implement a transaction method for file replacement
compatible with the methods used by the GNU "emacs" text editor on Unix
systems and the Microsoft "Word" editor.  

Both protocols employ what I term a "certificate" containing the user,
hostname, time, and (on Unix) process-id.  Intent to replace FILE is
indicated by adding to FILE's directory a certificate object whose name
is derived from FILE.

The Microsoft Word certificate is contained in a 162 byte file named
for the visited FILE with a `~$' prefix.  Emacs/Unix creates a symbolic
link to a certificate named for the visited FILE prefixed with `.#'.
Because Unix systems can import Microsoft file systems, these routines
maintain and check both Emacs and Word certificates.

 -- Function: file-lock-owner path
     Returns the string `USER@HOSTNAME' associated with the lock owner
     of file PATH if locked; and #f otherwise.

 -- Procedure: file-lock! path email
 -- Procedure: file-lock! path
     PATH must be a string naming the file to be locked.  If supplied,
     EMAIL must be a string formatted as `USER@HOSTNAME'.  If absent,
     EMAIL defaults to the value returned by `user-email-address'.

     If PATH is already locked, then `file-lock!' returns `#f'.  If
     PATH is unlocked, then `file-lock!' returns the certificate string
     associated with the new lock for file PATH.

 -- Procedure: file-unlock! path certificate
     PATH must be a string naming the file to be unlocked.  CERTIFICATE
     must be the string returned by `file-lock!' for PATH.

     If PATH is locked with CERTIFICATE, then `file-unlock!' removes
     the locks and returns `#t'.  Otherwise, `file-unlock!' leaves the
     file system unaltered and returns `#f'.

 -- Function: describe-file-lock path prefix                                  |
 -- Function: describe-file-lock path                                         |
     PATH must be a string naming a file.  Optional argument PREFIX is        |
     a string printed before each line of the message.                        |
     `describe-file-lock' prints to `(current-error-port)' that PATH is       |
     locked for writing and lists its lock-files.                             |
                                                                              |
          (describe-file-lock "my.txt" ">> ")                                 |
          -|                                                                  |
          >> "my.txt" is locked for writing by 'luser@no.com.4829:1200536423' |
          >> (lock files are "~$my.txt" and ".#my.txt")                       |
                                                                              |
File Transactions
.................

 -- Function: emacs:backup-name path backup-style
     PATH must be a string.  BACKUP-STYLE must be a symbol.  Depending
     on BACKUP-STYLE, `emacs:backup-name' returns:
    none
          #f

    simple
          the string "PATH~"

    numbered
          the string "PATH.~N~", where N is one greater than the
          highest number appearing in a filename matching "PATH.~*~".  N
          defauls to 1 when no filename matches.

    existing
          the string "PATH.~N~" if a numbered backup already exists in
          this directory; otherwise. "PATH~"

    orig
          the string "PATH.orig"

    bak
          the string "PATH.bak"

 -- Function: transact-file-replacement proc path backup-style
          certificate
 -- Function: transact-file-replacement proc path backup-style
 -- Function: transact-file-replacement proc path
     PATH must be a string naming an existing file.  BACKUP-STYLE is
     one of the symbols none, simple, numbered, existing, orig, bak or
     #f; with meanings described above; or a string naming the location
     of a backup file.  BACKUP-STYLE defaults to #f.  If supplied,
     CERTIFICATE is the certificate with which PATH is locked.

     PROC must be a procedure taking two string arguments:
        * PATH, the original filename (to be read); and

        * a temporary file-name.

     If PATH is locked by other than CERTIFICATE, or if CERTIFICATE is
     supplied and PATH is not locked, then `transact-file-replacement'
     returns #f.  If CERTIFICATE is not supplied, then,
     `transact-file-replacement' creates temporary (Emacs and Word)
     locks for PATH during the transaction.  The lock status of PATH
     will be restored before `transact-file-replacement' returns.

     `transact-file-replacement' calls PROC with PATH (which should not
     be modified) and a temporary file path to be written.  If PROC
     returns any value other than #t, then the file named by PATH is
     not altered and `transact-file-replacement' returns #f.
     Otherwise, `emacs:backup-name' is called with PATH and
     BACKUP-STYLE.  If it returns a string, then PATH is renamed to it.

     Finally, the temporary file is renamed PATH.
     `transact-file-replacement' returns #t if PATH was successfully
     replaced; and #f otherwise.

Identification
..............

 -- Function: user-email-address
     `user-email-address' returns a string of the form
     `username@hostname'.  If this e-mail address cannot be obtained,
     #f is returned.


File: slib.info,  Node: CVS,  Prev: Transactions,  Up: System Interface

7.6.3 CVS
---------

`(require 'cvs)' 

 -- Function: cvs-files directory/
     Returns a list of the local pathnames (with prefix DIRECTORY/) of
     all CVS controlled files in DIRECTORY/ and in DIRECTORY/'s
     subdirectories.

 -- Function: cvs-directories directory/
     Returns a list of all of DIRECTORY/ and all DIRECTORY/'s CVS
     controlled subdirectories.

 -- Function: cvs-root path/
     Returns the (string) contents of PATH/CVS/Root; or `(getenv
     "CVSROOT")' if Root doesn't exist.

 -- Function: cvs-repository directory/
     Returns the (string) contents of DIRECTORY/CVS/Root appended with
     DIRECTORY/CVS/Repository; or #f if DIRECTORY/CVS/Repository
     doesn't exist.

 -- Procedure: cvs-set-root! new-root directory/
     Writes NEW-ROOT to file CVS/Root of DIRECTORY/.

 -- Procedure: cvs-set-roots! new-root directory/
     Writes NEW-ROOT to file CVS/Root of DIRECTORY/ and all its CVS
     subdirectories.

 -- Function: cvs-vet directory/
     Signals an error if CVS/Repository or CVS/Root files in DIRECTORY/
     or any subdirectory do not match.


File: slib.info,  Node: Extra-SLIB Packages,  Prev: System Interface,  Up: Other Packages

7.7 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:
   * Because it requires special hardware or software which is not
     universal.

   * Because it is large and of limited interest to most Scheme users.

   * Because it has copying terms different enough from the other SLIB
     packages that its inclusion would cause confusion.

   * Because it is an application program, rather than a library module.

   * Because I have been too busy to integrate it.

  Once an optional package is installed (and an entry added to
`*catalog*'), the `require' mechanism allows it to be called up and           |
used as easily as any other SLIB package.  Some optional packages (for        |
which `*catalog*' already has entries) available from SLIB sites are:         |

SLIB-PSD
     is a portable debugger for Scheme (requires emacs editor).

     http://swiss.csail.mit.edu/ftpdir/scm/slib-psd1-3.tar.gz

     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

     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
     http://www.cs.tut.fi/staff/pk/scheme/psd/article/article.html

SCHELOG
     is an embedding of Prolog in Scheme.
     http://www.ccs.neu.edu/~dorai/schelog/schelog.html

JFILTER
     is a Scheme program which converts text among the JIS, EUC, and
     Shift-JIS Japanese character sets.
     http://www.sci.toyama-u.ac.jp/~iwao/Scheme/Jfilter/index.html


File: slib.info,  Node: About SLIB,  Next: Index,  Prev: Other Packages,  Up: Top

8 About SLIB
************

More people than I can name have contributed to SLIB.  Thanks to all of
you!

     SLIB 3b1, released February 2008.                                        |
     Aubrey Jaffer <agj @ alum.mit.edu>

  Current information about SLIB can be found on SLIB's "WWW" home page:

               `http://swiss.csail.mit.edu/~jaffer/SLIB'

  SLIB is part of the GNU project.                                            |
                                                                              |
* 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::


File: slib.info,  Node: Installation,  Next: The SLIB script,  Prev: About SLIB,  Up: About SLIB

8.1 Installation
================

There are five parts to installation:

   * Unpack the SLIB distribution.

   * Install documentation and `slib' script.

   * Configure the Scheme implementation(s) to locate the SLIB directory      |
     and implementation directories.                                          |

   * Arrange for Scheme implementation to load its SLIB initialization
     file.

   * Build the SLIB catalog for the Scheme implementation.

8.1.1 Unpacking the SLIB Distribution
-------------------------------------

If the SLIB distribution is a GNU/Linux RPM, it will create the SLIB
directory `/usr/share/slib'.

  If the SLIB distribution is a ZIP file, unzip the distribution to
create the SLIB directory.  Locate this `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 `/usr/share/slib', `/usr/local/lib/slib', or
`/usr/lib/slib'.  If you know where SLIB should go on other platforms,
please inform agj @ alum.mit.edu.

8.1.2 Install documentation and slib script
-------------------------------------------

     make infoz
     make install

8.1.3 Configure Scheme Implementation to Locate SLIB
----------------------------------------------------

If the Scheme implementation supports `getenv', then the value of the
shell environment variable SCHEME_LIBRARY_PATH will be used for
`(library-vicinity)' if it is defined.  Currently, Bigloo, Chez, Elk,         |
Gambit, Guile, Jscheme, Larceny, MITScheme, MzScheme, RScheme, STk,           |
VSCM, and SCM support `getenv'.  Scheme48 supports `getenv' but does          |
not use it for determining `library-vicinity'.  (That is done from the        |
Makefile.)                                                                    |

  The `(library-vicinity)' can also be set from the SLIB initialization       |
file or by implementation-specific means.                                     |
                                                                              |
  Support for locating an implementation's auxiliary directory is uneven      |
among implementations.  Also, the person installing SLIB may not have         |
write permission to some of these directories (necessary for writing          |
slibcat).  Therefore, those implementations supporting `getenv' (except       |
SCM and Scheme48) provide a means for specifying the                          |
`implementation-vicinity' through environment variables.  Define the          |
indicated environment variable to the pathname (with trailing slash or        |
backslash) of the desired directory.  Do not use `slib/' as an                |
implementation-vicinity!                                                      |
                                                                              |
Bigloo                 BIGLOO_IMPLEMENTATION_PATH                             |
Chez                   CHEZ_IMPLEMENTATION_PATH                               |
ELK                    ELK_IMPLEMENTATION_PATH                                |
Gambit                 GAMBIT_IMPLEMENTATION_PATH                             |
Guile                  GUILE_IMPLEMENTATION_PATH                              |
Jscheme                JSCHEME_IMPLEMENTATION_PATH                            |
MIT-Scheme             MITSCHEME_IMPLEMENTATION_PATH                          |
MzScheme               MZSCHEME_IMPLEMENTATION_PATH                           |
RScheme                RSCHEME_IMPLEMENTATION_PATH                            |
STk                    STK_IMPLEMENTATION_PATH                                |
Vscm                   VSCM_IMPLEMENTATION_PATH                               |

8.1.4 Loading SLIB Initialization File
--------------------------------------

Check the manifest in `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 `software-type',
`scheme-implementation-version', `implementation-vicinity', and
`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 `load' this initialization file.

8.1.5 Build New SLIB Catalog for Implementation
-----------------------------------------------

When SLIB is first used from an implementation, a file named `slibcat'
is written to the `implementation-vicinity' for that implementation.
Because users may lack permission to write in
`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:

     (require 'new-catalog)

  The catalog also supports color-name dictionaries.  With an
SLIB-installed scheme implementation, type:
     (require 'color-names)
     (make-slib-color-name-db)
     (require 'new-catalog)
     (slib:exit)

8.1.6 Implementation-specific Instructions
------------------------------------------

Multiple implementations of Scheme can all use the same SLIB directory.
Simply configure each implementation's initialization file as outlined
above.

 -- 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.

 -- Implementation: Larceny                                                   |
     Starting with version 0.96, Larceny contains its own SLIB                |
     initialization file, loaded by `(require 'srfi-96)'.  If                 |
     SCHEME_LIBRARY_PATH is not set, then Larceny looks for an `slib'         |
     subdirectory of a directory in the list returned by                      |
     `(current-require-path)'                                                 |
                                                                              |
          larceny -- -e "(require 'srfi-96)"                                  |
                                                                              |
 -- Implementation: ELK                                                       |
          elk -i -l ${SCHEME_LIBRARY_PATH}elk.init                            |
                                                                              |
 -- Implementation: PLT Scheme
 -- Implementation: DrScheme
 -- Implementation: MzScheme
     The `init.ss' file in the _slibinit_ collection is an SLIB
     initialization file.  To run SLIB in MzScheme:                           |

          mzscheme -f ${SCHEME_LIBRARY_PATH}mzscheme.init                     |

 -- Implementation: MIT Scheme
          scheme -load ${SCHEME_LIBRARY_PATH}mitscheme.init                   |

 -- Implementation: Gambit-C 3.0
          gsi -:s ${SCHEME_LIBRARY_PATH}gambit.init -                         |
                                                                              |
 -- Implementation: SISC                                                      |
          sisc -e "(load \"${SCHEME_LIBRARY_PATH}sisc.init\")" --             |
                                                                              |
 -- Implementation: Kawa                                                      |
          kawa -f ${SCHEME_LIBRARY_PATH}kawa.init --                          |

 -- Implementation: Guile
     Guile versions 1.6 and earlier link to an archaic SLIB version.  In
     RedHat or Fedora installations:

          rm /usr/share/guile/slib
          ln -s ${SCHEME_LIBRARY_PATH} /usr/share/guile/slib

     In Debian installations:

          rm /usr/share/guile/1.6/slib
          ln -s ${SCHEME_LIBRARY_PATH} /usr/share/guile/1.6/slib

     `${SCHEME_LIBRARY_PATH}' is where SLIB gets installed.

     Guile with SLIB can then be started thus:

          guile -l ${SCHEME_LIBRARY_PATH}guile.init                           |

 -- Implementation: Scheme48
     To make a Scheme48 image for an installation under `<prefix>',

       1. `cd' to the SLIB directory

       2. type `make prefix=<prefix> slib48'.

       3. To install the image, type `make prefix=<prefix> install48'.
          This will also create a shell script with the name `slib48'
          which will invoke the saved image.

 -- Implementation: VSCM
     From: Matthias Blume <blume @ cs.Princeton.EDU>
     Date: Tue, 1 Mar 1994 11:42:31 -0500

     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 `vscm.init' as an explicit command line
     argument.  Since this is not very nice I would recommend the
     following installation procedure:

       1. run scheme

       2. `(load "vscm.init")'

       3. `(slib:dump "dumpfile")'

       4. mv dumpfile place-where-vscm-standard-bootfile-resides.  For        |
          example:                                                            |

          `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.                       |


File: slib.info,  Node: The SLIB script,  Next: Porting,  Prev: Installation,  Up: About SLIB

8.2 The SLIB script
===================

SLIB comes with shell script for Unix platforms.

      slib  [ scheme | scm | gsi | mzscheme | guile
            | scheme48 | scmlit | elk | sisc | kawa ]

Starts an interactive Scheme-with-SLIB session.

The optional argument to the `slib' script is the Scheme implementation
to run.  Absent the argument, it searches for implementations in the
above order.


File: slib.info,  Node: Porting,  Next: Coding Guidelines,  Prev: The SLIB script,  Up: About SLIB

8.3 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
     `IEEE Std 1178-1990',
     `Revised^4 Report on the Algorithmic Language Scheme', or
     `Revised^5 Report on the Algorithmic Language Scheme'
  in order to support SLIB.  (1)

  `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 `.init'
appended.  For instance, if you were porting `foo-scheme' then the
initialization file might be called `foo.init'.

  Your customized version should then be loaded as part of your scheme
implementation's initialization.  It will load `require.scm' from the
library; this will allow the use of `provide', `provided?', and
`require' along with the "vicinity" functions (these functions are
documented in the sections *Note Feature:: and *Note Require::).  The
rest of the library will then be accessible in a system independent
fashion.

  Please mail new working configuration files to `agj @ alum.mit.edu'
so that they can be included in the SLIB distribution.

  ---------- Footnotes ----------

  (1) If you are porting a `Revised^3 Report on the Algorithmic
Language Scheme' implementation, then you will need to finish writing
`sc4sc3.scm' and `load' it from your initialization file.


File: slib.info,  Node: Coding Guidelines,  Next: Copyrights,  Prev: Porting,  Up: About SLIB

8.4 Coding Guidelines
=====================

All library packages are written in IEEE P1178 Scheme and assume that a
configuration file and `require.scm' package have already been loaded.
Other versions of Scheme can be supported in library packages as well
by using, for example, `(provided? 'r3rs)' or `(require 'r3rs)' (*note
Require::).  

  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:

     (define module-name:foo foo)

  The module name and `:' 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 (*note Schmooz::) or `;@' at the beginning of the line
immediately preceding the definition (`define', `define-syntax', or
`defmacro').  Modules, exports and other relevant issues are discussed
in *Note Compiling Scheme::.

  Code submitted for inclusion in SLIB should not duplicate (more than
one) routines already in SLIB files.  Use `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 _before_ you send me the
code!

8.4.1 Modifications
-------------------

Please document your changes.  A line or two for `ChangeLog' is
sufficient for simple fixes or extensions.  Look at the format of
`ChangeLog' to see what information is desired.  Please send me `diff'
files from the latest SLIB distribution (remember to send `diff's of
`slib.texi' and `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 `slib.texi' and `*.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 _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.


File: slib.info,  Node: Copyrights,  Next: About this manual,  Prev: Coding Guidelines,  Up: About SLIB

8.5 Copyrights
==============

This section has instructions for SLIB authors regarding copyrights.  

  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 `require.scm' and
`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.

8.5.1 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.

     I, <MY-NAME>, hereby affirm that I have placed the software
     package <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.
                                                     SIGNATURE AND DATE

  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.

8.5.2 Explicit copying terms
----------------------------

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:

   * Arrange that your name appears in a copyright line for the
     appropriate year.  Multiple copyright lines are acceptable.

   * With your copyright line, specify any terms you require to be
     different from those already in the file.

   * 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.

8.5.3 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:

     <EMPLOYER> Corporation hereby disclaims all copyright interest in
     the program <PROGRAM> written by <NAME>.

     <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.

     <SIGNATURE AND DATE>,
     <NAME>, <TITLE>, <EMPLOYER> Corporation


File: slib.info,  Node: About this manual,  Prev: Copyrights,  Up: About SLIB

8.6 About this manual
=====================
                                                                              |
   * 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.

   * Examples in this text were produced using the `scm' Scheme
     implementation.

   * At the beginning of each section, there is a line that looks like:       |
          (require 'feature)                                                  |
     Include this line in your code prior to using the package.               |
                                                                              |
* Menu:
                                                                              |
* GNU Free Documentation License::


File: slib.info,  Node: GNU Free Documentation License,  Prev: About this manual,  Up: About this manual
                                                                              |
8.6.1 GNU Free Documentation License                                          |
------------------------------------                                          |

                      Version 1.2, November 2002

     Copyright (C) 2000,2001,2002 Free Software Foundation, Inc.
     51 Franklin St, Fifth Floor, Boston, MA  02110-1301, USA                 |

     Everyone is permitted to copy and distribute verbatim copies
     of this license document, but changing it is not allowed.

  0. PREAMBLE

     The purpose of this License is to make a manual, textbook, or other
     functional and useful document "free" in the sense of freedom: to
     assure everyone the effective freedom to copy and redistribute it,
     with or without modifying it, either commercially or
     noncommercially.  Secondarily, this License preserves for the
     author and publisher a way to get credit for their work, while not
     being considered responsible for modifications made by others.

     This License is a kind of "copyleft", which means that derivative
     works of the document must themselves be free in the same sense.
     It complements the GNU General Public License, which is a copyleft
     license designed for free software.

     We have designed this License in order to use it for manuals for
     free software, because free software needs free documentation: a
     free program should come with manuals providing the same freedoms
     that the software does.  But this License is not limited to
     software manuals; it can be used for any textual work, regardless
     of subject matter or whether it is published as a printed book.
     We recommend this License principally for works whose purpose is
     instruction or reference.

  1. APPLICABILITY AND DEFINITIONS

     This License applies to any manual or other work, in any medium,
     that contains a notice placed by the copyright holder saying it
     can be distributed under the terms of this License.  Such a notice
     grants a world-wide, royalty-free license, unlimited in duration,
     to use that work under the conditions stated herein.  The
     "Document", below, refers to any such manual or work.  Any member
     of the public is a licensee, and is addressed as "you".  You
     accept the license if you copy, modify or distribute the work in a
     way requiring permission under copyright law.

     A "Modified Version" of the Document means any work containing the
     Document or a portion of it, either copied verbatim, or with
     modifications and/or translated into another language.

     A "Secondary Section" is a named appendix or a front-matter section
     of the Document that deals exclusively with the relationship of the
     publishers or authors of the Document to the Document's overall
     subject (or to related matters) and contains nothing that could
     fall directly within that overall subject.  (Thus, if the Document
     is in part a textbook of mathematics, a Secondary Section may not
     explain any mathematics.)  The relationship could be a matter of
     historical connection with the subject or with related matters, or
     of legal, commercial, philosophical, ethical or political position
     regarding them.

     The "Invariant Sections" are certain Secondary Sections whose
     titles are designated, as being those of Invariant Sections, in
     the notice that says that the Document is released under this
     License.  If a section does not fit the above definition of
     Secondary then it is not allowed to be designated as Invariant.
     The Document may contain zero Invariant Sections.  If the Document
     does not identify any Invariant Sections then there are none.

     The "Cover Texts" are certain short passages of text that are
     listed, as Front-Cover Texts or Back-Cover Texts, in the notice
     that says that the Document is released under this License.  A
     Front-Cover Text may be at most 5 words, and a Back-Cover Text may
     be at most 25 words.

     A "Transparent" copy of the Document means a machine-readable copy,
     represented in a format whose specification is available to the
     general public, that is suitable for revising the document
     straightforwardly with generic text editors or (for images
     composed of pixels) generic paint programs or (for drawings) some
     widely available drawing editor, and that is suitable for input to
     text formatters or for automatic translation to a variety of
     formats suitable for input to text formatters.  A copy made in an
     otherwise Transparent file format whose markup, or absence of
     markup, has been arranged to thwart or discourage subsequent
     modification by readers is not Transparent.  An image format is
     not Transparent if used for any substantial amount of text.  A
     copy that is not "Transparent" is called "Opaque".

     Examples of suitable formats for Transparent copies include plain
     ASCII without markup, Texinfo input format, LaTeX input format,
     SGML or XML using a publicly available DTD, and
     standard-conforming simple HTML, PostScript or PDF designed for
     human modification.  Examples of transparent image formats include
     PNG, XCF and JPG.  Opaque formats include proprietary formats that
     can be read and edited only by proprietary word processors, SGML or
     XML for which the DTD and/or processing tools are not generally
     available, and the machine-generated HTML, PostScript or PDF
     produced by some word processors for output purposes only.

     The "Title Page" means, for a printed book, the title page itself,
     plus such following pages as are needed to hold, legibly, the
     material this License requires to appear in the title page.  For
     works in formats which do not have any title page as such, "Title
     Page" means the text near the most prominent appearance of the
     work's title, preceding the beginning of the body of the text.

     A section "Entitled XYZ" means a named subunit of the Document
     whose title either is precisely XYZ or contains XYZ in parentheses
     following text that translates XYZ in another language.  (Here XYZ
     stands for a specific section name mentioned below, such as
     "Acknowledgements", "Dedications", "Endorsements", or "History".)
     To "Preserve the Title" of such a section when you modify the
     Document means that it remains a section "Entitled XYZ" according
     to this definition.

     The Document may include Warranty Disclaimers next to the notice
     which states that this License applies to the Document.  These
     Warranty Disclaimers are considered to be included by reference in
     this License, but only as regards disclaiming warranties: any other
     implication that these Warranty Disclaimers may have is void and
     has no effect on the meaning of this License.

  2. VERBATIM COPYING

     You may copy and distribute the Document in any medium, either
     commercially or noncommercially, provided that this License, the
     copyright notices, and the license notice saying this License
     applies to the Document are reproduced in all copies, and that you
     add no other conditions whatsoever to those of this License.  You
     may not use technical measures to obstruct or control the reading
     or further copying of the copies you make or distribute.  However,
     you may accept compensation in exchange for copies.  If you
     distribute a large enough number of copies you must also follow
     the conditions in section 3.

     You may also lend copies, under the same conditions stated above,
     and you may publicly display copies.

  3. COPYING IN QUANTITY

     If you publish printed copies (or copies in media that commonly
     have printed covers) of the Document, numbering more than 100, and
     the Document's license notice requires Cover Texts, you must
     enclose the copies in covers that carry, clearly and legibly, all
     these Cover Texts: Front-Cover Texts on the front cover, and
     Back-Cover Texts on the back cover.  Both covers must also clearly
     and legibly identify you as the publisher of these copies.  The
     front cover must present the full title with all words of the
     title equally prominent and visible.  You may add other material
     on the covers in addition.  Copying with changes limited to the
     covers, as long as they preserve the title of the Document and
     satisfy these conditions, can be treated as verbatim copying in
     other respects.

     If the required texts for either cover are too voluminous to fit
     legibly, you should put the first ones listed (as many as fit
     reasonably) on the actual cover, and continue the rest onto
     adjacent pages.

     If you publish or distribute Opaque copies of the Document
     numbering more than 100, you must either include a
     machine-readable Transparent copy along with each Opaque copy, or
     state in or with each Opaque copy a computer-network location from
     which the general network-using public has access to download
     using public-standard network protocols a complete Transparent
     copy of the Document, free of added material.  If you use the
     latter option, you must take reasonably prudent steps, when you
     begin distribution of Opaque copies in quantity, to ensure that
     this Transparent copy will remain thus accessible at the stated
     location until at least one year after the last time you
     distribute an Opaque copy (directly or through your agents or
     retailers) of that edition to the public.

     It is requested, but not required, that you contact the authors of
     the Document well before redistributing any large number of
     copies, to give them a chance to provide you with an updated
     version of the Document.

  4. MODIFICATIONS

     You may copy and distribute a Modified Version of the Document
     under the conditions of sections 2 and 3 above, provided that you
     release the Modified Version under precisely this License, with
     the Modified Version filling the role of the Document, thus
     licensing distribution and modification of the Modified Version to
     whoever possesses a copy of it.  In addition, you must do these
     things in the Modified Version:

       A. Use in the Title Page (and on the covers, if any) a title
          distinct from that of the Document, and from those of
          previous versions (which should, if there were any, be listed
          in the History section of the Document).  You may use the
          same title as a previous version if the original publisher of
          that version gives permission.

       B. List on the Title Page, as authors, one or more persons or
          entities responsible for authorship of the modifications in
          the Modified Version, together with at least five of the
          principal authors of the Document (all of its principal
          authors, if it has fewer than five), unless they release you
          from this requirement.

       C. State on the Title page the name of the publisher of the
          Modified Version, as the publisher.

       D. Preserve all the copyright notices of the Document.

       E. Add an appropriate copyright notice for your modifications
          adjacent to the other copyright notices.

       F. Include, immediately after the copyright notices, a license
          notice giving the public permission to use the Modified
          Version under the terms of this License, in the form shown in
          the Addendum below.

       G. Preserve in that license notice the full lists of Invariant
          Sections and required Cover Texts given in the Document's
          license notice.

       H. Include an unaltered copy of this License.

       I. Preserve the section Entitled "History", Preserve its Title,
          and add to it an item stating at least the title, year, new
          authors, and publisher of the Modified Version as given on
          the Title Page.  If there is no section Entitled "History" in
          the Document, create one stating the title, year, authors,
          and publisher of the Document as given on its Title Page,
          then add an item describing the Modified Version as stated in
          the previous sentence.

       J. Preserve the network location, if any, given in the Document
          for public access to a Transparent copy of the Document, and
          likewise the network locations given in the Document for
          previous versions it was based on.  These may be placed in
          the "History" section.  You may omit a network location for a
          work that was published at least four years before the
          Document itself, or if the original publisher of the version
          it refers to gives permission.

       K. For any section Entitled "Acknowledgements" or "Dedications",
          Preserve the Title of the section, and preserve in the
          section all the substance and tone of each of the contributor
          acknowledgements and/or dedications given therein.

       L. Preserve all the Invariant Sections of the Document,
          unaltered in their text and in their titles.  Section numbers
          or the equivalent are not considered part of the section
          titles.

       M. Delete any section Entitled "Endorsements".  Such a section
          may not be included in the Modified Version.

       N. Do not retitle any existing section to be Entitled
          "Endorsements" or to conflict in title with any Invariant
          Section.

       O. Preserve any Warranty Disclaimers.

     If the Modified Version includes new front-matter sections or
     appendices that qualify as Secondary Sections and contain no
     material copied from the Document, you may at your option
     designate some or all of these sections as invariant.  To do this,
     add their titles to the list of Invariant Sections in the Modified
     Version's license notice.  These titles must be distinct from any
     other section titles.

     You may add a section Entitled "Endorsements", provided it contains
     nothing but endorsements of your Modified Version by various
     parties--for example, statements of peer review or that the text
     has been approved by an organization as the authoritative
     definition of a standard.

     You may add a passage of up to five words as a Front-Cover Text,
     and a passage of up to 25 words as a Back-Cover Text, to the end
     of the list of Cover Texts in the Modified Version.  Only one
     passage of Front-Cover Text and one of Back-Cover Text may be
     added by (or through arrangements made by) any one entity.  If the
     Document already includes a cover text for the same cover,
     previously added by you or by arrangement made by the same entity
     you are acting on behalf of, you may not add another; but you may
     replace the old one, on explicit permission from the previous
     publisher that added the old one.

     The author(s) and publisher(s) of the Document do not by this
     License give permission to use their names for publicity for or to
     assert or imply endorsement of any Modified Version.

  5. COMBINING DOCUMENTS

     You may combine the Document with other documents released under
     this License, under the terms defined in section 4 above for
     modified versions, provided that you include in the combination
     all of the Invariant Sections of all of the original documents,
     unmodified, and list them all as Invariant Sections of your
     combined work in its license notice, and that you preserve all
     their Warranty Disclaimers.

     The combined work need only contain one copy of this License, and
     multiple identical Invariant Sections may be replaced with a single
     copy.  If there are multiple Invariant Sections with the same name
     but different contents, make the title of each such section unique
     by adding at the end of it, in parentheses, the name of the
     original author or publisher of that section if known, or else a
     unique number.  Make the same adjustment to the section titles in
     the list of Invariant Sections in the license notice of the
     combined work.

     In the combination, you must combine any sections Entitled
     "History" in the various original documents, forming one section
     Entitled "History"; likewise combine any sections Entitled
     "Acknowledgements", and any sections Entitled "Dedications".  You
     must delete all sections Entitled "Endorsements."

  6. COLLECTIONS OF DOCUMENTS

     You may make a collection consisting of the Document and other
     documents released under this License, and replace the individual
     copies of this License in the various documents with a single copy
     that is included in the collection, provided that you follow the
     rules of this License for verbatim copying of each of the
     documents in all other respects.

     You may extract a single document from such a collection, and
     distribute it individually under this License, provided you insert
     a copy of this License into the extracted document, and follow
     this License in all other respects regarding verbatim copying of
     that document.

  7. AGGREGATION WITH INDEPENDENT WORKS

     A compilation of the Document or its derivatives with other
     separate and independent documents or works, in or on a volume of
     a storage or distribution medium, is called an "aggregate" if the
     copyright resulting from the compilation is not used to limit the
     legal rights of the compilation's users beyond what the individual
     works permit.  When the Document is included in an aggregate, this
     License does not apply to the other works in the aggregate which
     are not themselves derivative works of the Document.

     If the Cover Text requirement of section 3 is applicable to these
     copies of the Document, then if the Document is less than one half
     of the entire aggregate, the Document's Cover Texts may be placed
     on covers that bracket the Document within the aggregate, or the
     electronic equivalent of covers if the Document is in electronic
     form.  Otherwise they must appear on printed covers that bracket
     the whole aggregate.

  8. TRANSLATION

     Translation is considered a kind of modification, so you may
     distribute translations of the Document under the terms of section
     4.  Replacing Invariant Sections with translations requires special
     permission from their copyright holders, but you may include
     translations of some or all Invariant Sections in addition to the
     original versions of these Invariant Sections.  You may include a
     translation of this License, and all the license notices in the
     Document, and any Warranty Disclaimers, provided that you also
     include the original English version of this License and the
     original versions of those notices and disclaimers.  In case of a
     disagreement between the translation and the original version of
     this License or a notice or disclaimer, the original version will
     prevail.

     If a section in the Document is Entitled "Acknowledgements",
     "Dedications", or "History", the requirement (section 4) to
     Preserve its Title (section 1) will typically require changing the
     actual title.

  9. TERMINATION

     You may not copy, modify, sublicense, or distribute the Document
     except as expressly provided for under this License.  Any other
     attempt to copy, modify, sublicense or distribute the Document is
     void, and will automatically terminate your rights under this
     License.  However, parties who have received copies, or rights,
     from you under this License will not have their licenses
     terminated so long as such parties remain in full compliance.

 10. FUTURE REVISIONS OF THIS LICENSE

     The Free Software Foundation may publish new, revised versions of
     the GNU Free Documentation License from time to time.  Such new
     versions will be similar in spirit to the present version, but may
     differ in detail to address new problems or concerns.  See
     `http://www.gnu.org/copyleft/'.

     Each version of the License is given a distinguishing version
     number.  If the Document specifies that a particular numbered
     version of this License "or any later version" applies to it, you
     have the option of following the terms and conditions either of
     that specified version or of any later version that has been
     published (not as a draft) by the Free Software Foundation.  If
     the Document does not specify a version number of this License,
     you may choose any version ever published (not as a draft) by the
     Free Software Foundation.

ADDENDUM: How to use this License for your documents                          |
====================================================                          |

To use this License in a document you have written, include a copy of
the License in the document and put the following copyright and license
notices just after the title page:

       Copyright (C)  YEAR  YOUR NAME.
       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, no Front-Cover Texts, and no Back-Cover
       Texts.  A copy of the license is included in the section entitled ``GNU
       Free Documentation License''.

  If you have Invariant Sections, Front-Cover Texts and Back-Cover
Texts, replace the "with...Texts." line with this:

         with the Invariant Sections being LIST THEIR TITLES, with
         the Front-Cover Texts being LIST, and with the Back-Cover Texts
         being LIST.

  If you have Invariant Sections without Cover Texts, or some other
combination of the three, merge those two alternatives to suit the
situation.

  If your document contains nontrivial examples of program code, we
recommend releasing these examples in parallel under your choice of
free software license, such as the GNU General Public License, to
permit their use in free software.


File: slib.info,  Node: Index,  Prev: About SLIB,  Up: Top

Index
*****

Procedure and Macro Index
*************************