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
|
<!DOCTYPE html>
<html lang="en">
<!-- documentation for s7 -->
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
<title>s7</title>
<style>
EM.red {color:red; font-style:normal}
EM.normal {font-style:normal}
EM.redb {color:red; font-weight: bold; font-style: normal}
EM.error {color:chocolate; font-style:normal}
EM.emdef {font-weight: bold; font-style: normal}
EM.green {color:green; font-style:normal}
EM.gray {color:#505050; font-style:normal}
EM.big {font-size: 20px; font-style: normal;}
EM.bigger {font-size: 30px; font-style: normal;}
EM.def {font-style: normal}
H1 {text-align: center}
UL {list-style-type: none}
A {text-decoration:none}
A:hover {text-decoration:underline}
A.def {font-weight: bold;
font-style: normal;
text-decoration:none;
}
PRE.indented {padding-left: 1.0cm;}
DIV.indented {background-color: #F8F8F0;
padding-left: 0.5cm;
padding-right: 0.5cm;
padding-top: 0.5cm;
padding-bottom: 0.5cm;
margin-bottom: 0.5cm;
border: 1px solid gray;
border-radius: 20px;
-moz-border-radius: 20px;
-webkit-border-radius: 20px;
}
DIV.small {font-size: small;
padding-left: 0.5cm;
padding-right: 0.5cm;
padding-bottom: 0.5cm;
}
DIV.header {margin-top: 60px;
margin-bottom: 30px;
border: 4px solid #00ff00; /* green */
background-color: #eefdee; /* lightgreen */
padding-left: 30px;
}
DIV.shortheader {margin-top: 30px;
margin-bottom: 10px;
border: 4px solid #00ff00; /* green */
background-color: #f5f5dc;
padding-left: 30px;
padding-top: 5px;
padding-bottom: 5px;
width: 20%;
}
DIV.topheader {margin-top: 10px;
margin-bottom: 40px;
border: 4px solid #00ff00; /* green */
background-color: #f5f5dc; /* beige */
font-family: 'Helvetica';
font-size: 30px;
text-align: center;
padding-top: 10px;
padding-bottom: 10px;
}
DIV.separator {margin-top: 30px;
margin-bottom: 10px;
border: 2px solid #00ff00; /* green */
background-color: #f5f5dc; /* beige */
padding-top: 4px;
width: 30%;
border-radius: 4px;
-moz-border-radius: 4px;
-webkit-border-radius: 4px;
}
DIV.smallseparator {margin-top: 10px;
margin-bottom: 10px;
border: 2px solid #00ff00; /* green */
background-color: #f5f5dc; /* beige */
padding-top: 4px;
width: 20%;
border-radius: 4px;
-moz-border-radius: 4px;
-webkit-border-radius: 4px;
text-align: center;
}
BODY.body {background-color: #ffffff; /* white */
margin-right: 20px;
margin-left: 20px;
}
DIV.listener {background-color: #f0f8ff;
font-family: 'Monospace';
padding-left: 6px;
padding-right: 6px;
padding-bottom: 4px;
margin-left: 1.0cm;
margin-right: 4.0cm;
border: 2px solid #a0a0a0;
}
LI.li_header {padding-top: 20px;}
</style>
</head>
<body class="body">
<!-- INDEX s7doc:s7 scheme -->
<div class="topheader" id="s7doc">s7
</div>
<p>s7 is a Scheme interpreter intended as an extension language for other applications.
It exists as just two files, s7.c and
s7.h, that want only to disappear into someone else's source tree. There are no libraries,
no run-time init files, and no configuration scripts.
It can be built as a stand-alone
interpreter (see <a href="s7-ffi.html#repl">repl</a>). s7test.scm is a regression test for s7.
A tarball is available: <a href="https://ccrma.stanford.edu/software/s7/s7.tar.gz">s7 tarball</a>.
There is an svn repository at sourceforge (the Snd project): <a href="https://sourceforge.net/p/snd/svn1/HEAD/tree/">Snd</a>,
and a git repository (just s7): git@cm-gitlab.stanford.edu:bil/s7.git <a href="https://cm-gitlab.stanford.edu/bil/s7.git">s7.git</a>.
Please ignore all other "s7" github sites. Christos Vagias created a web-assembly site with
a repl: https://github.com/actonDev/s7-playground/.
</p>
<p>
s7 is an extension language of Snd and sndlib (<a href="https://ccrma.stanford.edu/software/snd/index.html">snd</a>),
Rick Taube's Common Music (commonmusic at sourceforge), Kjetil Matheussen's Radium music editor, and Iain Duncan's Scheme for Max (or Pd).
There are X, Motif, and openGL bindings
in libxm in the Snd tarball, or at ftp://ccrma-ftp.stanford.edu/pub/Lisp/libxm.tar.gz.
</p>
<p>Although it is a descendant of tinyScheme, s7 is closest as a Scheme dialect to Guile 1.8.
I believe it is compatible with <a href="#s7vsr5rs">r5rs</a> and <a href="#r7rs">r7rs</a>: you can just ignore all the additions discussed in this file.
It has continuations,
ratios, complex numbers,
macros, keywords, hash-tables,
multiprecision arithmetic,
generalized set!, unicode, and so on.
It does not have syntax-rules or any of
its friends, and it thinks there is no such thing
as an inexact integer.
</p>
<p>This file assumes you know about Scheme and all its problems,
and want a quick tour of where s7 is different. (Well, it was quick once upon a time).
The main difference: if it's in s7, it's a first-class citizen of s7, and that includes
macros, environments, and syntactic values.
</p>
<br>
<blockquote>
<div class="indented">
<p>I originally used a small font for scholia, but now I have to squint
to read that tiny text, so less-than-vital commentaries are shown in the normal font, but
indented and on a sort of brownish background.
</p>
</div>
</blockquote>
<br>
<ul>
<li><a href="#multiprecision">arbitrary precision arithmetic</a>
<li><a href="#math">math functions</a>
<li><a href="#define*">define*, named let*</a>
<li><a href="#macros">define-macro</a>
<li><a href="#pws">setter</a>
<li><a href="#generalizedset">generic functions, generalized set!</a>
<li><a href="#multidimensionalvectors">multidimensional vectors</a>
<li><a href="#hashtables">hash tables</a>
<li><a href="#environments">environments</a>
<li><a href="#multiplevalues">multiple-values</a>
<li><a href="#callwithexit1">call-with-exit</a>
<li><a href="#format1">format</a>
<li><a href="#hooks">hooks</a>
<li><a href="#variableinfo">variable info</a>
<li><a href="#evalstring">eval</a>
<li><a href="#IO">IO and other OS functions</a>
<li><a href="#errors">errors</a>
<li><a href="#autoload">autoload</a>
<li><a href="#constants">define-constant</a>
<li><a href="#miscellanea">marvels and curiousities:</a>
<ul>
<li><a href="#loadpath">*load-path*</a>, <a href="#featureslist">*features*</a>, <a href="#sharpreaders">*#readers*</a>,
<li><a href="#makelist">make-list</a>, <a href="#charposition">char-position</a>, <a href="#keywords">keywords</a>
<li><a href="#symboltable">symbol-table</a>, <a href="#s7help">help</a>, <a href="#s7gc">gc</a>, <a href="#equivalentp">equivalent?</a>
<li><a href="#expansion">define-expansion</a>, <a href="#s7env">*s7*</a>, <a href="#s7vsr5rs">r5rs</a>, <a href="#r7rs">r7rs</a>,
<li><a href="#profiling">profiling</a>, <a href="#legolambda">legolambda</a>, etc...
</ul>
<li class="li_header"><a href="s7-ffi.html#FFIexamples">FFI examples</a>
<ul>
<li><a href="s7-ffi.html#repl">read-eval-print loop (and emacs)</a>
<li><a href="s7-ffi.html#defun">define a function with arguments and a returned value, and define a variable </a>
<li><a href="s7-ffi.html#defvar">call a Scheme function from C, and get/set Scheme variable values in C</a>
<li><a href="s7-ffi.html#juce">C++ and Juce</a>
<li><a href="s7-ffi.html#sndlib">load sndlib using the Xen functions and macros</a>
<li><a href="s7-ffi.html#pwstype">add a new Scheme type and a procedure with a setter</a>
<li><a href="s7-ffi.html#functionportexample">redirect display output to a C procedure</a>
<li><a href="s7-ffi.html#extendop">extend a built-in operator ("+" in this case)</a>
<li><a href="s7-ffi.html#definestar1">C-side define* (s7_define_function_star)</a>
<li><a href="s7-ffi.html#definemacro1">C-side define-macro (s7_define_macro)</a>
<li><a href="s7-ffi.html#definegeneric">define a generic function in C</a>
<li><a href="s7-ffi.html#signal">signal handling (C-C to break out of an infinite loop)</a>
<li><a href="s7-ffi.html#notify">notification in C that a Scheme variable has been set!</a>
<li><a href="s7-ffi.html#namespace">Load C defined stuff into a separate namespace</a>
<li><a href="s7-ffi.html#Cerrors">Error handling in C</a>
<li><a href="s7-ffi.html#testhook">Hooks in C and Scheme</a>
<li><a href="s7-ffi.html#dload">Load a C module dynamically</a>
<li><a href="s7-ffi.html#gmpex">gmp and friends</a>
<li><a href="s7-ffi.html#gdb">gdb</a>
<li><a href="s7-ffi.html#webassembly">WASM</a>
<li><a href="s7-ffi.html#ffinotes">FFI notes</a>
</ul>
<li class="li_header"><a href="s7-scm.html#s7examples">s7 examples</a>
<ul>
<li><a href="s7-scm.html#cload">cload.scm</a>
<ul>
<li><a href="s7-scm.html#libc">libc</a>
<li><a href="s7-scm.html#libgsl">libgsl</a>
<li><a href="s7-scm.html#libgdbm">libgdbm</a>
</ul>
<li><a href="s7-scm.html#case">case.scm</a>
<li><a href="s7-scm.html#debug">debug.scm</a>
<li><a href="s7-scm.html#lint">lint.scm</a>
<li><a href="s7-scm.html#schemerepl">repl.scm and nrepl.scm</a>
</ul>
</ul>
<div class="header" id="multiprecision"><h4>multiprecision arithmetic</h4></div>
<p>All numeric types, integers, ratios, reals, and complex numbers are supported.
The basic integer and real
types are defined in s7.h, defaulting to int64_t and double.
A ratio consists of two integers, a complex number consists of two reals.
pi is predefined.
s7 can be built with multiprecision support
for all types, using the gmp, mpfr, and mpc libraries (set WITH_GMP to 1 in s7.c).
If multiprecision arithmetic is
enabled, the following functions are included: bignum, and bignum?, and the variable (*s7* 'bignum-precision).
(*s7* 'bignum-precision) defaults to 128; it sets the number of bits each float takes.
pi automatically reflects the current (*s7* 'bignum-precision):
</p>
<pre class="indented">
> pi
<em class="gray">3.141592653589793238462643383279502884195E0</em>
> (*s7* 'bignum-precision)
<em class="gray">128</em>
> (set! (*s7* 'bignum-precision) 256)
<em class="gray">256</em>
> pi
<em class="gray">3.141592653589793238462643383279502884197169399375105820974944592307816406286198E0</em>
</pre>
<p>
<em class=def id="bignump">bignum?</em> returns #t if its argument is a big number of some type; I use "bignum"
for any big number, not just integers. To create a big number,
either include enough digits to overflow the default types, or use the <em class=def id="bignum">bignum</em> function.
Its argument is either a number which it casts to a bignum, or a string representing the desired number:
</p>
<pre class="indented">
> (bignum "123456789123456789")
<em class="gray">123456789123456789</em>
> (bignum "1.123123123123123123123123123")
<em class="gray">1.12312312312312312312312312300000000009E0</em>
</pre>
<p>For read-time bignums:
</p>
<pre class="indented">
(set! *#readers*
(cons (cons #\B (lambda (str)
(bignum (string->number (substring str 1)))))
*#readers*))
</pre>
<p>and now #B123 is the reader equivalent of (bignum 123).
</p>
<blockquote>
<div class="indented">
<p>In the non-gmp case, if s7 is built using doubles (s7_double in s7.h), the float "epsilon" is
around (expt 2 -53), or about 1e-16. In the gmp case, it is around (expt 2 (- (*s7* 'bignum-precision))).
So in the default case (precision = 128), using gmp:
</p>
<pre class="indented">
> (= 1.0 (+ 1.0 (expt 2.0 -128)))
<em class="gray">#t</em>
> (= 1.0 (+ 1.0 (expt 2.0 -127)))
<em class="gray">#f</em>
</pre>
<p>and in the non-gmp case:
</p>
<pre class="indented">
> (= 1.0 (+ 1.0 (expt 2 -53)))
<em class="gray">#t</em>
> (= 1.0 (+ 1.0 (expt 2 -52)))
<em class="gray">#f</em>
</pre>
<p>In the gmp case, integers and ratios are limited only by the size of memory,
but reals are limited by (*s7* 'bignum-precision). This means, for example, that
</p>
<pre class="indented">
> (floor 1e56) ; (*s7* 'bignum-precision) is 128
<em class="gray">99999999999999999999999999999999999999927942405962072064</em>
> (set! (*s7* 'bignum-precision) 256)
<em class="gray">256</em>
> (floor 1e56)
<em class="gray">100000000000000000000000000000000000000000000000000000000</em>
</pre>
<p>The non-gmp case is similar, but it's easy to find the edge cases:
</p>
<pre class="indented">
> (floor (+ 0.9999999995 (expt 2.0 23)))
<em class="gray">8388609</em>
</pre>
</div>
</blockquote>
<div class="header" id="math"><h4>math functions</h4></div>
<p>
s7 includes:
</p>
<ul>
<li>sinh, cosh, tanh, asinh, acosh, atanh
<li>logior, logxor, logand, lognot, logbit?, ash, integer-decode-float
<li>random
<li>nan?, infinite?, nan, nan-payload
</ul>
<p>
The random function can take any numeric argument, including 0.
Other math-related differences between s7 and r5rs:
</p>
<ul style="list-style-type:disc;">
<li>rational? and exact mean integer or ratio (i.e. not floating point), inexact means not exact.
<li>floor, ceiling, truncate, and round return (exact) integer results.
<li>"#" does not stand for an unknown digit. Is (= (+ #3# #20) ##5#)?
<li>the "@" complex number notation is not supported ("@" is an exponent marker in s7).
<li>"+i" is not considered a number; include the real part.
<li>modulo, remainder, and quotient take integer, ratio, or real arguments.
<li>lcm and gcd can take integer or ratio arguments.
<li>log takes an optional second argument, the base.
<li>'.' and an exponent can occur in a number in any base.
<li>rationalize returns a ratio!
<li>case is significant in numbers, as elsewhere: #b0 is 0, but #B0 is an error.
</ul>
<pre class="indented">
> (exact? 1.0)
<em class="gray">#f</em>
> (rational? 1.5)
<em class="gray">#f</em>
> (floor 1.4)
<em class="gray">1</em>
> (remainder 2.4 1)
<em class="gray">0.4</em>
> (modulo 1.4 1.0)
<em class="gray">0.4</em>
> (lcm 3/4 1/6)
<em class="gray">3/2</em>
> (log 8 2)
<em class="gray">3</em>
> (number->string 0.5 2)
<em class="gray">"0.1"</em>
> (string->number "0.1" 2)
<em class="gray">0.5</em>
> (rationalize 1.5)
<em class="gray">3/2</em>
> (complex 1/2 0)
<em class="gray">1/2</em>
> (logbit? 6 1) ; argument order, (logbit? int index), follows gmp, not CL
<em class="gray">#t</em>
</pre>
<p>See <a href="s7-scm.html#libgsl">cload and libgsl.scm</a> for easy access to GSL,
and similarly libm.scm for the C math library.
</p>
<blockquote>
<div class="indented">
<p>The exponent itself is always in base 10; this follows gmp usage.
Scheme normally uses "@" for its useless polar notation, but that
means <code>(string->number "1e1" 16)</code> is ambiguous — is the "e" a digit or an exponent marker?
In s7, "@" is an exponent marker.
</p>
<pre class="indented">
> (string->number "1e9" 2) ; (expt 2 9)
<em class="gray">512.0</em>
> (string->number "1e1" 12) ; "e" is not a digit in base 12
<em class="gray">#f</em>
> (string->number "1e1" 16) ; (+ (* 1 16 16) (* 14 16) 1)
<em class="gray">481</em>
> (string->number "1.2e1" 3); (* 3 (+ 1 2/3))
<em class="gray">5.0</em>
</pre>
</div>
<div class="indented">
<p>
The functions <b>nan</b> and <b>nan-payload</b> refer to the "payload" that can be associated with a NaN. s7's reader
can read NaNs with these payloads: <code>+nan.123</code> is a NaN with payload 123. s7 displays the NaN payload
in the same way: +nan.123. A NaN without any payload (or payload 0) is written +nan.0.
</p>
<pre class="indented">
> (nan 123)
<em class="gray">+nan.123</em>
> (nan-payload (nan 123))
<em class="gray">123</em>
</pre>
<p>
The nan function (and s7's reader) always returns a positive NaN.
</p>
</div>
<div class="indented">
<p>
What is <code>(/ 1.0 0.0)</code>? s7 gives a "division by zero" error here, and also in <code>(/ 1 0)</code>.
Guile returns +inf.0 in the first case, which seems reasonable, but a "numerical overflow" error in the second.
Slightly weirder is <code>(expt 0.0 0+i)</code>. Currently s7 returns 0.0, Guile returns +nan.0+nan.0i,
Clisp and sbcl throw an error. Everybody agrees that <code>(expt 0 0)</code> is 1, and Guile thinks
that <code>(expt 0.0 0.0)</code> is 1.0. But <code>(expt 0 0.0)</code> and <code>(expt 0.0 0)</code> return different
results in Guile (1 and 1.0), both are 0.0 in s7, the first is an error in Clisp, but the second returns 1,
and so on — what a mess! This mess was made a lot worse than it needs to be when the IEEE decreed that
0.0 equals -0.0, so we can't tell them apart, but that they produce different results:
</p>
<pre class="indented">
scheme@(guile-user)> (= -0.0 0.0)
<em class="gray">#t</em>
scheme@(guile-user)> (negative? -0.0)
<em class="gray">#f</em>
scheme@(guile-user)> (= (/ 1.0 0.0) (/ 1.0 -0.0))
<em class="gray">#f</em>
scheme@(guile-user)> (< (/ 1.0 -0.0) -1e100 1e100 (/ 1.0 0.0))
<em class="gray">#t</em>
</pre>
<p>
How can they be equal? In s7, the sign
of -0.0 is ignored, and they really are equal.
One other oddity: two floats can satisfy eq? and yet not be eqv?:
<code>(eq? +nan.0 +nan.0)</code> might be #t (it is unspecified), but <code>(eqv? +nan.0 +nan.0)</code> is #f.
The same problem afflicts memq and assq.
</p>
</div>
<div class="indented">
<p>The <em class=def id="random">random</em> function takes a range and an optional state, and returns a number
between zero and the range, of the same type as the range. It is perfectly reasonable
to use a range of 0, in which case random returns 0.
<em class=def id="randomstate">random-state</em> creates a new random state from a seed. If no seed is passed,
random-state returns the current state.
If no state is passed to random,
it uses some default state initialized from the current time. <em class=def id="randomstatep">random-state?</em> returns #t if passed a random state object.
</p>
<pre class="indented">
> (random 0)
<em class="gray">0</em>
> (random 1.0)
<em class="gray">0.86331198514245</em>
> (random 3/4)
<em class="gray">654/1129</em>
> (random 1+i)
<em class="gray">0.86300308872748+0.83601002730848i</em>
> (random -1.0)
<em class="gray">-0.037691127513267</em>
> (define r0 (random-state 1234))
<em class="gray">r0</em>
> (random 100 r0)
<em class="gray">94</em>
> (random 100 r0)
<em class="gray">19</em>
> (define r1 (random-state 1234))
<em class="gray">r1</em>
> (random 100 r1)
<em class="gray">94</em>
> (random 100 r1)
<em class="gray">19</em>
</pre>
<p>copy the random-state to save a spot in a random number sequence, or save the random-state as a list via
random-state->list, then to restart from that point, apply random-state to that list.
</p>
<p>In the gmp s7, random calls gmp's random number generator. There are
also many generators in GSL (see libgsl.scm). In the non-gmp s7, we use Marsaglia's MWC algorithm
which I think is a good compromise between quality and speed.
</p>
</div>
<div class="indented">
<p>I can't find the right tone for this section; this is the 400-th revision; I wish I were a better writer!
</p>
<p>In some Schemes,
"rational" means "could possibly be
expressed equally well as a ratio: floats are approximations". In s7 it's: "is actually expressed (at the scheme level) as a ratio (or an integer of course)";
otherwise "rational?" is the same as "real?":
</p>
<pre class="indented">
(not-s7)> (rational? (sqrt 2))
<em class="gray">#t</em>
</pre>
<p>That 1.0 is represented at the IEEE-float level as a sort of
ratio does not mean it has to be a scheme ratio; the two notions are independent.
</p>
<p>But that confusion is trivial compared to the completely nutty "inexact integer".
As I understand it, "inexact" originally meant "floating point", and "exact" meant integer or ratio of integers.
But words have a life of their own.
0.0 somehow became an "inexact" integer (although it can be represented exactly in floating
point).
+inf.0 must be an integer —
its fractional part is explicitly zero! But +nan.0...
And then there's:
</p>
<pre class="indented">
(not-s7)> (integer? 9007199254740993.1)
<em class="gray">#t</em>
</pre>
<p>
When does this matter? I often need to index into a vector, but the index is a float (a "real" in Scheme-speak: its
fractional part can be non-zero).
In one Scheme:
</p>
<pre class="indented">
(not-s7)> (vector-ref #(0) (floor 0.1))
<em class="gray">ERROR: Wrong type (expecting exact integer): 0.0 </em>; [why? "it's probably a programmer mistake"!]
</pre>
<p>Not to worry, I'll use inexact->exact:
</p>
<pre class="indented">
(not-s7)> (inexact->exact 0.1)
<em class="gray">3602879701896397/36028797018963968 </em>; [why? "floats are ratios"!]
</pre>
<p>So I end up using the verbose <code>(floor (inexact->exact ...))</code> everywhere, and even
then I have no guarantee that I'll get a legal vector index.
I have never seen any use made of the exact/inexact distinction — just
wild flailing to try get around it.
I think the whole idea is confused and useless, and leads
to verbose and buggy code.
If we discard it,
we can maintain backwards compatibility via:
</p>
<pre class="indented">
(define exact? rational?)
(define (inexact? x) (not (rational? x)))
(define inexact->exact rationalize) ; or floor
(define (exact->inexact x) (* x 1.0))
</pre>
<p>Standard Scheme's #i and #e are also useless because you can
have any number after, for example, #b:
</p>
<pre class="indented">
> #b1.1
<em class="gray">1.5</em>
> #b1e2
<em class="gray">4.0</em>
> #o17.5+i
<em class="gray">15.625+1i</em>
</pre>
<p>s7 uses #i for int-vector and does not implement #e.
Speaking of #b and friends, what should <code>(string->number "#xffff" 2)</code> return?
(For a different view of exact/inexact see https://www.deinprogramm.de/sperber/papers/numerical-tower.pdf).
</p>
</div>
</blockquote>
<div class="header" id="define*"><h4>define*, lambda*</h4></div>
<p><em class=def id="definestar">define*</em> and
<em class=def id="lambdastar">lambda*</em>
are extensions of define and lambda that make it easier
to deal with optional, keyword, and rest arguments.
The syntax is very simple: every parameter to define* has a default value
and is automatically available as a keyword argument. The default value
is either #f if unspecified, or given in a list whose first member is
the parameter name.
The last parameter
can be preceded by :rest or a dot to indicate that all other trailing arguments
should be packaged as a list under that parameter's name. A trailing or rest
parameter's default value is () and can't be specified in the declaration.
The rest parameter is not available as a keyword argument.
</p>
<pre class="indented">
(<em class=red>define*</em> (hi a (b 32) (c "hi")) (list a b c))
</pre>
<p>Here the parameter "a" defaults to #f, "b" to 32, etc.
When the function is called,
the parameter names are set from the values passed the function,
then any unset parameters are bound to their default values, evaluated in left-to-right order.
As the current argument list is scanned, any name that occurs as a keyword, :arg for example where the parameter name is arg,
sets that parameter's new value. Otherwise, as values occur, they
are plugged into the actual argument list based on their position, counting a keyword/value pair as one argument.
This is called an optional-key list in CLM. So, taking the function
above as an example:
</p>
<pre class="indented">
> (hi 1)
<em class="gray">(1 32 "hi")</em>
> (hi :b 2 :a 3)
<em class="gray">(3 2 "hi")</em>
> (hi 3 2 1)
<em class="gray">(3 2 1)</em>
</pre>
<p>See s7test.scm for many examples. (s7's define* is very close to srfi-89's define*).
To mark an argument as required, set its default value to a call on the error function:
</p>
<pre class="indented">
> (define* (f a (b (error 'unset-arg "f's b parameter not set"))) (list a b))
<em class="gray">f</em>
> (f 1 2)
(1 2)
> (f 1)
<em class=red>error</em><em class="gray">: f's b parameter not set</em>
</pre>
<blockquote>
<div class="indented">
<p>The combination of optional and keyword arguments is viewed with disfavor in the Lisp
community, but the problem is in CL's implementation of the idea, not the idea itself.
I've used the s7 style since around 1976, and have never found it confusing. The mistake
in CL is to require the optional arguments if a keyword argument occurs, and to consider them as distinct from the
keyword arguments. So everyone forgets and puts a keyword where CL expects a required-optional
argument. CL then does something ridiculous, and the programmer stomps around shouting about keywords, but the fault lies with CL.
If s7's way is considered too loose, one way to tighten it might be to insist that once a keyword
is used, only keyword argument pairs can follow.
</p>
</div>
<div class="indented">
<p>A natural companion of lambda* is named let*. In named let, the implicit function's
arguments have initial values, but thereafter, each call requires the full set of arguments.
Why not treat the initial values as default values?
</p>
<pre class="indented">
> (let* func ((i 1) (j 2))
(+ i j (if (> i 0) (func (- i 1)) 0)))
<em class="gray">5</em>
> (letrec ((func (lambda* ((i 1) (j 2))
(+ i j (if (> i 0) (func (- i 1)) 0)))))
(func))
<em class="gray">5</em>
</pre>
<p>This is consistent with the lambda* arguments because their defaults are
already set in left-to-right order, and as each parameter is set to its default value,
the binding is added to the default value expression environment (just as if it were a let*).
The let* name itself (the implicit function) is not defined until after the bindings
have been evaluated (as in named let).
</p>
<p>In CL, keyword default values are handled in the same way:
</p>
<pre class="indented">
> (defun foo (&key (a 0) (b (+ a 4)) (c (+ a 7))) (list a b c))
<em class="gray">FOO </em>
> (foo :b 2 :a 60)
<em class="gray">(60 2 67) </em>
</pre>
<p>In s7, we'd use:
</p>
<pre class="indented">
(define* (foo (a 0) (b (+ a 4)) (c (+ a 7))) (list a b c))
</pre>
<p>Also CL and s7 handle keywords as values in the same way:
</p>
<pre class="indented">
> (defun foo (&key a) a)
<em class="gray">FOO</em>
> (defvar x :a)
<em class="gray">X</em>
> (foo x 1)
<em class="gray">1</em>
</pre>
<pre class="indented">
> (define* (foo a) a)
<em class="gray">foo</em>
> (define x :a)
<em class="gray">:a</em>
> (foo x 1)
<em class="gray">1</em>
</pre>
<p>Keywords (named arguments) also work in named let*:
</p>
<pre class="indented">
> (let* loop ((i 0) (j 0))
(if (> i 3)
(+ i j)
(loop :j 2 :i (+ i 1))))
<em class="gray">6</em>
</pre>
</div>
<div class="indented">
<p>To try to catch what I believe are usually mistakes, I added two
error checks. One is triggered if you set the same parameter twice
in the same call, and the other if an unknown keyword is encountered
in the key position. To turn off these errors, add :allow-other-keys
at the end of the parameter list.
These problems arise in a case such as
</p>
<pre class="indented">
(define* (f (a 1) (b 2)) (list a b))
</pre>
<p>You could do any of the following by accident:
</p>
<pre class="indented">
(f 1 :a 2) ; what is a?
(f :b 1 2) ; what is b?
(f :c 3) ; did you really want a to be :c and b to be 3?
</pre>
<p>In the last case, to pass a keyword deliberately, either include the
argument keyword: <code>(f :a :c)</code>, or make the default value a keyword:
<code>(define* (f (a :c) ...))</code>, or set <code>(*s7* 'accept-all-keyword-arguments)</code>
to some true value.
See s7test.scm for many examples.
</p>
<p>What if two functions share a keyword argument,
and one wants to call the other, passing both arguments to the wrapper?
</p>
<pre class="indented">
(define* (f1 a) a) ; the wrappee
(define* (f2 a :rest b <em class=red>:allow-other-keys</em>) ; the wrapper
(+ a (apply f1 b)))
(f2 :a 3 :a 4) ; 7, b='(:a 4)
(let ((c :a))
(f2 c 3 c 4)) ; also 7
</pre>
<p>Since named let* is a form of lambda*, the prohibition of repeated variable names makes it different
from let*: <code>(let* ((a 1) (a 2)) a)</code> is 2, but <code>(let* loop ((a 1) (a 2)) a)</code> is an error.
If let* and named let* agreed in this, we'd have an inconsistency with lambda*. If all three allowed repeated
variables, the decision as to which parameter is intended becomes messy: <code>((lambda* (a a) a) 2 :a 3)</code>,
or <code>(let* loop ((a 1) (a 2)) (loop 2 :a 3))</code>.
CL and standard scheme accept repeated variables in let*, so I think the current
choice is the least surprising.
</p>
</div>
<div class="indented">
<p>s7's lambda* arglist handling is not the same as CL's lambda-list. First,
you can have more than one :rest parameter:
</p>
<pre class="indented">
> ((lambda* (:rest a :rest b) (map + a b)) 1 2 3 4 5)
<em class="gray">'(3 5 7 9)</em>
</pre>
<p>and second, the rest parameter, if any, takes up an argument slot just like any other
argument:
</p>
<pre class="indented">
> ((lambda* ((b 3) :rest x (c 1)) (list b c x)) 32)
<em class="gray">(32 1 ())</em>
> ((lambda* ((b 3) :rest x (c 1)) (list b c x)) 1 2 3 4 5)
<em class="gray">(1 3 (2 3 4 5))</em>
</pre>
<p>CL would agree with the first case if we used &key for 'c', but would give an error in the second.
Of course, the major difference is that s7 keyword arguments don't insist that the key be present.
The :rest argument is needed in cases like these because we can't use an expression
such as:
</p>
<pre class="indented">
> ((lambda* ((a 3) . b c) (list a b c)) 1 2 3 4 5)
<em class="red">error</em><em class="gray">: stray dot?</em>
> ((lambda* (a . (b 1)) b) 1 2) ; the reader turns the arglist into (a b 1)
<em class="red">error</em><em class="gray">: lambda* parameter '1 is a constant</em>
</pre>
<p>Yet another nit: the :rest argument is not considered a keyword argument, so
</p>
<pre class="indented">
> (define* (f :rest a) a)
<em class="gray">f</em>
> (f :a 1)
<em class="gray">(:a 1)</em>
</pre>
</div>
<!--
unknown key handling is not good, :allow-key-values?
(define* (f1 a) (list a))
(f1 :hi) -> (:hi)
(f1 ':hi) -> (:hi)
(f1 :a :hi) -> (:hi)
(define* (f2 a :allow-other-keys) (list a))
(f2 :hi) -> (:hi)
(define* (f3 a b :allow-other-keys) (list a b))
(f3 :hi 0) -> (#f #f)
(f3 :hi) => (:hi #f)
(define* (f4 a) (list (symbol->keyword a))) ; or string->keyword
(f4 'hi) -> (:hi)
(define* (f5 a)
((lambda* (hi) (list hi)) (symbol->keyword a) 32)) ; -> ((lambda* (hi) (list hi)) :hi 32) -> '(32)
(f5 'hi) -> (32)
(define* (f6 a b)
((lambda* (hi) (list hi)) a b))
(f6 :hi 1) -> unknown key :hi -> (unknown to f6)
(define* (f7 a b) (list a b))
(f7 :hi) -> (:hi #f)
(f7 0 :hi) -> (0 :hi)
(f7 :hi 0) -> unknown key
(f7 :a :hi) -> (:hi #f)
(f7 :a :hi 32) -> (:hi 32)
(define* (f8 a b)
((lambda* (hi ho) (list hi ho)) (symbol->keyword a) b))
(f8 'hi 32) -> (32 #f)
(f8 'ho 32) -> (#f 32)
another amusing lambda* case:
(call/cc
(lambda* (a (b (call/cc (lambda (c) c)))) ; even with-baffle still a loop (legit)
(b (call/cc (lambda (d) d)))))
;; equivalent to:
(let ((c (call/cc (lambda (c) c))))
(call/cc (lambda (a)
(c (call/cc (lambda (d) d))))))
-->
</blockquote>
<div class="header" id="macros"><h4>macros</h4></div>
<p>
<em class=def id="definemacro">define-macro</em>,
<em class=def id="definemacrostar">define-macro*</em>,
<em class=def id="definebacro">define-bacro</em>,
<em class=def id="definebacrostar">define-bacro*</em>,
<em class=def id="macroexpand">macroexpand</em>,
<em class=def id="gensym">gensym</em>,
<em class=def id="gensym?">gensym?</em>, and
<em class=def id="macrop">macro?</em>
implement the standard old-time macros.
The anonymous versions (analogous to lambda and lambda*) are
macro, macro*, bacro, and bacro*.
See s7test.scm for many examples of macros including such perennial favorites as
loop, dotimes, do*, enum, pushnew, and defstruct.
</p>
<pre class="indented">
> (define-macro (and-let* vars . body)
`(let ()
(and ,@(map (lambda (v)
`(define ,@v))
vars)
(begin ,@body))))
</pre>
<p>macroexpand can help debug a macro. I always forget that it
wants an expression:
</p>
<pre class="indented">
> (define-macro (add-1 arg) `(+ 1 ,arg))
<em class="gray">add-1</em>
> (macroexpand (add-1 32))
<em class="gray">(+ 1 32)</em>
</pre>
<p>gensym returns a symbol that is guaranteed to be unique. It takes an optional string argument
giving the new symbol name's prefix. gensym? returns #t if its argument is a symbol created by gensym.
</p>
<pre class="indented">
(define-macro (pop! sym)
(let ((v (<em class=red>gensym</em>)))
`(let ((,v (car ,sym)))
(set! ,sym (cdr ,sym))
,v)))
</pre>
<p>As in define*, the starred forms give optional and keyword arguments:
</p>
<pre class="indented">
> (define-macro* (add-2 a (b 2)) `(+ ,a ,b))
<em class="gray">add-2</em>
> (add-2 1 3)
<em class="gray">4</em>
> (add-2 1)
<em class="gray">3</em>
> (add-2 :b 3 :a 1)
<em class="gray">4</em>
</pre>
<blockquote>
<div class="indented">
<p>A macro is a first-class citizen of s7. You can
pass it as a function argument, apply it to a list, return it from a function,
call it recursively,
and assign it to a variable. You can even set its setter!
</p>
<pre class="indented">
> (define-macro (hi a) `(+ ,a 1))
<em class="gray">hi</em>
> (apply hi '(4))
<em class="gray">5</em>
> (define (fmac mac) (apply mac '(4)))
<em class="gray">fmac</em>
> (fmac hi)
<em class="gray">5</em>
> (define (fmac mac) (mac 4))
<em class="gray">fmac</em>
> (fmac hi)
<em class="gray">5</em>
> (define (make-mac)
(define-macro (hi a) `(+ ,a 1)))
<em class="gray">make-mac</em>
> (let ((x (make-mac)))
(x 2))
<em class="gray">3</em>
> (define-macro (ref v i) `(vector-ref ,v ,i))
<em class="gray">ref</em>
> (define-macro (set v i x) `(vector-set! ,v ,i ,x))
<em class="gray">set</em>
> (set! (setter ref) set)
<em class="gray">set</em>
> (let ((v (vector 1 2 3))) (set! (ref v 0) 32) v)
<em class="gray">#(32 2 3)</em>
</pre>
<p>To expand all the macros in a piece of code:
</p>
<pre class="indented">
(define-macro (fully-macroexpand form)
(list 'quote
(let expand ((form form))
(cond ((not (pair? form)) form)
((and (symbol? (car form))
(macro? (symbol->value (car form))))
(expand (apply macroexpand (list form))))
((and (eq? (car form) 'set!) ; look for (set! (mac ...) ...) and use mac's setter
(pair? (cdr form))
(pair? (cadr form))
(macro? (symbol->value (caadr form))))
(expand (apply macroexpand (list (cons (setter (symbol->value (caadr form)))
(append (cdadr form) (copy (cddr form))))))))
(else (cons (expand (car form)) (expand (cdr form))))))))
</pre>
<p>This does not always handle bacros correctly because their expansion can depend on the run-time
state.
</p>
</div>
<div class="indented">
<p>A bacro is a macro that expands its body and evaluates
the result in the calling environment.
</p>
<pre class="indented">
(define setf
(let ((args (gensym))
(name (gensym)))
(apply <em class=red>define-bacro</em> `((,name . ,args)
(unless (null? ,args)
(apply set! (car ,args) (cadr ,args) ())
(apply setf (cddr ,args)))))))
</pre>
<p>
The setf argument is a gensym (created when setf is defined) so that its name does not shadow any existing
variable. Bacros expand in the calling environment, and a normal argument name
might shadow something in that environment while the bacro is being expanded.
Similarly, if you introduce bindings in the bacro expansion code, you need to
keep track of which environment you want things to happen in. Use with-let
and gensym liberally.
stuff.scm has bacro-shaker which can find inadvertent name collisions,
but it is flighty and easily confused.
The calling environment itself is (outlet (curlet)) from within a bacro, so
</p>
<pre class="indented">
(define-bacro (holler)
`(format *stderr* "(~S~{ ~S ~S~^~})~%"
(let ((f (*function*)))
(if (pair? f) (car f) f))
(map (lambda (slot)
(values (symbol->keyword (car slot)) (cdr slot)))
(map values ,(outlet (curlet))))))
(define (f1 a b)
(holler)
(+ a b))
(f1 2 3) ; prints out "(f1 :a 2 :b 3)" and returns 5
</pre>
<p>
Since a bacro (normally) sheds its define-time environment:
</p>
<pre class="indented">
(define call-bac
(let ((<em class=red>x</em> 2))
(define-bacro (m a) `(+ ,a ,<em class=red>x</em>))))
> (call-bac 1)
<em class="red">error</em><em class="gray">: x: unbound variable</em>
</pre>
<p>
A macro here returns 3. The bacro can get its define-time environment (its closure)
via funclet, so define-macro is a special case of define-bacro! We can define
macros that work in all four ways: the expansion can happen in either the definition or calling environment,
as can the evaluation of that expansion. In a bacro, both happen in the calling environment
if we take no other action, and in a normal macro (define-macro), the expansion happens in the definition
environment, and the evaluation in the calling environment.
Here's a brief example of all four:
</p>
<pre class="indented">
(let ((x 1) (y 2))
(define-bacro (bac1 a)
`(+ ,x y ,a)) ; expand and eval in calling env
(let ((x 32) (y 64))
(bac1 3))) ; (with-let (inlet 'x 32 'y 64) (+ 32 y 3))
-> 99 ; with-let and inlet refer to <a href="#environments">environments</a>
(let ((x 1) (y 2)) ; this is like define-macro
(define-bacro (bac2 a)
(with-let (sublet (funclet bac2) :a a)
`(+ ,x y ,a))) ; expand in definition env, eval in calling env
(let ((x 32) (y 64))
(bac2 3))) ; (with-let (inlet 'x 32 'y 64) (+ 1 y 3))
-> 68
(let ((x 1) (y 2))
(define-bacro (bac3 a)
(let ((e (with-let (sublet (funclet bac3) :a a)
`(+ ,x y ,a))))
`(with-let ,(sublet (funclet bac3) :a a)
,e))) ; expand and eval in definition env
(let ((x 32) (y 64))
(bac3 3))) ; (with-let (inlet 'x 1 'y 2) (+ 1 y 3))
-> 6
(let ((x 1) (y 2))
(define-bacro (bac4 a)
(let ((e `(+ ,x y ,a)))
`(with-let ,(sublet (funclet bac4) :a a)
,e))) ; expand in calling env, eval in definition env
(let ((x 32) (y 64))
(bac4 3))) ; (with-let (inlet 'x 1 'y 2) (+ 32 y 3))
-> 37
</pre>
</div>
<div class="indented">
<p>Backquote (quasiquote) in s7 is almost trivial. Constants are unchanged, symbols are quoted,
",arg" becomes "arg", and ",@arg" becomes "(apply values arg)" — hooray for real multiple values!
It's almost as easy to write the actual macro body as the backquoted version of it.
</p>
<pre class="indented">
> (define-macro (hi a) `(+ 1 ,a))
<em class="gray">hi</em>
> (procedure-source hi)
<em class="gray">(lambda (a) (list-values '+ 1 a))</em>
> (define-macro (hi a) `(+ 1 ,@a))
<em class="gray">hi</em>
> (procedure-source hi)
<em class="gray">(lambda (a) (list-values '+ 1 (apply-values a)))</em>
</pre>
<p>list-values and apply-values are quasiquote helper functions described <a href="#listvalues">below</a>.
There is no unquote-splicing
macro in s7; ",@(...)" becomes "(unquote (apply-values ...))" at read-time. There shouldn't be any unquote
either. In Scheme the reader turns ,x into (unquote x), so:
</p>
<pre>
> (let (,'a) unquote)
<em class="gray">a</em>
> (let (, (lambda (x) (+ x 1))) ,,,,'3)
<em class="gray">7</em>
</pre>
<p>comma becomes a sort of symbol macro! I think I'll remove unquote; ,x and ,@x will still work
as expected, but there will not be any "unquote" or "unquote-splicing" in the resultant source code.
</p>
</div>
</blockquote>
<div class="smallseparator"><h4>hygienic macros</h4></div>
<div class="indented">
tldr: To make a macro hygienic, in the expanded code replace the names of things with the things themselves. For built-in values, use "#_",
e.g. "#_abs" rather than "abs". For macro-definition-time variables, use ",abs" rather than "abs". If possible, replace other names with gensyms.
As a last resort, use the explicit environment functions like let-ref and with-let.
</div>
<p>s7 macros are not hygienic. For example,
</p>
<pre class="indented">
> (define-macro (mac b)
`(let ((a 12))
(+ a ,b)))
<em class="gray">mac</em>
> (let ((a 1) (+ *)) (mac a))
<em class="gray">144</em>
</pre>
<p>This returns 144 because '+' has turned into '*', and 'a' is the internal 'a',
not the argument 'a'. We get <code>(* 12 12)</code> where we might have expected
<code>(+ 12 1)</code>.
Starting with the '+' problem,
as long as the redefinition of '+' is local (that is, it happens after the macro definition), we can unquote the +:
</p>
<pre class="indented">
> (define-macro (mac b)
`(let ((a 12))
(,+ a ,b))) ; ,+ picks up the definition-time +
<em class="gray">mac</em>
> (let ((a 1) (+ *)) (mac a))
<em class="gray">24 ; (+ a a) where a is 12</em>
</pre>
<p>But the unquote trick won't work if we have previously loaded some file that redefined '+'
at the top-level (so at macro definition time, + is *, but we want the built-in +).
Although this example is silly, the problem is real in Scheme
because Scheme has no reserved words and only one name space.
</p>
<pre class="indented">
> (define + *)
<em class="gray">+</em>
> (define (add a b) (+ a b))
<em class="gray">add</em>
> (add 2 3)
<em class="gray">6</em>
> (define (divide a b) (/ a b))
<em class="gray">divide</em>
> (divide 2 3)
<em class="gray">2/3</em>
> (set! / -) ; a bad idea — this turns off s7's optimizer
<em class="gray">-</em>
> (divide 2 3)
<em class="gray">-1</em>
</pre>
<p>Obviously macros are not the problem here. Since
we might be loading
code written by others, it's sometimes hard to tell what names
that code depends on or redefines.
We need a way to get the pristine (start-up, built-in) value of '+'.
One long-winded way in s7 uses <a href="#unlet">unlet</a>:
</p>
<pre class="indented">
> (define + *)
<em class="gray">+</em>
> (define (add a b) (with-let (unlet) (+ a b)))
<em class="gray">add</em>
> (add 2 3)
<em class="gray">5</em>
</pre>
<p>But this is hard to read, and we might want all three
values of a symbol, the start-up value, the definition-time value, and the
current value. The latter can be accessed with the bare symbol, the definition-time
value with unquote (','), and the start-up value with either unlet
or #_<name>. That is, #_+ is a reader macro for <code>(with-let (unlet) +)</code>.
</p>
<pre class="indented">
> (define-macro (mac b)
`(<em class=red>#_let</em> ((a 12))
(<em class=red>#_+</em> a ,b))) ; #_+ and #_let are start-up values
<em class="gray">mac</em>
> (let ((a 1) (+ *)) (mac a))
<em class="gray">24 ; (+ a a) where a is 12 and + is the start-up +</em>
;;; make + generic (there's a similar C-based example below)
> (define (+ . args)
(if (null? args) 0
(apply (if (number? (car args)) <em class=red>#_+ #_string-append</em>) args)))
<em class="gray">+</em>
> (+ 1 2)
<em class="gray">3</em>
> (+ "hi" "ho")
<em class="gray">"hiho"</em>
</pre>
<blockquote>
<div class="indented">
<p>Conceptually, #_<name> could be implemented via *#readers*:
</p>
<pre class="indented">
(set! *#readers*
(cons (cons #\_ (lambda (str)
(with-let (unlet)
(string->symbol (substring str 1)))))
*#readers*))
</pre>
<p>but s7 doesn't let you change the meaning of #\_; otherwise:
</p>
<pre class="indented">
(set! *#readers* (list (cons #\_ (lambda (str) (string->symbol (substring str 1))))))
</pre>
<p>and now #_ provides no protection:
</p>
<pre>
> (let ((+ -)) (#_+ 1 2))
<em class="gray">-1</em>
</pre>
<p>#t and #f (along with their stupid r7rs cousins #true and #false) are also not settable.
</p>
</div>
</blockquote>
<p>
So, now we have only the variable capture problem ('a' has been captured in the preceding examples).
This is the only thing that the gigantic "hygienic macro" systems actually deal with:
a microscopic problem that you'd think, from the hype, was up there with malaria and the
national debt. gensym is the standard approach:
</p>
<pre class="indented">
> (define-macro (mac b)
(let ((var (<em class=red>gensym</em>)))
`(#_let ((,var 12))
(#_+ ,var ,b))))
<em class="gray">mac</em>
> (let ((a 1) (+ *)) (mac a))
<em class="gray">13</em>
;; or use lambda:
> (define-macro (mac b)
`((lambda (b) (let ((a 12)) (#_+ a b))) ,b))
<em class="gray">mac</em>
> (let ((a 1) (+ *)) (mac a))
<em class="gray">13</em>
</pre>
<p>I think syntax-rules and its friends try to conjure up gensyms automatically, but
the real problem is not name collisions, but unspecified environments.
In s7 we have first-class environments, so you have complete
control over the environment at any point:
</p>
<pre>
(define-macro (mac b)
`(with-let (inlet 'b ,b)
(let ((a 12))
(+ a b))))
> (let ((a 1) (+ *)) (mac a))
<em class="gray">13</em>
(define-macro (mac1 . b) ; originally `(let ((a 12)) (+ a ,@b ,@b))
`(with-let (inlet 'e (curlet)) ; this 'e will not collide with the calling env
(let ((a 12)) ; nor will 'a (so no gensyms are needed etc)
(+ a (with-let e ,@b) (with-let e ,@b)))))
> (let ((a 1) (e 2)) (mac1 (display a) (+ a e)))
<em class="gray">18</em> ; (and it displays "11")
(define-macro (mac2 x) ; this will use mac2's definition environment for its body
`(with-let (sublet (funclet mac2) :x ,x)
(let ((a 12))
(+ a b x)))) ; a is always 12, b is whatever b happens to be in mac2's env
> (define b 10) ; this is mac2's b
<em class="gray">10</em>
> (let ((+ *) (a 1) (b 15)) (mac2 (+ a b)))
<em class="gray">37</em> ; mac2 uses its own a (12), b (10), and + (+)
; but (+ a b) is 15 because at that point + is *: (* 1 15)
</pre>
<p>Hygienic macros are trivial! Who needs syntax-rules?
Here's an example of the while macro in stuff.scm before and after
hygienification (using "exit" rather than "break"):
</p>
<pre>
(define-macro (unsafe-while test . body)
`(call-with-exit
(lambda (exit)
(let loop ()
(call-with-exit
(lambda (continue)
(do () ((not ,test) (exit))
,@body)))
(loop)))))
(define-macro (safe-while test . body)
(with-let (sublet (unlet) :test test :body body)
(let ((loop (gensym)))
(call-with-exit
(lambda (exit)
(let ,loop ()
(call-with-exit
(lambda (continue)
(do () ((not ,test) (exit))
,@body)))
(,loop)))))))
</pre>
<p>There are many more examples in s7test.scm (see especially the "or" macros
toward the end of s7test.scm).
</p>
<blockquote>
<div class="indented">
<pre>
(define-macro (swap a b) ; assume a and b are symbols
`(with-let (inlet 'e (curlet) 'tmp ,a)
(set! (e ',a) (e ',b))
(set! (e ',b) tmp)))
> (let ((b 1) (tmp 2)) (swap b tmp) (list b tmp))
<em class="gray">(2 1)</em>
(define-macro (swap a b) ; here a and b can be any settable expressions
`(set! ,b (with-let (inlet 'e (curlet) 'tmp ,a)
(with-let e (set! ,a ,b))
tmp)))
> (let ((v (vector 1 2))) (swap (v 0) (v 1)) v)
<em class="gray">#(2 1)</em>
> (let ((tmp (cons 1 2))) (swap (car tmp) (cdr tmp)) tmp)
<em class="gray">(2 . 1)</em>
(set! (setter swap) (define-macro (set-swap a b c) `(set! ,b ,c)))
> (let ((a 1) (b 2) (c 3) (d 4)) (swap a (swap b (swap c d))) (list a b c d))
<em class="gray">(2 3 4 1)</em>
;;; but this is simpler:
(define-macro (rotate! . args)
`(set! ,(args (- (length args) 1))
(with-let (inlet 'e (curlet) 'tmp ,(car args))
(with-let e
,@(map (lambda (a b) `(set! ,a ,b)) args (cdr args)))
tmp)))
> (let ((a 1) (b 2) (c 3)) (rotate! a b c) (list a b c))
<em class="gray">(2 3 1)</em>
</pre>
</div>
</blockquote>
<!--
<br>
<p>
If you want the macro's expanded result
to be evaluated in its definition environment:
</p>
<pre>
(let ((a 3))
(define-macro (mac b)
`(with-let (inlet 'b ,b (funclet mac))
(+ a b))) ; definition-time "a", call-time "b"
(define-macro (mac-1 b)
`(+ a ,b)) ; call-time "a" and "b"
(let ((a 32))
(list (mac 1)
(mac-1 1))))
</pre>
-->
<blockquote>
<div class="indented">
<pre>
(let ()
(define (f23 y) (+ y 1)) ; the first f23
(define-macro (m1 x) `(f23 ,x)) ; picks up f23 from whatever the local env is where m1 is expanded
(m1 3) ; 4
(let ((f23 (lambda (y) (+ y 2)))) ; the second f23
(m1 3) ; 5
(set! (symbol-initial-value :f23) f23))
;; this remembers the second f23 as #_:f23 or (symbol-initial-value :f23)
(define-macro (m2 x) `(,f23 ,x)) ; ",f23" picks up f23 from m2's definition-time environment
(define e1 #f)
(let ((f23 (lambda (y) (+ y 3)))) ; the third f23
(set! e1 (curlet)) ; save the environment holding the third f23
(m2 3)) ; 4 ; y + 1 because at this point the definition env f23 is the first
(set! (symbol-initial-value 'f23) f23) ; #_f23 now refers to the first f23
(set! f23 (lambda (y) (+ y 4))) ; the fourth f23
(define-macro (m3 x) `((#_symbol-initial-value 'f23) ,x))
;; this picks up the first f23 by delaying the reference to it until evaluation time.
;; Using `(#_f23 ,x) here will fail unless f23's symbol-initial-value is set at the top-level
;; because the reader only knows about global values:
(define-macro (m4 x) `(#_f23 ,x))
;; that is, when this definition is encountered, the reader sees the #_f23 without knowing anything about its
;; context (this is while reading the let form, before the symbol-initial-value is actually set).
;; When the let is later evaluated, the m4 code has already become `(#<undefined: f23> ,x)
;; so we get the error: "attempt to apply an undefined object #_f23 in (#_f23 3)?"
(define-macro (m5 x) `((#_symbol-initial-value :f23) ,x)) ; this is a reference to the second f23
;; 'f23 and :f23 can have different initial-values
(define-macro (m6 x) `((,e1 'f23) ,x)) ; use e1 to get the third f23
;; more hygienic: set e1's symbol-initial-value to itself above, then use (#_symbol-initial-value 'e1) here
(let ((f23 (lambda (y) (+ y 5)))) ; the fifth f23
(m1 3) ; 8 = 3 + 5 from local (fifth) f23
(m2 3) ; 7 = 3 + 4 from definition environment f23 (the fourth)
(m3 3) ; 4 = 3 + 1 from the first f23 (before the (set! f23 ...))
(catch #t (lambda () (m4 3)) (lambda (type info) (apply format #f info))))) ; error given above
(m5 3) ; 5 = 3 + 2 from second f23
(m6 3))) ; 6 = 3 + 3 from third f23
</pre>
</div>
</blockquote>
<!--
<blockquote>
<div class="indented">
<p>Here are some variations on "unless", inspired by the wikipedia hygienic macro page:
</p>
<pre>
(define-macro (my-unless condition . body)
`(with-let (inlet (unlet) :condition ,condition) ; here unlet protects body (format below)
(if (not condition) (begin ,@body))))
(let ((not (lambda (x) x))
(begin 32)
(if +)
(format abs))
(my-unless #t (format #t "This should not be printed!\n"))
(my-unless #f (format #t "This should be printed!\n")))
(set! format abs)
(let ((not (lambda (x) x)))
(my-unless #t (format #t "This should not be printed!\n"))
(my-unless #f (format #t "This should be printed!\n")))
(define (user-defined-operator x) (not x))
(define-macro (my-unless-1 condition . body)
`(with-let (inlet (unlet) :condition ,condition)
(if (user-defined-operator condition) (begin ,@body))))
(let ((user-defined-operator (lambda (x) x)))
(my-unless-1 #t (format #t "This should not be printed!\n"))
(my-unless-1 #f (format #t "This should be printed!\n")))
(define my-unless-2
(let ((op1 (lambda (x) (not x))))
(define-macro (_ condition . body)
`(with-let (inlet (unlet) (funclet my-unless-2) :condition ,condition)
;; funclet above to get my-unless-2's version of op1
(if (op1 condition) (begin ,@body))))))
(let ((op1 (lambda (x) x)))
(my-unless-2 #t (format #t "This should not be printed!\n"))
(my-unless-2 #f (format #t "This should be printed!\n")))
(define my-unless-3
(let ((op1 (lambda (x) x)))
(define-macro (_ condition . body)
`(with-let (inlet (unlet) :condition ,condition :local-env (curlet))
;; curlet to get run-time local version of op1
(if ((with-let local-env op1) condition) (begin ,@body))))))
(let ((op1 (lambda (x) (not x))))
(my-unless-3 #t (format #t "This should not be printed!\n"))
(my-unless-3 #f (format #t "This should be printed!\n")))
</pre>
</div>
</blockquote>
-->
<!--
(define (tree-quote tree args)
(if (pair? tree)
(if (eq? (car tree) 'quote)
tree
(cons (tree-quote (car tree) args)
(tree-quote (cdr tree) args)))
(if (memq tree args)
(list 'quote tree)
tree)))
(define-macro (define-hacro name-and-args . body)
(let ((name (car name-and-args))
(args (cdr name-and-args)))
`(define-macro ,name-and-args
(list 'with-let
(list 'inlet ,@(map (lambda (arg)
(values (symbol->keyword arg) arg))
args))
,@(tree-quote body args)))))
; (define-hacro (mac a b) `(+ ,a ,b))
; (macroexpand (mac 2 3))
; (with-let (inlet :a 2 :b 3) (+ a b))
; (procedure-source mac)
; (lambda (a b) (list 'with-let (list 'inlet :a a :b b) (list-values '+ 'a 'b)))
-->
<blockquote>
<div class="indented">
<p>On the subject of *#readers*, say we have:
</p>
<pre>
(set! *#readers* (list (cons #\o (lambda (str) 42)) ; #o... -> 42
(cons #\x (lambda (str) 3)))) ; #x... -> 3
</pre>
<p>Now we load a file with:
</p>
<pre>
(define (oct) #o123)
(let-temporarily ((*#readers* ()))
(eval (with-input-from-string "(define (hex) #x123)" read)))
(define-constant old-readers *#readers*)
(set! *#readers* ())
(define (oct1) #o123)
(define (hex1) #x123)
(set! *#readers* old-readers)
(define (oct2) #o123)
(define (hex2) #x123)
</pre>
<p>Now we evaluate these functions, and get:
</p>
<pre>
(oct): 42 ; oct is not read-time hygienic so #o123 -> 42
(oct1): 83 ; oct1 is protected by the top-level set, #o123 -> 83
(oct2): 42 ; same as oct
(hex): 291 ; hex is protected by let-temporarily + read
(hex1): 291 ; hex1 is like oct1
(hex2): 3 ; hex2 is like oct
</pre>
</div>
</blockquote>
<blockquote>
<div class="indented">
<p>Here is Peter Seibel's wonderful once-only macro:
</p>
<pre class="indented">
(define-macro (once-only names . body)
(let ((gensyms (map (lambda (n) (gensym)) names)))
`(let (,@(map (lambda (g) (list g '(gensym))) gensyms))
`(let (,,@(map (lambda (g n) (list list g n)) gensyms names))
,(let (,@(map list names gensyms))
,@body)))))
</pre>
<!-- this was:
(define-macro (once-only names . body)
(let ((gensyms (map (lambda (n) (gensym)) names)))
`(let (,@(map (lambda (g) `(,g (gensym))) gensyms))
`(let (,,@(map (lambda (g n) ``(,,g ,,n)) gensyms names))
,(let (,@(map (lambda (n g) `(,n ,g)) names gensyms))
,@body)))))
-->
<p>From the land of sparkling bacros:
</p>
<pre class="indented">
(define once-only
(let ((names (gensym))
(body (gensym)))
(apply define-bacro `((,(gensym) ,names . ,body)
`(let (,@(map (lambda (name) `(,name ,(eval name))) ,names))
,@,body)))))
</pre>
<p>Sadly, with-let is simpler.
</p>
</div>
</blockquote>
<div class="header" id="pws"><h4>setter</h4></div>
<pre class="indented">
(<em class=def>setter</em> proc)
(<em class=def id="dilambda">dilambda</em> proc setter)
</pre>
<p>There are several kinds of setters, reflecting the many ways that set! can be called.
First are the symbol setters:
</p>
<pre class="indented">
> (let ((x 1))
(set! (setter 'x) (lambda (name new-value) (* new-value 2)))
(set! x 2)
x)
<em class="gray">4</em>
</pre>
<p>Here the setter is a function that is called before the variable is set.
It can take two or three arguments. In the two argument case shown above,
the first is the variable name (a symbol), and the second is the new-value.
The variable is set to the value returned by the setter function.
When s7 sees <code>(set! x 2)</code> above, it calls the setter which returns 4.
So x is set to 4.
</p>
<p>In some cases you need the environment that the variable lives in (to get its
current value for example), so you can include that in the setter function parameter list:
</p>
<pre class="indented">
> (let ((x 1))
(set! (setter 'x) (lambda (name new-value enviroment) (* new-value 2)))
(set! x 2)
x)
<em class="gray">4</em>
(define-macro (watch var) ; notification if 'var is set!
`(set! (setter ',var)
(lambda (s v e)
(format *stderr* "~S set! to ~S~A~%" s v
(let ((func (with-let e (*function*))))
(if (eq? func #<undefined>) "" (format #f ", ~S" func))))
v)))
</pre>
<p>Since symbol setters are often implementing type restrictions, you can use
the built-in type checking functions such as integer? as a short-hand
for a setter that insists the new value be an integer:
</p>
<pre class="indented">
> (let ((x 1))
(set! (setter 'x) integer?)
(set! x 3.14))
<em class="red">error</em><em class="gray">: set! x: 3.14, is a real but should be an integer</em>
;;; use typed-let from stuff.scm to do the same thing:
> (typed-let ((x 3 integer?))
(set! x 3.14))
<em class="red">error</em><em class="gray">: set! x: 3.14, is a real but should be an integer</em>
;; see also typed-lambda in stuff.scm
</pre>
<p>C-side symbol setters go through s7_set_setter. There is an example <a href="#notify">below</a>.
</p>
<p>The second case is a function setter. Almost any function or macro can
have an associated setter that is invoked when the function is the target of set!.
In this case, the setter function does the set! itself (unlike a symbol setter):
</p>
<pre class="indented">
> (setter cadr)
<em class="gray">#f</em> ; by default cadr has no setter so (set! (cadr p) x) is an error
> (set! (setter cadr) ; add a setter to cadr
(lambda (lst val)
(set! (car (cdr lst)) val)))
<em class="gray">#<lambda (lst val)></em>
> (procedure-source (setter cadr))
<em class="gray">(lambda (lst val) (set! (car (cdr lst)) val))</em>
> (let ((lst (list 1 2 3)))
(set! (cadr lst) 4)
lst)
<em class="gray">(1 4 3)</em>
</pre>
<p>In some cases, the setter needs to be a macro:
</p>
<pre class="indented">
> (set! (setter logbit?)
(define-macro (m var index on) ; here we want to set "var", so we need a macro
`(if ,on
(set! ,var (logior ,var (ash 1 ,index)))
(set! ,var (logand ,var (lognot (ash 1 ,index)))))))
<em class="gray">m</em>
> (define (mingle a b)
(let ((r 0))
(do ((i 0 (+ i 1)))
((= i 31) r)
(set! (logbit? r (* 2 i)) (logbit? a i))
(set! (logbit? r (+ (* 2 i) 1)) (logbit? b i)))))
<em class="gray">mingle</em>
> (mingle 6 3) ; the INTERCAL mingle operator?
<em class="gray">30</em>
</pre>
<p>dilambda defines a function (or macro) and its setter without having to set! the setter by hand:
</p>
<pre class="indented">
> (define f (let ((x 123))
(dilambda (lambda ()
x)
(lambda (new-value)
(set! x new-value)))))
<em class="gray">f</em>
> (f)
<em class="gray">123</em> ; x = 123
> (set! (f) 32)
<em class="gray">32</em> ; now x = 32
> (f)
<em class="gray">32</em>
</pre>
<div class="indented">
<p>Here is a pretty example of dilambda:
</p>
<pre class="indented">
(define-macro (c?r path)
;; "path" is a list and "X" marks the spot in it that we are trying to access
;; (a (b ((c X)))) — anything after the X is ignored, other symbols are just placeholders
;; c?r returns a dilambda that gets/sets X
(define (X-marks-the-spot accessor tree)
(if (eq? tree 'X)
accessor
(and (pair? tree)
(or (X-marks-the-spot (cons 'car accessor) (car tree))
(X-marks-the-spot (cons 'cdr accessor) (cdr tree))))))
(let ((body 'lst))
(for-each
(lambda (f)
(set! body (list f body)))
(reverse (X-marks-the-spot () path)))
`(<em class=red>dilambda</em>
(lambda (lst)
,body)
(lambda (lst val)
(set! ,body val)))))
> ((c?r (a b (X))) '(1 2 (3 4) 5))
<em class="gray">3</em>
> (let ((lst (list 1 2 (list 3 4) 5)))
(set! ((c?r (a b (X))) lst) 32)
lst)
<em class="gray">(1 2 (32 4) 5)</em>
> (procedure-source (c?r (a b (X))))
<em class="gray">(lambda (lst) (car (car (cdr (cdr lst)))))</em>
> ((c?r (a b . X)) '(1 2 (3 4) 5))
<em class="gray">((3 4) 5)</em>
> (let ((lst (list 1 2 (list 3 4) 5)))
(set! ((c?r (a b . X)) lst) '(32))
lst)
<em class="gray">(1 2 32)</em>
> (procedure-source (c?r (a b . X)))
<em class="gray">(lambda (lst) (cdr (cdr lst)))</em>
> ((c?r (((((a (b (c (d (e X)))))))))) '(((((1 (2 (3 (4 (5 6))))))))))
<em class="gray">6</em>
> (let ((lst '(((((1 (2 (3 (4 (5 6)))))))))))
(set! ((c?r (((((a (b (c (d (e X)))))))))) lst) 32)
lst)
<em class="gray">(((((1 (2 (3 (4 (5 32)))))))))</em>
> (procedure-source (c?r (((((a (b (c (d (e X)))))))))))
<em class="gray">(lambda (lst) (car (cdr (car (cdr (car (cdr (car (cdr (car (cdr (car (car (car (car lst)))))))))))))))</em>
</pre>
</div>
<p>I may remove dilambda and dilambda? someday; they are trivial:
</p>
<pre class="indented">
(define (dilambda get set) (set! (setter get) set) get)
(define dilambda? setter)
</pre>
<p>When a function setter is called, <code>(set! (func ...) val)</code> is
evaluated by s7 as <code>((setter func) ... val)</code>, so the setter function
needs to handle both the inner arguments to the function and the new value.
</p>
<pre class="indented">
(let ((x 123))
(define (f a b) (+ x a b))
(set! (setter f) (lambda (a b val) (set! x val)))
(display (f 1 2)) (newline) ; "126"
(set! (f 1 2) 32)
(display (f 1 2)) (newline)) ; "35"
</pre>
<p>A third type of setter handles vector element type and hash-table key and value types.
These are described under <a href="#typedvectors">typed vectors</a> and
<a href="#typedhash">typed hash-tables</a>.
</p>
<br>
<blockquote>
<div class="indented">
<p>Speaking of INTERCAL, COME-FROM:
</p>
<pre class="indented">
(define-macro (define-with-goto-and-come-from name-and-args . body)
(let ((labels ())
(gotos ())
(come-froms ()))
(let collect-jumps ((tree body))
(when (pair? tree)
(when (pair? (car tree))
(case (caar tree)
((label) (set! labels (cons tree labels)))
((goto) (set! gotos (cons tree gotos)))
((come-from) (set! come-froms (cons tree come-froms)))
(else (collect-jumps (car tree)))))
(collect-jumps (cdr tree))))
(for-each
(lambda (goto)
(let* ((name (cadr (cadar goto)))
(label (member name labels (lambda (a b) (eq? a (cadr (cadar b)))))))
(if label
(set-cdr! goto (car label))
(error 'bad-goto "can't find label: ~S" name))))
gotos)
(for-each
(lambda (from)
(let* ((name (cadr (cadar from)))
(label (member name labels (lambda (a b) (eq? a (cadr (cadar b)))))))
(if label
(set-cdr! (car label) from)
(error 'bad-come-from "can't find label: ~S" name))))
come-froms)
`(define ,name-and-args
(let ((label (lambda (name) #f))
(goto (lambda (name) #f))
(come-from (lambda (name) #f)))
,@body))))
</pre>
</div>
</blockquote>
<!-- (define-macro (please . args) args) -->
<div class="header" id="generalizedset"><h4>applicable objects, generalized set!, generic functions</h4></div>
<p>A procedure with a setter can be viewed as one generalization of set!. Another
treats objects as having predefined get and set functions. In s7
lists, strings, vectors, hash-tables, environments, and any cooperating C or Scheme-defined objects
are both applicable and settable. newLisp calls this implicit indexing, Kawa has it, Gauche implements it
via object-apply, Guile via procedure-with-setter; CL's funcallable instance might be the same idea.
</p>
<p>
In <code>(vector-ref #(1 2) 0)</code>, for example, vector-ref is just a type
declaration. But in Scheme, type declarations are unnecessary, so we get exactly
the same result from <code>(#(1 2) 0)</code>. Similarly, <code>(lst 1)</code> is the
same as <code>(list-ref lst 1)</code>, and <code>(set! (lst 1) 2)</code> is the same
as <code>(list-set! lst 1 2)</code>.
I like this syntax: the less noise, the better!
</p>
<blockquote>
<div class="indented">
<p>Well, maybe applicable strings look weird: <code>("hi" 1)</code> is #\i, but worse,
so is <code>(cond (1 => "hi"))</code>! Even though a string, list, or vector is "applicable", it is
not currently considered to be a procedure, so <code>(procedure? "hi")</code> is #f. map and for-each, however,
accept anything that apply can handle, so
<code>(map #(0 1) '(1 0))</code> is '(1 0). (On the first call to map in this case, you get the result of
<code>(#(0 1) 1)</code> and so on).
string->list, vector->list, and let->list are <code>(map values object)</code>.
Their inverses are (and always have been) equally trivial.
</p>
<p>The applicable object syntax makes it easy to write generic functions.
For example, s7test.scm has implementations of Common Lisp's sequence functions.
length, copy, reverse, fill!, iterate, map and for-each are generic in this sense (map always returns a list).
</p>
<pre class="indented">
> (map (lambda (a b) (- a b)) (list 1 2) (vector 3 4))
<em class="gray">(5 -3 9)</em>
> (length "hi")
<em class="gray">2</em>
</pre>
<p>
Here's a generic FFT:
</p>
<pre class="indented">
(define* (cfft data n (dir 1)) ; complex data
(unless n (set! n (length data)))
(do ((i 0 (+ i 1))
(j 0))
((= i n))
(if (> j i)
(let ((temp (data j)))
(set! (data j) (data i))
(set! (data i) temp)))
(do ((m (/ n 2) (/ m 2)))
((not (<= 2 m j))
(set! j (+ j m)))
(set! j (- j m))))
(do ((ipow (floor (log n 2)))
(prev 1)
(lg 0 (+ lg 1))
(mmax 2 (* mmax 2))
(pow (/ n 2) (/ pow 2))
(theta (complex 0.0 (* pi dir)) (* theta 0.5)))
((= lg ipow))
(do ((wpc (exp theta))
(wc 1.0)
(ii 0 (+ ii 1)))
((= ii prev)
(set! prev mmax))
(do ((jj 0 (+ jj 1))
(i ii (+ i mmax))
(j (+ ii prev) (+ j mmax)))
((>= jj pow)
(set! wc (* wc wpc)))
(let ((tc (* wc (data j))))
(set! (data j) (- (data i) tc))
(set! (data i) (+ (data i) tc))))))
data)
> (cfft (list 0.0 1+i 0.0 0.0))
<em class="gray">(1+1i -1+1i -1-1i 1-1i)</em>
> (cfft (vector 0.0 1+i 0.0 0.0))
<em class="gray">#(1+1i -1+1i -1-1i 1-1i)</em>
</pre>
<p>And a generic function that copies one sequence's elements into another sequence:
</p>
<pre class="indented">
(define (copy-into source dest) ; this is equivalent to (copy source dest)
(do ((i 0 (+ i 1)))
((= i (min (length source) (length dest)))
dest)
(set! (dest i) (source i))))
</pre>
<p>but that is already built-in as the two-argument version of the copy function.
</p>
</div>
<div class="indented">
<p>There is one place where list-set! and friends are not the same as set!: the former
evaluate their first argument, but set! does not (with a quibble; see below):
</p>
<pre class="indented">
> (let ((str "hi")) (string-set! (let () str) 1 #\a) str)
<em class="gray">"ha"</em>
> (let ((str "hi")) (set! (let () str) 1 #\a) str)
<em class="gray">;((let () str) 1 #\a): too many arguments to set!</em>
> (let ((str "hi")) (set! ((let () str) 1) #\a) str)
<em class="gray">"ha"</em>
> (let ((str "hi")) (set! (str 1) #\a) str)
<em class="gray">"ha"</em>
</pre>
<p>set! looks at its first argument to decide what to set.
If it's a symbol, no problem. If it's a pair, set! looks at its car to see if it is
some object that has a setter. If the car is itself a list, set! evaluates the internal
expression, and tries again. So the second case above is the only one that won't work.
And of course:
</p>
<pre class="indented">
> (let ((x (list 1 2)))
(set! ((((lambda () (list x))) 0) 0) 3)
x)
<em class="gray">(3 2)</em>
</pre>
</div>
<div class="indented">
<p>By my count, around 20 of the Scheme built-in functions are already generic in the sense
that they accept arguments of many types (leaving aside the numeric and type checking functions, take for example equal?, display,
member, assoc, apply, eval, quasiquote, and values). s7 extends that list with map, for-each, reverse,
and length, and adds a few others such as copy, fill!, sort!, object->string, object->let, vector-length and friends, and append.
newLisp takes a more radical approach than s7: it extends operators such as '>'
to compare strings and lists, as well as numbers. In map and for-each, however, you can mix the argument
types, so I'm not as attracted to making '>' generic; you can't, for example, <code>(> "hi" 32.1)</code>,
or even <code>(> 1 0+i)</code>.
</p>
</div>
</blockquote>
<div class="separator"></div>
<p>The somewhat non-standard generic sequence functions in s7 are:
</p>
<pre class="indented">
(<em class=def id="sortb">sort!</em> sequence less?)
(<em class=def id="reverseb">reverse!</em> sequence) and (reverse sequence)
(<em class=def id="fillb">fill!</em> sequence value (start 0) end)
(<em class=def id="s7copy">copy</em> obj) and (copy source destination (start 0) end)
(<em class=def id="objtostr">object->string</em> obj)
(object->let obj)
(length obj)
(append . sequences)
(map func . sequences) and (for-each func . sequences)
(<a href="#equivalentp">equivalent?</a> obj1 obj2)
</pre>
<p><b>copy</b> returns a (shallow) copy of its argument. If a destination is provided,
it need not match the source in size or type. The start and end indices refer to the source.
</p>
<pre class="indented">
> (copy '(1 2 3 4) (make-list 2))
<em class="gray">(1 2)</em>
> (copy #(1 2 3 4) (make-list 5) 1) ; start at 1 in the source
<em class="gray">(2 3 4 #f #f)</em>
> (copy "1234" (make-vector 2))
<em class="gray">#(#\1 #\2)</em>
> (define lst (list 1 2 3 4 5))
<em class="gray">(1 2 3 4 5)</em>
> (copy #(8 9) (cddr lst))
<em class="gray">(8 9 5)</em>
> lst
<em class="gray">(1 2 8 9 5)</em>
</pre>
<p><b>reverse!</b> is an in-place version of reverse. That is,
it modifies the sequence passed to it in the process of reversing its contents.
If the sequence is a list, remember to use set!:
<code>(set! p (reverse! p))</code>. This is somewhat inconsistent with other cases,
but historically, lisp programmers have treated the in-place reverse as the fast
version, so s7 follows suit.
</p>
<pre class="indented">
> (define lst (list 1 2 3))
<em class="gray">(1 2 3)</em>
> (reverse! lst)
<em class="gray">(3 2 1)</em>
> lst
<em class="gray">(1)</em>
</pre>
<p>Leaving aside the weird list case,
<b>append</b> returns a sequence of the same type as its first argument.
</p>
<pre class="indented">
> (append #(1 2) '(3 4))
<em class="gray">#(1 2 3 4)</em>
> (append (float-vector) '(1 2) (byte-vector 3 4))
<em class="gray">(float-vector 1.0 2.0 3.0 4.0)</em>
</pre>
<p>
<b>sort!</b> sorts a sequence using the
function passed as its second argument:
</p>
<pre class="indented">
> (sort! (list 3 4 8 2 0 1 5 9 7 6) <)
<em class="gray">(0 1 2 3 4 5 6 7 8 9)</em>
</pre>
<p>sort! calls qsort or qsort_r; if the sequence is large (more than 1024 elements?), qsort_r may allocate an internal array;
if the comparison function raises an error, this internal array will probably not be freed.
</p>
<p>Underlying some of these functions are generic iterators, also built-into s7:
</p>
<pre class="indented">
(<em class=def id="makeiterator">make-iterator</em> sequence carrier)
(<em class=def id="iteratorp">iterator?</em> obj)
(<em class=def id="iterate">iterate</em> iterator)
(<em class=def id="iteratorsequence">iterator-sequence</em> iterator)
(<em class=def id="iteratoratend">iterator-at-end?</em> iterator)
</pre>
<p><b>make-iterator</b> takes a sequence argument and returns an iterator object that traverses
that sequence as it is called. A sequence is a list, let, vector (of any type), string, hash-table,
or c-object, or a function of macro that declares itself to be iterable (via +iterator+).
The iterator returned by make-iterator can be treated as a function of no arguments,
or (for code clarity) it can be the argument to <b>iterate</b>, which does the same thing.
That is <code>(iter)</code> is the same as <code>(iterate iter)</code>. The sequence that an iterator is traversing
is <b>iterator-sequence</b>.
A c-object iterator iterates by calling c-object-ref (s7_c_type_set_ref) until
it reaches c-object-length (s7_c_type_set_length) (for array traversal etc).
</p>
<p>
If the sequence is a hash-table or let, the iterator normally returns a cons of the key and value.
There are many cases where this overhead is objectionable, so make-iterator takes a second optional
argument, carrier, which should be the cons to use. Similarly,
for int, float, and complex vectors, the carrier argument can be #t which tells s7 to use a mutable number of the
correct type. In both cases, the returned carrier is the same across all iterator calls, so
copy the carrier value if you need to save it.
</p>
<p>When an iterator reaches the end of its sequence, it returns #<eof> by default.
To change this value, set (*s7* 'iterator-at-end-value). (If the new value might be GC collected, you'll need to GC protect it).
If an iterator over a
list notices that its list is circular, it returns the (*s7* 'iterator-at-end) value;
map and for-each use
iterators, so if you pass a circular list to either, it will stop eventually. (An
arcane consequence for method writers: specialize make-iterator, not map or for-each).
</p>
<pre class="indented">
(define (find-if f sequence)
(let ((iter (make-iterator sequence)))
(do ((x (iter) (iter)))
((or (iterator-at-end? iter)
(f x))
(and (not (iterator-at-end? iter))
x)))))
</pre>
<p>The argument to make-iterator can also be a function or macro.
In this case, to be acceptable to iterate, the closure's environment must have a
variable named '+iterator+ with a non-#f value:
</p>
<pre class="indented">
(define (make-circular-iterator obj)
(let ((iter (make-iterator obj)))
(make-iterator
(let ((+iterator+ #t))
(lambda ()
(case (iter)
((#<eof>) ((set! iter (make-iterator obj))))
(else)))))))
</pre>
<p>The +iterator+ variable is similar to the '+documentation+ variable used by documentation.
It gives make-iterator some hope of catching inadvertent bogus function arguments that would
otherwise cause an infinite loop. But unfortunately it can escape and infect
other functions:
</p>
<pre class="indented">
(with-let (let ((<em class="red">+iterator+</em> #t))
(lambda () #<eof>)) ; we intended this to be our iterator
(concatenate vector (lambda a (copy a)))) ; from stuff.scm
;; (lambda a (copy a)) is also considered an iterator by map (in sequences->list) because
;; the local +iterator+ is #t. "a" is () because there are no further arguments to
;; concatenate, so (lambda a (copy a)) is generating infinitely many ()'s and this
;; code eventually dies with a heap overflow!
</pre>
<div class="header" id="multidimensionalvectors"><h4>multidimensional vectors</h4></div>
<p>
s7 supports
vectors with any number of dimensions. It is here, in particular, that generalized
set! shines. make-vector's first argument can be a list of dimensions, rather than
an integer as in the one dimensional case:
</p>
<pre class="indented">
(make-vector (list 2 3 4))
(make-vector '(2 3) 1.0)
(vector-dimensions (make-vector '(2 3 4))) -> (2 3 4)
</pre>
<p>The second example includes the optional initial element.
<code>(vect i ...)</code> or <code>(vector-ref vect i ...)</code> return the given
element, and <code>(set! (vect i ...) value)</code> and <code>(vector-set! vect i ... value)</code>
set it. vector-length (or just length) returns the total number of elements.
vector-dimensions returns a list of the dimensions; vector-rank returns the length of this list,
and vector-dimension returns the nth member of the list (the size of the nth dimension).
</p>
<pre class="indented">
> (define v (make-vector '(2 3) 1.0))
<em class="gray">#2d((1.0 1.0 1.0) (1.0 1.0 1.0))</em>
> (set! (v 0 1) 2.0)
<em class="gray">#2d((1.0 2.0 1.0) (1.0 1.0 1.0))</em>
> (v 0 1)
<em class="gray">2.0</em>
> (vector-length v)
<em class="gray">6</em>
</pre>
<p>This function initializes each element of a multidimensional vector:
</p>
<pre class="indented">
(define (make-array dims . inits)
(subvector (apply vector (flatten inits)) 0 (apply * dims) dims))
> (make-array '(3 3) '(1 1 1) '(2 2 2) '(3 3 3))
<em class="gray">#2d((1 1 1) (2 2 2) (3 3 3))</em>
</pre>
<p>make-int-vector, make-float-vector, make-complex-vector and make-byte-vector produce homogeneous vectors holding
s7_ints, s7_doubles, s7_complexs or unsigned bytes.
</p>
<pre class="indented">
(<em class=def id="makevector">make-vector</em> length-or-list-of-dimensions initial-value element-type-function)
(<em class=def id="vectordimensions">vector-dimensions</em> vect)
(<em class=def id="vectordimension">vector-dimension</em> vect n)
(<em class=def id="vectorrank">vector-rank</em> obj)
(<em class=def id="vectortyper">vector-typer</em> obj)
(<em class=def id="floatvectorp">float-vector?</em> obj)
(<em class=def id="floatvector">float-vector</em> . args)
(<em class=def id="makefloatvector">make-float-vector</em> len (init 0.0))
(<em class=def id="floatvectorref">float-vector-ref</em> obj . indices)
(<em class=def id="floatvectorset">float-vector-set!</em> obj indices[...] value)
(<em class=def id="complexvectorp">complex-vector?</em> obj)
(<em class=def id="complexvector">complex-vector</em> . args)
(<em class=def id="makecomplexvector">make-complex-vector</em> len (init 0.0))
(<em class=def id="complexvectorref">complex-vector-ref</em> obj . indices)
(<em class=def id="complexvectorset">complex-vector-set!</em> obj indices[...] value)
(<em class=def id="intvectorp">int-vector?</em> obj)
(<em class=def id="intvector">int-vector</em> . args)
(<em class=def id="makeintvector">make-int-vector</em> len (init 0))
(<em class=def id="intvectorref">int-vector-ref</em> obj . indices)
(<em class=def id="intvectorset">int-vector-set!</em> obj indices[...] value)
(<em class=def id="bytevectorp">byte-vector?</em> obj)
(<em class=def id="bytevector">byte-vector</em> . args)
(<em class=def id="makebytevector">make-byte-vector</em> len (init 0))
(<em class=def id="bytevectorref">byte-vector-ref</em> obj . indices)
(<em class=def id="bytevectorset">byte-vector-set!</em> obj indices[...] byte)
(<em class=def id="bytep">byte?</em> obj)
(<em class=def id="stringtobytevector">string->byte-vector</em> str)
(<em class=def id="bytevectortostring">byte-vector->string</em> str)
(<em class=def id="subvector">subvector</em> vector start end dimensions)
(<em class=def id="subvectorp">subvector?</em> obj)
(<em class=def id="subvectorvector">subvector-vector</em> obj)
(<em class=def id="subvectorposition">subvector-position</em> obj)
</pre>
<p id="typedvectors">In addition to the dimension list mentioned above, make-vector accepts
optional arguments giving the initial element and the element type. If the
type is given, every attempt to set an element of the vector first calls
the type function on the new value.
If the type function is omitted (or set to #t),
no type checking is performed.
If the type function is a closure (rather than a C-defined or built-in function),
its name must be accessible; it can't be an anonymous lambda (the signature and
error handlers need this name). <a href="#vectortyper">vector-typer</a> returns or sets this type function;
when set via vector-typer, there is no automatic check that the vector's current contents
match that type function.
</p>
<pre class="indented">
> (define v (make-vector 3 'x symbol?)) ; initial element: 'x, elements must be symbols
<em class="gray">#(x x x)</em>
> (vector-set! v 0 123)
<em class="red">error</em><em class="gray">: vector-set! argument 3, 123, is an integer but should be a symbol?</em>
> (define (10|12? val) (memv val '(10 12)))
<em class="gray">10|12?</em>
> (define v1 (make-vector 3 10 10|12?)) ; only allow values 10 or 12 (initially 10)
<em class="gray">#(10 10 10)</em>
> (set! (v1 0) 12)
<em class="gray">12</em>
> v1
<em class="gray">#(12 10 10)</em>
> (set! (v1 1) 32)
<em class="red">error</em><em class="gray">: vector-set! argument 3, 32, is an integer but should be a 10|12?</em>
</pre>
<p>To access a vector's elements with different dimensions than the original had, use
<code>(subvector original-vector 0 (length original-vector) new-dimensions)</code>:
</p>
<pre class="indented">
> (let ((v1 #2d((1 2 3) (4 5 6))))
(let ((v2 (subvector v1))) ; flatten the original (1D is the default)
v2))
<em class="gray">#(1 2 3 4 5 6)</em>
> (let ((v1 #(1 2 3 4 5 6)))
(let ((v2 (subvector v1 0 6 '(3 2))))
v2))
<em class="gray">#2d((1 2) (3 4) (5 6))</em>
</pre>
<p>A subvector is a window onto some other vector's data. The data is not copied, just accessed differently.
The new-dimensions parameter is a list giving the lengths of the dimensions. The start and
end parameters refer to positions in the original vector.
subvector-vector returns
the underlying vector, and subvector-position returns the starting point of the subvector
in the underlying data. subvector makes it easy to access rows or columns of a vector viewed as a matrix:
</p>
<pre class="indented">
> (define V (vector 0 1 2 3 4 5 6 7 8 9 10 11))
#(0 1 2 3 4 5 6 7 8 9 10 11)
> (do ((i 0 (+ i 4))) ((= i 12)) (display (subvector V i (+ i 4))) (newline))
#(0 1 2 3)
#(4 5 6 7)
#(8 9 10 11)
> (do ((sV (subvector V 0 12 '(3 4))) (i 0 (+ i 1))) ((= i 4))
(display (vector (sV 0 i) (sV 1 i) (sV 2 i))) (newline))
#(0 4 8)
#(1 5 9)
#(2 6 10)
#(3 7 11)
</pre>
<!--
<div class="small">
<p>subvector's parameter list changed 8-Jul-2020. It was <code>(subvector vect new-length-or-dimension-list start)</code>,
but that conflicts with substring, and is confusing (the start position follows the length). To translate from
the old subvector to the new:
</p>
<pre class="indented">
(define* (old-subvector vect len (offset 0))
(if (pair? len)
(subvector vect offset (+ offset (apply * len)) len)
(if (not len)
(subvector vect offset (length vect))
(subvector vect offset (+ offset len)))))
</pre>
</div>
-->
<blockquote>
<div class="indented">
<p>matrix multiplication:
</p>
<pre>
(define (matrix-multiply A B)
;; assume square matrices and so on for simplicity
(let ((size (car (vector-dimensions A))))
(do ((C (make-vector (list size size) 0))
(i 0 (+ i 1)))
((= i size) C)
(do ((j 0 (+ j 1)))
((= j size))
(do ((sum 0)
(k 0 (+ k 1)))
((= k size)
(set! (C i j) sum))
(set! sum (+ sum (* (A i k) (B k j)))))))))
</pre>
</div>
<div class="indented">
<p>Conway's game of Life:
</p>
<pre>
(define* (life (width 40) (height 40))
(let ((state0 (make-vector (list width height) 0))
(state1 (make-vector (list width height) 0)))
;; initialize with some random pattern
(do ((x 0 (+ x 1)))
((= x width))
(do ((y 0 (+ y 1)))
((= y height))
(set! (state0 x y) (if (< (random 100) 15) 1 0))))
(do () ()
;; show current state (using terminal escape sequences, borrowed from the Rosetta C code)
(format *stderr* "~C[H" #\escape) ; ESC H = tab set
(do ((y 0 (+ y 1)))
((= y height))
(do ((x 0 (+ x 1)))
((= x width))
(format *stderr*
(if (zero? (state0 x y))
" " ; ESC 07m below = inverse
(values "~C[07m ~C[m" #\escape #\escape))))
(format *stderr* "~C[E" #\escape)) ; ESC E = next line
;; get the next state
(do ((x 1 (+ x 1)))
((= x (- width 1)))
(do ((y 1 (+ y 1)))
((= y (- height 1)))
(let ((n (+ (state0 (- x 1) (- y 1))
(state0 x (- y 1))
(state0 (+ x 1) (- y 1))
(state0 (- x 1) y)
(state0 (+ x 1) y)
(state0 (- x 1) (+ y 1))
(state0 x (+ y 1))
(state0 (+ x 1) (+ y 1)))))
(set! (state1 x y)
(if (or (= n 3)
(and (= n 2)
(not (zero? (state0 x y)))))
1 0)))))
(copy state1 state0))))
</pre>
</div>
<div class="indented">
<p>Multidimensional vector constant syntax is modelled after CL: #nd(...)
signals that the lists specify the elements of an 'n' dimensional vector: <code>#2d((1 2 3) (4 5 6))</code>
int-vector constants use #i, float-vectors use #r, complex-vectors use #c.
Append the "nd" business after the type indication: <code>#i2d((1 2) (3 4))</code>. This syntax
collides with the r7rs byte-vector notation "#u8"; s7 uses "#u" for byte-vectors. "#u2d(...)" is a two-dimensional byte-vector.
For backwards compatibility, you can use "#u8" for one-dimensional byte-vectors.
</p>
<pre class="indented">
> (vector-ref #2d((1 2 3) (4 5 6)) 1 2)
<em class="gray">6</em>
> (matrix-multiply #2d((-1 0) (0 -1)) #2d((2 0) (-2 2)))
<em class="gray">#2d((-2 0) (2 -2))</em>
> (int-vector 1 2 3)
<em class="gray">#i(1 2 3)</em>
> (make-float-vector '(2 3) 1.0)
<em class="gray">#r2d((1.0 1.0 1.0) (1.0 1.0 1.0))</em>
> (vector (vector 1 2) (int-vector 1 2) (float-vector 1 2))
<em class="gray">#(#(1 2) #i(1 2) #r(1.0 2.0))</em>
</pre>
<p>If any dimension has 0 length, you get an n-dimensional empty vector. It is not
equal to a 1-dimensional empty vector.
</p>
<pre class="indented">
> (make-vector '(10 0 3))
<em class="gray">#3d()</em>
> (equal? #() #3d())
<em class="gray">#f</em>
</pre>
</div>
<div class="indented">
<p>To save on costly parentheses, and make it easier to write generic multidimensional sequence functions,
you can use this same syntax with lists.
</p>
<pre class="indented">
> (let ((L '((1 2 3) (4 5 6))))
(L 1 0)) ; same as (list-ref (list-ref L 1) 0) or ((L 1) 0)
<em class="gray">4</em>
> (let ((L '(((1 2 3) (4 5 6)) ((7 8 9) (10 11 12)))))
(set! (L 1 0 2) 32) ; same as (list-set! (list-ref (list-ref L 1) 0) 2 32) which is unreadable!
L)
<em class="gray">(((1 2 3) (4 5 6)) ((7 8 32) (10 11 12)))</em>
</pre>
<p>Or with vectors of vectors, of course:
</p>
<pre class="indented">
> (let ((V #(#(1 2 3) #(4 5 6))))
(V 1 2)) ; same as (vector-ref (vector-ref V 1) 2) or ((V 1) 2)
<em class="gray">6</em>
> (let ((V #2d((1 2 3) (4 5 6))))
(V 0))
<em class="gray">#(1 2 3)</em>
</pre>
<p>There's one difference between a vector-of-vectors and a multidimensional vector:
in the latter case, you can't clobber one of the inner vectors.
</p>
<pre class="indented">
> (let ((V #(#(1 2 3) #(4 5 6)))) (set! (V 1) 32) V)
<em class="gray">#(#(1 2 3) 32)</em>
> (let ((V #2d((1 2 3) (4 5 6)))) (set! (V 1) 32) V)
<em class="gray">;not enough arguments for vector-set!: (#2d((1 2 3) (4 5 6)) 1 32)</em>
</pre>
</div>
<div class="indented">
<p>Using lists to display the inner vectors may not be optimal, especially when the elements are also lists:
</p>
<pre class="indented">
#2d(((0) (0) ((0))) ((0) 0 ((0))))
</pre>
<p>The "#()" notation is no better (the elements can be vectors), and I'm not a fan of "[]" parentheses.
Perhaps we could use different colors? Or different size parentheses?
</p>
<pre class="indented">
#2D<em class=green>(</em><em class=red>(</em>(0) (0) ((0))<em class=red>)</em> <em class=red>(</em>(0) 0 ((0))<em class=red>)</em><em class=green>)</em>
#2D<em class="bigger">(</em><em class="big">(</em>(0) (0) ((0))<em class="big">)</em> <em class="big">(</em>(0) 0 ((0))<em class="big">)</em><em class="bigger">)</em>
</pre>
</div>
<div class="indented">
<p>I'm not sure how to handle vector->list and list->vector in the multidimensional case.
Currently, vector->list flattens the vector, and list->vector always returns a
one dimensional vector, so the two are not inverses.
</p>
<pre class="indented">
> (vector->list #2d((1 2) (3 4)))
<em class="gray">(1 2 3 4)</em> ; should this be '((1 2) (3 4)) or '(#(1 2) #(3 4))?
> (list->vector '(#(1 2) #(3 4))) ; what about '((1 2) (3 4))?
<em class="gray">#(#(1 2) #(3 4)) </em>
</pre>
<p>
This also affects format and sort!:
</p>
<pre class="indented">
> (format #f "~{~A~^ ~}" #2d((1 2) (3 4)))
<em class="gray">"1 2 3 4"</em>
> (sort! #2d((1 4) (3 2)) >)
<em class="gray">#2d((4 3) (2 1))</em>
</pre>
<p>Perhaps subvector can help:
</p>
<pre class="indented">
>(subvector (list->vector '(1 2 3 4)) 0 4 '(2 2))
<em class="gray">#2d((1 2) (3 4))</em>
> (let ((a #2d((1 2) (3 4)))
(b #2d((5 6) (7 8))))
(list (subvector (append a b) 0 8 '(2 4))
(subvector (append a b) 0 8 '(4 2))
(subvector (append (a 0) (b 0) (a 1) (b 1)) 0 8 '(2 4))
(subvector (append (a 0) (b 0) (a 1) (b 1)) 0 8 '(4 2))))
<em class="gray">(#2d((1 2 3 4) (5 6 7 8))
#2d((1 2) (3 4) (5 6) (7 8))
#2d((1 2 5 6) (3 4 7 8))
#2d((1 2) (5 6) (3 4) (7 8)))</em>
</pre>
</div>
<div class="indented">
<p>Another question: should we accept the multi-index syntax in a case such as <code>
(#("abc" "def") 0 2)</code>?
My first thought was that the indices should all refer to the same
type of object, so s7 would complain in a mixed case like that.
If we can nest any applicable objects and apply the whole thing to
an arbitrary list of indices, ambiguities arise:
</p>
<pre class="indented">
((lambda (x) x) "hi" 0)
((lambda (x) (lambda (y) (+ x y))) 1 2)
</pre>
<p>I think these should complain that the function got too many arguments,
but from the implicit indexing point of view, they could be interpreted
as:
</p>
<pre class="indented">
(string-ref ((lambda (x) x) "hi") 0) ; i.e. (((lambda (x) x) "hi") 0)
(((lambda (x) (lambda (y) (+ x y))) 1) 2)
</pre>
<p>Add optional and rest arguments, and you can't tell who is supposed to
take which arguments.
Currently, you can mix types with implicit indices, but if you implicitly
call an element of a sequence that is a function
that is not known to be "safe" (unproblematic) you'll get an error.
To insist that all objects are of the same type, use an explicit getter:
</p>
<pre class="indented">
> (list-ref (list 1 (list 2 3)) 1 0) ; same as ((list 1 (list 2 3)) 1 0)
<em class="gray">2</em>
> ((list 1 (vector 2 3)) 1 0)
<em class="gray">2</em>
> (list-ref (list 1 (vector 2 3)) 1 0)
<em class="red">error</em><em class="gray">: list-ref argument 1, #(2 3), is a vector but should be a proper list</em>
</pre>
</div>
</blockquote>
<div class="header" id="hashtables"><h4>hash-tables</h4></div>
<ul>
<li>(<em class=def id="makehashtable">make-hash-table</em> (size 8) eq-func typers)
<li>(<em class=def id="makeweakhashtable">make-weak-hash-table</em> (size 8) eq-func typers)
<li>(<em class=def id="hashtable">hash-table</em> ...)
<li>(<em class=def id="weakhashtable">weak-hash-table</em> ...)
<li>(<em class=def id="hashtablep">hash-table?</em> obj)
<li>(<em class=def id="weakhashtablep">weak-hash-table?</em> obj)
<li>(<em class=def id="hashtableref">hash-table-ref</em> ht key)
<li>(<em class=def id="hashtableset">hash-table-set!</em> ht key value)
<li>(<em class=def id="hashtableentries">hash-table-entries</em> ht)
<li>(<em class=def id="hashtablekeytyper">hash-table-key-typer</em> obj)
<li>(<em class=def id="hashtablevaluetyper">hash-table-value-typer</em> obj)
<li>(<em class=def id="hashcode">hash-code</em> obj eqfunc)
</ul>
<p>
Each hash-table keeps track of the keys it contains, optimizing the search wherever possible.
Any s7 object can be the key or the key's value.
If you pass a table size that is not a power of 2, make-hash-table rounds it up to the next power of 2.
The table grows as needed. length returns the current size.
If a key is not in the table, hash-table-ref returns #f. To remove a key,
set its value to #f; to remove all keys, <code>(fill! table #f)</code>.
(This #f is (*s7* 'hash-table-missing-key-value); it can be set to some
other value such as #<undefined>: <code>(set! (*s7* 'hash-table-missing-key-value) #<undefined>)</code>.)
(If the new value might be GC collected, you'll need to GC protect it).
</p>
<pre class="indented">
> (let ((ht (make-hash-table)))
(set! (ht "hi") 123)
(ht "hi"))
<em class="gray">123</em>
</pre>
<p>hash-table (the function) parallels the functions vector, list, and string.
Its arguments are
the keys and values: <code>(hash-table 'a 1 'b 2)</code>.
Implicit indexing gives multilevel hashes:
</p>
<pre class="indented">
> (let ((h (hash-table 'a (hash-table 'b 2 'c 3)))) (h 'a 'b))
<em class="gray">2</em>
> (let ((h (hash-table 'a (hash-table 'b 2 'c 3)))) (set! (h 'a 'b) 4) (h 'a 'b))
<em class="gray">4</em>
</pre>
<p>hash-code is like Common Lisp's sxhash. It returns an integer that can be associated with
an s7 object when implementing your own hash-tables. s7test.scm has an example using vectors.
In this case the eqfunc argument is ignored (hash-code assumes equal? is in use).
</p>
<blockquote>
<div class="indented">
<p>Since hash-tables accept the same applicable-object syntax that vectors use, we can
treat a hash-table as, for example, a sparse array:
</p>
<pre class="indented">
> (define make-sparse-array make-hash-table)
<em class="gray">make-sparse-array</em>
> (let ((arr (make-sparse-array)))
(set! (arr 1032) "1032")
(set! (arr -23) "-23")
(list (arr 1032) (arr -23)))
<em class="gray">("1032" "-23")</em>
</pre>
</div>
<div class="indented">
<p>map and for-each accept hash-table arguments. On each iteration, the map or for-each function is passed
an entry, <code>'(key . value)</code>, in whatever order the entries are encountered in the table.
</p>
<pre class="indented">
(define (hash-table->alist table)
(map values table))
</pre>
<p>reverse of a hash-table returns a new table with the keys and values reversed.
fill! sets all the values.
Two hash-tables are equal if they have the same keys with the same values. This is independent
of the table sizes, or the order in which the key/value pairs were added.
</p>
</div>
<div class="indented">
<p>The second argument to make-hash-table (eq-func) is slightly complicated. If it is omitted (or #f),
s7 chooses the hashing equality and mapping functions based on the keys in the hash-table.
There are times when you know
in advance what equality function you want. If it's one of the built-in s7 equality
functions, eq?, eqv?, equal?, equivalent?, =, string=?, string-ci=?, char=?, or char-ci=?,
you can pass that function as the second argument. In any other case, you need to
give s7 both the equality function and the mapping function. The latter takes any object
and returns the hash-table location for it (an integer). The problem here is that
for the arbitrary equality function to work, objects that are equal according to that
function have to be mapped to the same hash-table location. There's no way for s7 to intuit
what this mapping should be except in the built-in cases. So to specify some arbitrary function, the second
argument is a cons: '(equality-checker mapper).
</p>
<p>Here's a brief example. In CLM, we have c-objects of type mus-generator (from s7's point of view),
and we want to hash them using equal? (which will call the generator-specific equality function).
But s7 doesn't realize that the mus-generator type covers 40 or 50 internal types, so as the mapper we pass mus-type:
<code>(make-hash-table 64 (cons equal? mus-type))</code>.
</p>
</div>
<div class="indented">
<p>If the hash key is a float (a non-rational number), hash-table-ref uses <a href="#equivalentp">equivalent?</a>.
Otherwise, for example, you could use NaN as a key, but then never be able to access it!
</p>
</div>
<div class="indented">
<p>To implement read-time hash-tables using #h(...):
</p>
<pre>
(set! *#readers*
(cons (cons #\h (lambda (str)
(and (string=? str "h") ; #h(...)
(apply hash-table (read)))))
*#readers*))
(display #h(:a 1)) (newline)
(display #h(:a 1 :b "str")) (newline)
</pre>
<p>These can be made immutable by <code>(immutable! (apply...))</code>, or even better,
</p>
<pre>
(let ((h (apply hash-table (read))))
(if (> (*s7* 'safety) 1) (immutable! h) h))
</pre>
</div>
<div class="indented">
<pre>
(define-macro (define-memoized name&arg . body)
(let ((arg (cadr name&arg))
(memo (gensym "memo")))
`(define ,(car name&arg)
(let ((,memo (<em class=red>make-hash-table</em>)))
(lambda (,arg)
(or (,memo ,arg) ; check for saved value
(set! (,memo ,arg) (begin ,@body)))))))) ; set! returns the new value
> (define (fib n)
(if (< n 2) n (+ (fib (- n 1)) (fib (- n 2)))))
<em class="gray">fib</em>
> (define-memoized
(memo-fib n)
(if (< n 2) n (+ (memo-fib (- n 1)) (memo-fib (- n 2)))))
<em class="gray">memo-fib</em>
> (time (fib 34)) ; un-memoized time
<em class="gray">1.168</em> ; 0.70 on ccrma's i7-3930 machines
> (time (memo-fib 34)) ; memoized time
<em class="gray">3.200e-05</em>
> (outlet (funclet memo-fib))
<em class="gray">(inlet '{memo}-18 (hash-table
'(0 . 0) '(1 . 1) '(2 . 1) '(3 . 2) '(4 . 3) '(5 . 5)
'(6 . 8) '(7 . 13) '(8 . 21) '(9 . 34) '(10 . 55) '(11 . 89)
'(12 . 144) '(13 . 233) '(14 . 377) '(15 . 610) '(16 . 987)
'(17 . 1597) '(18 . 2584) '(19 . 4181) '(20 . 6765) '(21 . 10946)
'(22 . 17711) '(23 . 28657) '(24 . 46368) '(25 . 75025) '(26 . 121393)
'(27 . 196418) '(28 . 317811) '(29 . 514229) '(30 . 832040) '(31 . 1346269)
'(32 . 2178309) '(33 . 3524578) '(34 . 5702887)))</em>
</pre>
<p>but the tail recursive version of fib is simpler and almost as fast as the memoized version,
and the iterative version beats both.
</p>
</div>
<p id="typedhash">The third argument, typers, sets type checkers for the keys and values in the table,
much like the third argument to make-vector.
It is a cons of the type functions,
<code>(cons symbol? integer?)</code> for example. This says that all the keys must
be symbols and all the values integers.
<a href="#hashtablekeytyper">hash-table-key-typer</a> and
<a href="#hashtablevaluetyper">hash-table-value-typer</a>
return or set these functions.
</p>
<pre class="indented">
> (define (10|12? val) (memv val '(10 12)))
<em class="gray">10|12?</em>
> (define hash (make-hash-table 8 #f (cons #t 10|12?))) ; any key is ok, but all values must be 10 or 12
<em class="gray">(hash-table)</em>
> (set! (hash 'a) 10)
<em class="gray">10</em>
> hash
<em class="gray">(hash-table 'a 10)</em>
> (set! (hash 'b) 32)
<em class="red">error</em><em class="gray">: hash-table-set! value argument 3, 32, is an integer but should be a 10|12?</em>
</pre>
<div class="indented">
<pre>
(define H (hash-table 'v1 1 'v2 2 'v3 3))
(let ((last-key #f))
(define (valtyp val)
(or (not last-key)
(eq? last-key 'v1)
(and (eq? last-key 'v2)
(integer? val)
(<= 0 val 32))))
(define (keytyp key)
(set! last-key key)
#t)
(set! (<em class=red>hash-table-key-typer</em> H) keytyp)
(set! (<em class=red>hash-table-value-typer</em> H) valtyp))
;; now (H 'v1) can be set to anything
;; (H 'v2) must be an integer between 0 and 32
;; (H 'v3) is immutable (but setting it to #f will remove it from H)
> (hash-table-set! H 'v1 11)
11
>(hash-table-set! H 'v2 12)
12
> (hash-table-set! H 'v3 13)
<em class=red>error</em>: hash-table-set! third argument 13, is an integer, but the hash-table's value type checker, valtyp, rejects it
> (hash-table-set! H 'v2 112)
<em class=red>error</em>: hash-table-set! third argument 112, is an integer, but the hash-table's value type checker, valtyp, rejects it
</pre>
</div>
</blockquote>
<div class="header" id="environments"><h4>environments</h4></div>
<p>An environment holds symbols and their values. The global environment, for example,
holds all the variables that are defined at the top level.
Environments are first class (and applicable) objects in s7.
In many cases, where the description below says "env" or "let", you can actually
pass either a let (an environment) or any object that has its own let.
</p>
<pre class="indented">
(<em class=def id="rootlet">rootlet</em>) the top-level (global) environment
(<em class=def id="curlet">curlet</em>) the current (innermost) environment
(<em class=def id="funclet">funclet</em> proc) the environment at the time when proc was defined
(<em class=def id="isfunclet">funclet?</em> env) #t if env is a funclet
(owlet) the environment at the point of the last error
(<em class=def id="unlet">unlet</em>) a let with built-in functions with their original value
(<em class=def id="letref">let-ref</em> env sym) get value of sym in env, same as (env sym)
(<em class=def id="letset">let-set!</em> env sym val) set value of sym in env to val, same as (set! (env sym) val)
(<em class=def id="inlet">inlet</em> . bindings) make a new environment with the given bindings
(<em class=def id="sublet">sublet</em> env . bindings) same as inlet, but the new environment is local to env
(<em class=def id="varlet">varlet</em> env . bindings) add new bindings directly to env
(<em class=def id="cutlet">cutlet</em> env . fields) remove bindings from env
(<em class=def id="letp">let?</em> obj) #t if obj is an environment
(<em class=def id="with-let">with-let</em> env . body) evaluate body in the environment env
(<em class=def id="outlet">outlet</em> env) the environment that encloses the environment env (settable)
(<em class=def id="lettolist">let->list</em> env) return the environment bindings as a list of (symbol . value) cons's
(<em class=def id="openlet">openlet</em> env) mark env as open (see below)
(<em class=def id="openletp">openlet?</em> env) #t is env is open
(<em class=def id="coverlet">coverlet</em> env) mark env as closed (undo an earlier openlet)
(<em class=def id="objecttolet">object->let</em> obj) return an environment containing information about obj
(<em class=def id="lettemporarily">let-temporarily</em> vars . body)
</pre>
<blockquote>
<pre class="indented">
> (inlet 'a 1 'b 2)
<em class="gray">(inlet 'a 1 'b 2)</em>
> (let ((a 1) (b 2)) (curlet))
<em class="gray">(inlet 'a 1 'b 2)</em>
> (let ((x (inlet :a 1 :b 2))) (x 'a))
<em class="gray">1</em>
> (with-let (inlet 'a 1 'b 2) (+ a b))
<em class="gray">3</em>
> (let ((x (inlet :a 1 :b 2))) (set! (x 'a) 4) x)
<em class="gray">(inlet 'a 4 'b 2)</em>
> (let ((x (inlet))) (varlet x 'a 1) x)
<em class="gray">(inlet 'a 1)</em>
> (let ((a 1)) (let ((b 2)) (outlet (curlet))))
<em class="gray">(inlet 'a 1)</em>
> (let ((e (inlet 'a (inlet 'b 1 'c 2)))) (e 'a 'b)) ; in C terms, e->a->b
<em class="gray">1</em>
> (let ((e (inlet 'a (inlet 'b 1 'c 2)))) (set! (e 'a 'b) 3) (e 'a 'b))
<em class="gray">3</em>
> (define* (make-let (a 1) (b 2)) (sublet (rootlet) (curlet)))
<em class="gray">make-let</em>
> (make-let :b 32)
<em class="gray">(inlet 'a 1 'b 32)</em>
</pre>
</blockquote>
<p>As the names suggest, in s7 an environment is viewed as a disembodied let. Environments are equal if they
contain the same symbols with the same values leaving aside shadowing, and taking into account the environment
chain up to the rootlet. That is, two environments are equal if any local variable of either has the same value in both.
</p>
<p><b>let-ref</b> and <b>let-set!</b> return #<undefined> if the first argument is not
defined in the environment or its parents. To search just the given environment (ignoring its outlet chain),
use defined? with the third argument #t before calling let-ref or let-set!:
</p>
<pre class="indented">
> (defined? 'car (inlet 'a 1) #t)
<em class="gray">#f</em>
> (defined? 'car (inlet 'a 1))
<em class="gray">#t</em>
</pre>
<p>This matters in let-set!: <code>(let-set! (inlet 'a 1) 'car #f)</code>
is the same as <code>(set! car #f)</code>!
</p>
<p>
<b>with-let</b> evaluates its body in the given environment, so
<code>(with-let e . body)</code> is equivalent to
<code>(eval `(begin ,@body) e)</code>, but probably faster.
Similarly, <code>(let bindings . body)</code> is equivalent to
<code>(eval `(begin ,@body) (apply inlet (flatten bindings)))</code>,
ignoring the outer (enclosing) environment (the default outer environment
of inlet is rootlet).
Or better,
</p>
<pre class="indented">
(define-macro (with-environs e . body)
`(apply let (map (lambda (a) (list (car a) (cdr a))) ,e) '(,@body)))
</pre>
<p>Or turning it around,</p>
<pre>
(define-macro (Let vars . body)
`(with-let (sublet (curlet)
,@(map (lambda (var)
(values (symbol->keyword (car var)) (cadr var)))
vars))
,@body))
(Let ((c 4))
(Let ((a 2)
(b (+ c 2)))
(+ a b c)))
</pre>
<p>It is faster to use <code>(biglet 'a-function)</code> than <code>(with-let biglet a-function)</code>.
</p>
<p><b>let-temporarily</b> is somewhat similar to fluid-let in other Schemes.
Its syntax looks like
let, but it first saves the current value, then sets the
variable to the new value (via set!), calls the body, and finally restores the
original value. It can handle anything settable:
</p>
<pre class="indented">
(let-temporarily (((*s7* 'print-length) 8)) (display x))
</pre>
<p>This sets s7's print-length variable to 8 while displaying x, then
puts it back to its original value.
</p>
<pre class="indented">
> (define ourlet
(let ((x 1))
(define (a-func) x)
(define b-func (let ((y 1))
(lambda ()
(+ x y))))
(curlet)))
<em class="gray">(inlet 'x 1 'a-func a-func 'b-func b-func)</em>
> (ourlet 'x)
<em class="gray">1</em>
> (let-temporarily (((ourlet 'x) 2))
((ourlet 'a-func)))
<em class="gray">2</em>
> ((funclet (ourlet 'b-func)) 'y)
<em class="gray">1</em>
> (let-temporarily ((((funclet (ourlet 'b-func)) 'y) 3))
((ourlet 'b-func)))
<em class="gray">4</em>
</pre>
<p>Despite the name, no new environment is created by let-temporarily:
<code>(let () (let-temporarily () (define x 2)) (+ x 1))</code> is 3.
Also, if the variable in question has a setter, that setter is called
twice (to set the new value, then later to restore the old).
</p>
<p>
<b>sublet</b> makes a new let with the bindings passed to it, then sets the new environment's outlet to the 'env' argument.
This is similar to a let form inside another let.
</p>
<pre class="indented">
> (sublet (curlet) 'b 2)
<em class="gray">(inlet 'b 2)</em>
> (let ((a 1)) (with-let (sublet (curlet) 'b 2) (+ a b)))
<em class="gray">3</em>
</pre>
<p>
To add the bindings directly to the environment,
use <b>varlet</b>.
Both accept environment other than the first as well as individual bindings,
adding all the argument's bindings to the new environment.
<b>inlet</b> is very similar, but normally omits the environment argument.
The arguments to sublet and inlet can be passed as
symbol/value pairs, as a cons, or using keywords as if in define*.
inlet can also be used to copy an environment without accidentally invoking
that environment's copy method.
</p>
<p>To implement read-time lets using #let(...):
</p>
<pre>
(set! *#readers*
(cons (cons #\l (lambda (str)
(and (string=? str "let") ; #let(...)
(apply inlet (read)))))
*#readers*))
(display #let(:a 1)) (newline)
(display #let(:a 1 :b "str")) (newline)
</pre>
<p>Here's an example of varlet: we want to define two functions that share a
local variable:
</p>
<pre class="indented">
(varlet (curlet) ; import f1 and f2 into the current environment
(let ((x 1)) ; x is our local variable
(define (f1 a) (+ a x))
(define (f2 b) (* b x))
(inlet 'f1 f1 'f2 f2))) ; export f1 and f2
</pre>
<p>One way to add reader and writer functions to an individual environment slot is:
</p>
<pre class="indented">
(define e (inlet
'x (let ((local-x 3)) ; x's initial value
(dilambda
(lambda () local-x)
(lambda (val) (set! local-x (max 0 (min val 100))))))))
> ((e 'x))
<em class="gray">3</em>
> (set! ((e 'x)) 123)
<em class="gray">100</em>
</pre>
<p><b>funclet</b> returns a function's local environment. Here's an example that
keeps a circular buffer of the calls to that function:
</p>
<pre class="indented">
(define func (let ((history (let ((lst (make-list 8 #f)))
(set-cdr! (list-tail lst 7) lst))))
(lambda (x y)
(let ((result (+ x y)))
(set-car! history (list result x y))
(set! history (cdr history))
result))))
> (func 1 2)
<em class="gray">3</em>
> (func 3 4)
<em class="gray">7</em>
> ((funclet func) 'history)
<em class="gray">#1=(#f #f #f #f #f #f (3 1 2) (7 3 4) . #1#)</em>
</pre>
<p>It is possible in Scheme to redefine built-in functions such as car.
To ensure that some code sees the original built-in function definitions,
wrap it in <code>(with-let (unlet) ...)</code>:
</p>
<pre class="indented">
> (let ((caar 123))
(+ caar (with-let (unlet)
(caar '((2) 3)))))
<em class="gray">125</em>
</pre>
<p>Or perhaps better, to keep the current environment intact except for the
changed built-ins:
</p>
<pre class="indented">
> (let ((x 1)
(display 3))
(with-let (sublet (curlet) (unlet)) ; (curlet) picks up 'x, (unlet) the original 'display
(display x)))
<em class="gray">1</em>
</pre>
<p>
with-let and unlet are constants, so you can
use them in any context without worrying about whether they've been redefined.
As mentioned in the macro section, #_<name> is a built-in reader macro
for <code>(with-let (unlet) <name>)</code>,
so for example, #_+ is the built-in + function, no matter what.
(The environment of built-in functions
that unlet accesses is not accessible from scheme code, so there's no way
that those values can be clobbered).
</p>
<p><b>cutlet</b> removes bindings from an environment. If the environment is
part of the outlet chain of a function, you'll probably get a segfault.
Don't, for example, <code>(cutlet (outlet (funclet func) 'x))</code>
where func refers to x in its body. Similarly, don't mess up the
outlet chain of a function (via (set! (outlet...))), and still
expect that function to do something reasonable. (I may remove cutlet someday).
</p>
<br>
<div class="indented">
<p>
I think these functions can implement the notions of libraries,
separate namespaces, or modules.
Here's one way: first the library writer just writes his library.
The normal user simply loads it. The abnormal user worries about everything,
so first he loads the library in a local let to make sure no bindings escape
to pollute his code, and then he
uses unlet to
make sure that none of his bindings pollute the library code:
</p>
<pre class="indented">
(let ()
(with-let (unlet)
(load "any-library.scm" (curlet))
;; by default load puts stuff in the global environment
...))
</pre>
<p>Now Abnormal User can do what he wants with the library entities.
Say he wants to use "lognor" under the name "bitwise-not-or", and
all the other functions are of no interest:
</p>
<pre class="indented">
(varlet (curlet)
'bitwise-not-or (with-let (unlet)
(load "any-library.scm" (curlet))
lognor)) ; lognor is presumably defined in "any-library.scm"
</pre>
<p>Say he wants to make sure the library is cleanly loaded, but all
its top-level bindings are imported into the current environment:
</p>
<pre class="indented">
(varlet (curlet)
(with-let (unlet)
(let ()
(load "any-library.scm" (curlet))
(curlet)))) ; these are the bindings introduced by loading the library
</pre>
<p>To do the same thing, but prepend "library:" to each name:
</p>
<pre class="indented">
(apply varlet (curlet)
(with-let (unlet)
(let ()
(load "any-library.scm" (curlet))
(map (lambda (binding)
(cons (symbol "library:" (symbol->string (car binding)))
(cdr binding)))
(curlet)))))
</pre>
<p>That's all there is to it! Here is the same idea as a macro:
</p>
<pre>
(define-macro (let! init end . body)
;; syntax mimics 'do: (let! (vars&values) ((exported-names) result) body)
;; (let! ((a 1)) ((hiho)) (define (hiho x) (+ a x)))
`(let ,init
,@body
(varlet (outlet (curlet))
,@(map (lambda (export)
`(cons ',export ,export))
(car end)))
,@(cdr end)))
</pre>
<!--
(define-macro (safe-let! init end . body)
`(with-let (#_inlet (unlet)
,@(#_map (#_lambda (b)
`(#_cons ',(#_car b) ,(#_cadr b)))
init))
,@body
(#_varlet (#_outlet (#_curlet))
,@(#_map (#_lambda (export)
`(#_cons ',export ,export))
(#_car end)))
,@(#_cdr end)))
-->
</div>
<div class="indented">
<p>Well, almost, darn it. If the loaded library file sets (via set!) a global value
such as abs, we need to put it back to its original form:
</p>
<pre>
(define (safe-load file)
(let ((e (with-let (unlet) ; save the environment before loading
(let->list (curlet)))))
(<em class=red>load</em> file (curlet))
(let ((new-e (with-let (unlet) ; get the environment after loading
(let->list (curlet)))))
(for-each ; see if any built-in functions were stepped on
(lambda (sym)
(unless (assoc (car sym) e)
(format () "~S clobbered ~A~%" file (car sym))
(apply set! (car sym) (list (cdr sym)))))
new-e))))
;; say libtest.scm has the line (set! abs odd?)
> (safe-load "libtest.scm")
<em class="gray">"libtest.scm" clobbered abs</em>
> (abs -2)
<em class="gray">2</em>
</pre>
</div>
<p><b>openlet</b> marks its argument, either an environment, a closure, a c-object, or a c-pointer
as open; <b>coverlet</b> as closed. I need better terminology here! An open object is one that the
built-in s7 functions handle specially. If they encounter one in their
argument list, they look in the object for their own name, and call that
function if it exists. A bare-bones example:
</p>
<pre class="indented">
> (abs (openlet (inlet 'abs (lambda (x) 47))))
<em class="gray">47</em>
> (define* (f1 (a 1)) (if (real? a) (abs a) ((a 'f1) a)))
<em class="gray">f1</em>
> (f1 :a (openlet (inlet 'f1 (lambda (e) 47))))
<em class="gray">47</em>
</pre>
<p>In CLOS, we'd declare a class and a method, and call make-instance,
and then discover that it wouldn't work anyway.
Here we have, in effect, an anonymous instance of an anonymous class.
I think this is called a "prototype system"; javascript is apparently similar.
A slightly more complex example:
</p>
<pre class="indented">
(let* ((e1 (openlet
(inlet
'x 3
'* (lambda args
(apply * (if (number? (car args))
(values (car args) ((cadr args) 'x) (cddr args))
(values ((car args) 'x) (cdr args))))))))
(e2 (copy e1)))
(set! (e2 'x) 4)
(* 2 e1 e2)) ; (* 2 3 4) => 24
</pre>
<p>Perhaps these names would be better: openlet -> with-methods, coverlet -> without-methods,
and openlet? -> methods?. If the signature of the replaced function does not match that of the
new function, you may get optimizer problems, particularly if the replacement is for-each, map, member, or assoc.
</p>
<blockquote>
<div class="indented">
<p>let-ref and let-set! are problematic as methods. It is very easy to get into an infinite
loop, especially with let-ref, since any reference to the let within the method body probably
calls let-ref, which calls the let-ref method. We used to recommend coverlet here, but
even that is not enough, so now let-ref and let-set! are immutable; they can't be used
as methods.
Use let-ref-fallback and let-set-fallback instead, if possible.
</p>
</div>
</blockquote>
<p><b>object->let</b> returns an environment (more of a dictionary really) that
contains details about its argument. It
is intended as a debugging aid, underlying a debugger's "inspect" for example.
</p>
<pre class="indented">
> (let ((iter (make-iterator "1234")))
(iter)
(iter)
(object->let iter))
<em class="gray">(inlet 'value #<iterator: string> 'type iterator? 'at-end #f 'sequence "1234" 'length 4 'position 2)</em>
</pre>
<p>A c-object (in the sense of s7_make_c_type), can add its own info to this namespace via an object->let
method in its local environment. snd-marks.c has a simple example using a class-wide environment (g_mark_methods),
holding as the value of its 'object->let field the function s7_mark_to_let. The latter uses s7_varlet to
add information to the namespace created by <code>(object->let mark)</code>.
</p>
<div class="indented">
<pre>
(define-macro (value->symbol expr)
`(let ((val ,expr)
(e1 (curlet)))
(call-with-exit
(lambda (return)
(do ((e e1 (outlet e))) ()
(for-each
(lambda (slot)
(if (equal? val (cdr slot))
(return (car slot))))
e)
(if (eq? e (rootlet))
(return #f)))))))
> (let ((a 1) (b "hi"))
(value->symbol "hi"))
<em class="gray">b</em>
</pre>
</div>
<div class="indented">
<p>openlet alerts the rest of s7 that the environment has methods.
</p>
<pre>
(begin
(define fvector? #f)
(define make-fvector #f)
(let ((type (gensym))
(->float (lambda (x)
(if (real? x)
(* x 1.0)
(error 'wrong-type-arg "fvector new value is not a real: ~A" x)))))
(set! make-fvector
(lambda* (len (init 0.0))
(<em class=red>openlet</em>
(inlet :v (make-vector len (->float init))
:type type
:length (lambda (f) len)
:object->string (lambda (f . args) "#<fvector>")
:let-set! (lambda (fv i val) (#_vector-set! (fv 'v) i (->float val)))
:let-ref-fallback (lambda (fv i) (#_vector-ref (fv 'v) i))))))
(set! fvector? (lambda (p)
(and (let? p)
(eq? (p 'type) type))))))
> (define fv (make-fvector 32))
<em class="gray">fv</em>
> fv
<em class="gray">#<fvector></em>
> (length fv)
<em class="gray">32</em>
> (set! (fv 0) 123)
<em class="gray">123.0</em>
> (fv 0)
<em class="gray">123.0</em>
</pre>
<p>Normally, every let's outlet chain goes back to the rootlet. If we want to
create a let that breaks that chain, we can use let-ref-fallback:
</p>
<pre>
(define lt (<em class=red>openlet</em> (inlet 'a 1 'let-ref-fallback #<undefined>)))
> (lt 'abs)
<em class="gray">#<undefined></em>
</pre>
<p>let-ref-fallback can be either a constant (most usefully #<undefined>) or
a function of two arguments, the let and the symbol.
</p>
</div>
<div class="indented">
<p>If an s7 function ignores the type of an argument, as in cons or vector for example,
then that argument won't be treated as having any methods.
</p>
<p>
Since outlet is settable, there are two ways an environment can
become circular. One is to include the current environment as the value of one of its variables.
The other is: <code>(let () (set! (outlet (curlet)) (curlet)))</code>.
</p>
<p>If you want to hide an environment's fields from any part of s7 that does not
know the field names in advance,
</p>
<pre class="indented">
(openlet ; make it appear to be empty to the rest of s7
(inlet 'object->string (lambda args "#<let>")
'map (lambda args ())
'for-each (lambda args #<unspecified>)
'let->list (lambda args ())
'length (lambda args 0)
'copy (lambda args (inlet))
'open #t
'coverlet (lambda (e) (set! (e 'open) #f) e)
'openlet (lambda (e) (set! (e 'open) #t) e)
'openlet? (lambda (e) (e 'open))
;; your secret data here
))
</pre>
<p>(There are still at least two ways to tell that something is fishy).
</p>
<!-- add a field and it disappears, or sublet and read back -->
</div>
<div class="indented">
<p>Here's one way to add a method to a closure:
</p>
<pre class="indented">
(define sf (openlet (let ((object->string (lambda (obj . arg)
"#<secret function!>")))
(lambda (x)
(+ x 1)))))
> sf
<em class="gray">#<secret function!></em>
</pre>
</div>
<div class="header" id="multiplevalues"><h4>multiple-values</h4></div>
<p>
In s7, multiple values are spliced directly into the caller's argument list.
</p>
<pre class="indented">
> (+ (values 1 2 3) 4)
<em class="gray">10</em>
> (string-ref ((lambda () (values "abcd" 2))))
<em class="gray">#\c</em>
> ((lambda (a b) (+ a b)) ((lambda () (values 1 2))))
<em class="gray">3</em>
> (+ (call/cc (lambda (ret) (ret 1 2 3))) 4) ; call/cc has an implicit "values"
<em class="gray">10</em>
> ((lambda* ((a 1) (b 2)) (list a b)) (values :a 3))
<em class="gray">(3 2)</em>
(define-macro (call-with-values producer consumer)
`(,consumer (,producer)))
(define-macro (multiple-value-bind vars expr . body)
`((lambda ,vars ,@body) ,expr))
(define-macro (define-values vars expression)
`(if (not (null? ',vars))
(varlet (curlet) ((lambda ,vars (curlet)) ,expression))))
(define (curry function . args)
(if (null? args)
function
(lambda more-args
(if (null? more-args)
(apply function args)
(function (apply values args) (apply values more-args))))))
</pre>
<blockquote>
<div class="indented">
<p>multiple-values are useful in several situations. For example,
<code>(if test (+ a b c) (+ a b d e))</code> can be written
<code>(+ a b (if test c (values d e)))</code>.
There are a few special uses of multiple-values.
First, you can use the values function to return any number of values, including 0,
from map's function application:
</p>
<pre class="indented">
> (map (lambda (x) (if (odd? x) (values x (* x 20)) (values))) (list 1 2 3))
<em class="gray">(1 20 3 60)</em>
> (map values (list 1 2 3) (list 4 5 6))
<em class="gray">(1 4 2 5 3 6)</em>
(define (remove-if func lst)
(map (lambda (x) (if (func x) (values) x)) lst))
(define (pick-mappings func lst)
(map (lambda (x) (or (func x) (values))) lst))
(define (shuffle . args)
(apply map values args))
> (shuffle '(1 2 3) #(4 5 6) '(7 8 9))
<em class="gray">(1 4 7 2 5 8 3 6 9)</em>
(define (concatenate . args)
(apply append (map (lambda (arg) (map values arg)) args)))
</pre>
<p>Second, a macro can return multiple values; these are evaluated and spliced,
exactly like a normal macro,
so you can use <code>(values '(define a 1) '(define b 2))</code> to
splice multiple definitions at the macro invocation point.
If an expansion returns (values), nothing is spliced in. This is
mostly useful in <a href="#readercond">reader-cond</a> and the #; reader, but
unfortunately, it is tricky to use. The reader only knows about things globally defined
when it encounters them, and a locally defined expansion is handled as a normal macro,
so:
</p>
<pre class="indented">
> (define-expansion (comment str) (values)) ; this must be at the top-level
<em class="gray">comment</em>
> (+ 1 (comment "one") 2 (comment "two"))
<em class="gray">3</em>
</pre>
<p>At the top-level (in the REPL), since there's nothing to splice into, you simply get your values back:
</p>
<pre class="indented">
> (values 1 (list 1 2) (+ 3 4 5))
<em class="gray">(values 1 (1 2) 12)</em>
</pre>
<p>But this printout is just trying to be informative. There is no multiple-values object
in s7. You can't <code>(set! x (values 1 2))</code>, for example. The values function
tells s7 that its arguments should be handled in a special way, and the multiple-value indication goes away
as soon as the arguments are spliced into some caller's arguments.
</p>
<p id="listvalues">There are two helper functions for multiple values, apply-values and list-values,
both intended primarily for quasiquote where (apply-values ...) implements what other schemes call unquote-splicing (",@...").
(apply-values lst) is like (apply values lst),
and (list-values ...) is like (list ...) except in one special case. It is common in writing macros
to create some piece of code to be spliced into the output, but if that code is nil, the resulting
macro code should contain nothing (not nil). apply-values and list-values cooperate with quasiquote to implement
this. As an example:
</p>
<pre class="indented">
> (list-values 1 2 (apply-values) 3)
<em class="gray">(1 2 3)</em>
> (define (supply . args) (apply-values args))
<em class="gray">supply</em>
> (define (consume f . args) (apply f (apply list-values args)))
<em class="gray">consume</em>
> (consume + (supply 1 2) (supply 3 4 5) (supply))
<em class="gray">15</em>
> (consume + (supply))
<em class="gray">0</em>
</pre>
<p>It might seem simpler to return "nothing" from (values), rather than #<unspecified>,
but that has drawbacks. First, <code>(abs -1 (values))</code>, or worse <code>(abs (f x) (f y))</code>
is no longer an error at the level of the program text; you lose the ability to see at a glance that
a normal function has the right number of arguments. Second, a lot of code currently assumes that
(values) returns #<unspecified>, and that implies that <code>(apply values ())</code> does as well.
But it would be nice if <code>((lambda* ((x 1)) x) (values))</code> returned 1!
<!--
Is <code>(apply apply func arglist)</code> the same as <code>(apply func (apply values arglist))</code>,
or (leaving aside <code>'(()))</code>, <code>(func (apply values (apply values arglist)))</code>?
-->
</p>
</div>
<div class="indented">
<p>Since set! does not evaluate its first argument, and
there is no setter for "values", <code>(set! (values x) ...)</code> is not
the same as <code>(set! x ...)</code>. <code>(string-set! (values string) ...)</code>
works because string-set! does evaluate its first argument. <code>((values + 1 2) (values 3 4) 5)</code>
is 15, as anyone would expect.
</p>
</div>
<p>One problem with this way of handling multiple values involves cases where you can't
tell whether an expression will return multiple values. Then you have, for example, <code>(let ((val (expr)))...)</code>
and need to accept either a normal single value from <code>expr</code>, or one member of the
possible set of multiple values. In lint.scm, I'm currently handling this with lambda:
<code>(let ((val ((lambda args (car args)) (expr))))...)</code>, but this feels kludgey.
CL has nth-value which appears to do "the right thing" in this context; perhaps s7 needs
it too.
</p>
<p>A similar difficulty arises in <code>(if (expr) ...)</code> where <code>(expr)</code> might
return multiple values. CL (or sbcl anyway) treats this as if it were wrapped in <code>(nth-value 0 (expr))</code>.
Splicing the values in, on the other hand, could lead to disaster: there would be no way to tell from the code
that the if statement
was valid, or which branch would be taken! So, in those cases where a syntactic form evaluates
an argument, s7 follows CL, and uses only the first of the values (this affects if, when, unless, cond, and case).
</p>
<p>s7's signatures can indicate that a function returns multiple values: call-with-exit's signature is '(values procedure?).
Perhaps we could indicate the number and the expected types of those values via '((values integer? integer?)...);
is this the function's "rarity"?
</p>
</blockquote>
<div class="header" id="callwithexit1"><h4>call-with-exit, with-baffle and continuation?</h4></div>
<p><b><em class=def id="callwithexit">call-with-exit</em></b> is call/cc without the ability to jump back into the original context,
similar to "return" in C. This
is cleaner than call/cc, and much faster.
</p>
<pre class="indented">
(define-macro (block . body)
;; borrowed loosely from CL — predefine "return" as an escape
`(<em class=red>call-with-exit</em> (lambda (return) ,@body)))
(define-macro (while test . body) ; while loop with predefined break and continue
`(<em class=red>call-with-exit</em>
(lambda (break)
(let continue ()
(if (let () ,test)
(begin
(let () ,@body)
(continue))
(break))))))
(define-macro (switch selector . clauses) ; C-style case (branches fall through unless break called)
`(<em class=red>call-with-exit</em>
(lambda (break)
(case ,selector
,@(do ((clause clauses (cdr clause))
(new-clauses ()))
((null? clause) (reverse new-clauses))
(set! new-clauses (cons `(,(caar clause)
,@(cdar clause)
,@(map (lambda (nc)
(apply values (cdr nc))) ; doubly spliced!
(if (pair? clause) (cdr clause) ())))
new-clauses)))))))
(define (and-for-each func . args)
;; apply func to the first member of each arg, stopping if it returns #f
(<em class=red>call-with-exit</em>
(lambda (quit)
(apply for-each (lambda arglist
(if (not (apply func arglist))
(quit #<unspecified>)))
args))))
(define (find-if f . args) ; generic position-if is very similar
(<em class=red>call-with-exit</em>
(lambda (return)
(apply for-each (lambda main-args
(if (apply f main-args)
(apply return main-args)))
args))))
> (find-if even? #(1 3 5 2))
<em class="gray">2</em>
> (* (find-if > #(1 3 5 2) '(2 2 2 3)))
<em class="gray">6</em>
</pre>
<p>
The call-with-exit function's argument (the "continuation") is only valid
within the call-with-exit function. In call/cc, you can save it, then call it later
to jump back, but if you try that with call-with-exit (from outside the call-with-exit function's body), you'll get an error.
This is similar to trying to read from a closed input port.
</p>
<p>The other side, so to speak, of call-with-exit, is <em class=def id="withbaffle">with-baffle</em>.
Sometimes we need a normal call/cc, but want to make sure it is active
only within a given block of code.
Normally, if a continuation gets away, there's no telling when it might wreak havoc on us.
with-baffle blocks that — no continuation can jump into its body:
</p>
<pre class="indented">
(let ((what's-for-breakfast ())
(bad-dog 'fido)) ; bad-dog wonders what's for breakfast?
(<em class=red>with-baffle</em> ; the syntax is (with-baffle . body)
(set! what's-for-breakfast
(call/cc
(lambda (biscuit?)
(set! bad-dog biscuit?) ; bad-dog smells a biscuit!
'biscuit!))))
(if (eq? what's-for-breakfast 'biscuit!)
(bad-dog 'biscuit!)) ; now, outside the baffled block, bad-dog wants that biscuit!
what's-for-breakfast) ; but s7 says "No!": baffled! ("continuation can't jump into with-baffle")
</pre>
<br>
<p><em class=def id="continuationp">continuation?</em> returns #t if its argument is a continuation,
as opposed to a normal procedure. I don't know why Scheme hasn't had this function from
the very beginning, but it's needed if you want to write a continuable error
handler. Here is a sketch of the situation:
</p>
<pre class="indented">
(catch #t
(lambda ()
(let ((res (call/cc
(lambda (ok)
(error 'cerror "an error" ok)))))
(display res) (newline)))
(lambda args
(when (and (eq? (car args) 'cerror)
(<em class=red>continuation?</em> (cadadr args)))
(display "continuing...")
((cadadr args) 2))
(display "oops")))
</pre>
<p>In a more general case, the error handler is separate from the
catch body, and needs a way to distinguish a real continuation
from a simple procedure.
</p>
<pre class="indented">
(define (continuable-error . args)
(call/cc
(lambda (continue)
(apply error args))))
(define (continue-from-error)
(if (<em class=red>continuation?</em> ((owlet) 'continue)) ; might be #<undefined> or a function as in the while macro
(((owlet) 'continue))
'bummer))
</pre>
<!--
(define-macro (call-with-exit func)
(let ((tag (caadr func)))
`(catch ',tag
(lambda ()
(define-macro (,tag . body)
`(throw ',',tag ,@body))
,@(cddr func))
(lambda (type info)
(car info)))))
-->
<div class="header" id="format1"><h4>format, object->string</h4></div>
<pre class="indented">
(<em class=def id="objecttostring">object->string</em> obj (write #t) (max-len (*s7* 'most-positive-fixnum)))
(<em class=def id="format">format</em> output-choice control-string . arguments)
</pre>
<p>object->string returns the string representation of its first argument. Its optional second argument
can be #f or :display (use display), #t or :write (the default, use write), or :readable. In the latter case, object->string
tries to produce a string that can be evaluated via eval-string to return an object equal to the
original. The optional third argument sets the maximum desired string length; if object->string
notices it has exceeded this limit, it returns the partial string.
</p>
<pre class="indented">
> (object->string "hiho")
<em class="gray">"\"hiho\""</em>
> (format #f "~S" "hiho")
<em class="gray">"\"hiho\""</em>
</pre>
<p>s7's format function is very close to CL's and that in srfi-48.
</p>
<pre class="indented">
> (format #f "~A ~D ~F" 'hi 123 3.14)
<em class="gray">"hi 123 3.140000"</em>
</pre>
<p>The format directives (tilde chars) are:</p>
<pre class="indented">
~% insert newline
~& insert newline if preceding char was not newline
~~ insert tilde
~\n (tilde followed by newline): trim white space
~{ begin iteration (take arguments from a list, string, vector, or any other applicable object)
~} end iteration
~^ ~| jump out of iteration
~* ignore the current argument
~C print character (numeric argument = how many times to print it)
~P insert 's' if current argument is not 1 or 1.0 (use ~@P for "ies" or "y")
~A object->string as in display
~S object->string as in write
~B number->string in base 2
~O number->string in base 8
~D number->string in base 10 (~:D for ordinal)
~X number->string in base 16
~E float to string, (format #f "~E" 100.1) -> "1.001000e+02", (%e in C)
~F float to string, (format #f "~F" 100.1) -> "100.100000", (%f in C)
~G float to string, (format #f "~G" 100.1) -> "100.1", (%g in C)
~T insert spaces (padding)
~N get numeric argument from argument list (similar to ~V in CL)
~W object->string with :readable (write readably: "serialization"; s7 is the intended reader)
</pre>
<p>The eight directives before ~N take the usual numeric arguments to specify field width and precision.
These can also be ~N or ~n in which case the numeric argument is read from the list of arguments:
</p>
<pre class="indented">
(format #f "~ND" 20 1234) ; => (format "~20D" 1234)
<em class="gray">" 1234"</em>
</pre>
<p>
<code>(format #f ...)</code> simply returns the formatted string; <code>(format #t ...)</code>
also sends the string to the current-output-port. <code>(format () ...)</code> sends the output to
the current-output-port without returning the string (this mimics the other IO routines
such as display and newline). Other built-in port choices are *stdout* and *stderr*.
</p>
<blockquote>
<div class="indented">
<p>Floats can occur in any base, so:
</p>
<pre class="indented">
> #xf.c
<em class="gray">15.75</em>
</pre>
<p>This also affects format. In most Schemes, <code>(format #f "~X" 1.25)</code> is
an error. In CL, it is equivalent to using ~A which is perverse. But
</p>
<pre class="indented">
> (number->string 1.25 16)
<em class="gray">"1.4"</em>
</pre>
<p>and there's no obvious way to get the same effect from format unless we accept
floats in the "~X" case. So in s7,
</p>
<pre class="indented">
> (format #f "~X" 21)
<em class="gray">"15"</em>
> (format #f "~X" 1.25)
<em class="gray">"1.4"</em>
> (format #f "~X" 1.25+i)
<em class="gray">"1.4+1.0i"</em>
> (format #f "~X" 21/4)
<em class="gray">"15/4"</em>
</pre>
<p>That is, the output choice matches the argument. A case that came up in the Guile mailing lists is:
<code>(format #f "~F" 1/3)</code>. s7 currently returns "1/3", but Clisp returns "0.33333334".
</p>
<p>The curly bracket directive applies to anything you can map over, not just lists:
</p>
<pre class="indented">
> (format #f "~{~C~^ ~}" "hiho")
<em class="gray">"h i h o"</em>
> (format #f "~{~{~C~^ ~}~^...~}" (list "hiho" "test"))
<em class="gray">"h i h o...t e s t"</em>
> (with-input-from-string (format #f "(~{~C~^ ~})" (format #f "~B" 1367)) read) ; integer->list
<em class="gray">(1 0 1 0 1 0 1 0 1 1 1)</em>
</pre>
<p>Since any sequence can be passed to ~{~}, we need a way to truncate output and represent
the rest of the sequence with "...", but ~^ only stops at the end of the sequence. ~|
is like ~^ but it also stops after it handles (*s7* 'print-length) elements and prints
"...". So, <code>(format #f "~{~A~| ~}" #(0 1 2 3 4))</code> returns "0 1 2 ..."
if (*s7* 'print-length) is 3.
</p>
</div>
</blockquote>
<blockquote>
<div class="indented">
<p>I added object->string to s7 before deciding to include format. format excites a
vague disquiet — why do we need this ancient unlispy thing?
We can almost replace it with:
</p>
<pre class="indented">
(define (objects->string . objects)
(apply string-append (map (lambda (obj) (object->string obj #f)) objects)))
</pre>
<p>But how to handle lists (~{...~} in format), or columnized output (~T)?
I wonder whether formatted string output still matters outside a REPL. Even in that context,
a modern GUI leaves formatting decisions to a text or table widget.
</p>
<pre class="indented">
(define-macro (string->objects str . objs)
`(with-input-from-string ,str
(lambda ()
,@(map (lambda (obj)
`(set! ,obj (eval (read))))
objs))))
</pre>
</div>
<div class="indented">
<p>format is a mess. It is trying to cram two different choices into its first ("port") argument.
Perhaps it should be split into format->string and format->port. format->string has no
port argument and returns a string. format->port writes to its port argument (which must be an output
port, not a boolean), and returns an empty string. Then:
</p>
<pre>
(format #f ...) -> (format->string ...)
(format () ...) -> (format->port (current-output-port) ...)
(format #t ...) -> (display (format->string ...))
(format port ...) -> (display (format->string ...) port)
</pre>
<p>and the currently unavailable choice, format to port without creating a string:
<code>(format->port port ...)</code>.
</p>
</div>
<!--
:(objects->string "int: " 32 ", string: " "hi")
"int: 32, string: hi"
(define (cycle->string . objs)
(call-with-exit
(lambda (return)
(for-each
(lambda (obj)
(if (pair? obj)
(return
(string-append
(apply objects->string
(map (lambda (obj)
(if (pair? obj)
(car obj)
obj))
objs))
(apply cycle->string
(map (lambda (obj)
(if (pair? obj)
(cdr obj)
obj))
objs))))))
objs)
"")))
;;; (cycle->string ": " (list 1 2 3) " |")
:(objects->string "int: " 32 ", list with spaces: (" (cycle->string (list 1 2 3) " ") "), string: " "hi")
"int: 32, list with spaces: (1 2 3 ), string: hi"
:(let ((x 0) (y 0)) (string->objects "1 2" x y) (list x y))
(1 2)
-->
</blockquote>
<div class="header" id="hooks"><h4>hooks</h4></div>
<pre class="indented">
(<em class=def id="makehook">make-hook</em> . fields) ; make a new hook
(<em class=def id="hookfunctions">hook-functions</em> hook) ; the hook's list of 'body' functions
</pre>
<p>A hook is a function created by make-hook, and called (normally from C) when something interesting happens.
In GUI toolkits hooks are called callback-lists, in CL conditions,
in other contexts watchpoints or signals. s7 itself has several
hooks: <a href="#errorhook">*error-hook*</a>, <a href="#readerrorhook">*read-error-hook*</a>,
<a href="#unboundvariablehook">*unbound-variable-hook*</a>, *missing-close-paren-hook*, *rootlet-redefinition-hook*,
<a href="#loadhook">*load-hook*</a>, and *autoload-hook*.
make-hook is:
</p>
<pre class="indented">
(define (make-hook . args)
(let ((body ()))
(apply lambda* args
'(let ((result #<unspecified>))
(let ((e (curlet)))
(for-each (lambda (f) (f e)) body)
result))
())))
</pre>
<p>So the result of calling make-hook is a function (the lambda* that is applied to args above) that
contains a list of functions, 'body.
Each function in that list takes one argument, the hook.
Each time the hook itself is called, each of the body functions is called, and the value of 'result is returned.
That variable, and each of the hook's arguments are accessible to the hook's internal
functions by going through the environment passed to the internal functions. This is a bit circuitous;
here's a sketch:
</p>
<pre class="indented">
> (define h (make-hook '(a 32) 'b)) ; h is a function: (lambda* ((a 32) b) ...)
<em class="gray">h</em>
> (set! (hook-functions h) ; this sets ((funclet h) 'body)
(list (lambda (hook) ; each hook internal function takes one argument, the environment
(set! (hook 'result) ; this is the "result" variable above
(format #f "a: ~S, b: ~S" (hook 'a) (hook 'b))))))
<em class="gray">(#<lambda (hook)>)</em>
> (h 1 2) ; this calls the hook's internal functions (just one in this case)
<em class="gray">"a: 1, b: 2" ; we set "result" to this string, so it is returned as the hook application result</em>
> (h)
<em class="gray">"a: 32, b: #f"</em>
</pre>
<p>In C, to make a hook:
</p>
<pre class="indented">
hook = s7_eval_c_string("(make-hook '(a 32) 'b)");
s7_gc_protect(s7, hook);
</pre>
<p>And call it:
</p>
<pre class="indented">
result = s7_call(s7, hook, s7_list(s7, 2, s7_make_integer(s7, 1), s7_make_integer(s7, 2)));
</pre>
<div class="indented">
<pre>
(define-macro (hook . body) ; return a new hook with "body" as its body, setting "result"
`(let ((h (make-hook)))
(set! (hook-functions h) (list (lambda (h) (set! (h 'result) (begin ,@body)))))
h))
</pre>
</div>
<div class="header" id="variableinfo"><h4>variable info</h4></div>
<pre class="indented">
(<em class=def id="documentation">documentation</em> obj)
(<em class=def id="signature">signature</em> obj)
(<em class=def id="setter">setter</em> obj)
(<em class=def id="arity">arity</em> obj)
(<em class=def id="aritablep">aritable?</em> obj num-args)
(funclet proc)
(<em class=def id="proceduresource">procedure-source</em> proc)
(<em class=def id="procedurearglist">procedure-arglist</em> proc)
</pre>
<p>
<b>funclet</b> returns
a procedure's environment.
</p>
<pre class="indented">
> (funclet (let ((b 32)) (lambda (a) (+ a b))))
<em class="gray">(inlet 'b 32)</em>
> (funclet abs)
<em class="gray">(rootlet)</em>
</pre>
<p>
<b>setter</b> returns or sets the setter function associated with a procedure (set-car! with car, for example).
</p>
<p>
<b>procedure-source</b> returns the procedure source (a list):
</p>
<pre class="indented">
(define (procedure-arglist f) (cadr (procedure-source f)))
</pre>
<p><b>procedure-arglist</b> returns the procedure's argument list.
"procedure" here refers to functions and macros defined in s7, not built-in procedures.
</p>
<p>
<b>documentation</b> returns the documentation string associated with a procedure. This is normally
provided via the '+documentation+ variable in the function's environment. If you'd rather,
you can treat the initial string in the function's body as documentation.
</p>
<pre class="indented">
(define func
(let ((+documentation+ "helpful info"))
(lambda (a) a)))
> (documentation func)
<em class="gray">"helpful info"</em>
(define (cl-func)
"this is documentation"
123)
> (documentation cl-func)
<em class="gray">"this is documentation"</em>
</pre>
<p>Since documentation is a method, a function's documentation can be computed at run-time:
</p>
<pre class="indented">
(define func
(let ((documentation (lambda (f) (format #f "this is func's funclet: ~S" (funclet f)))))
(lambda (x)
(+ x 1))))
> (documentation func)
<em class="gray">"this is func's funclet: (inlet 'x ())"</em>
</pre>
<p>
<b>arity</b> takes any object and returns either #f if that object is not applicable,
or a cons containing the minimum and maximum number of arguments acceptable. If the maximum reported
is a really big number, that means any number of arguments is ok.
<b>aritable?</b> takes two arguments, an object and an integer, and returns #t if the object can be
applied to that many arguments. (For define* and friends, a key+value pair is considered to be one argument).
</p>
<pre class="indented">
> (define* (add-2 a (b 32)) (+ a b))
<em class="gray">add-2</em>
> (procedure-source add-2)
<em class="gray">(lambda* (a (b 32)) (+ a b))</em>
> (arity add-2)
<em class="gray">(0 . 2)</em>
> (aritable? add-2 1)
<em class="gray">#t</em>
> (aritable? add-2 2)
<em class="gray">#t</em>
> (aritable? add-2 3) ; we can call (add-2 1 :b 2), but
<em class="gray">#f</em> ; as mentioned above, the key+value pair is one argument
</pre>
<p>
<b>signature</b> is a list describing the argument types and returned value type
of the function. The first entry in the list is the return type, and the rest are
argument types. #t means any type is possible, and 'values means the function returns multiple values.
</p>
<pre class="indented">
> (signature round)
<em class="gray">(integer? real?)</em> ; round takes a real argument, returns an integer
> (signature vector-ref)
<em class="gray">(#t vector? . #1=(integer? . #1#))</em> ; trailing args are all integers (indices)
</pre>
<p>If an entry is a list, any of the listed types can occur:
</p>
<pre class="indented">
> (signature char-position)
<em class="gray">((boolean? integer?) (char? string?) string? integer?)</em>
</pre>
<p>which says that the first argument to char-position can be a string or a character,
and the return type can be either boolean or an integer. To specify the types returned
if multiple values are returned, use (values type1 ..). So the function:
</p>
<code>(define (f int) (case ((0) (values 0 1)) ((1) ((values 'a 1)) (else 0))))</code>
<p>could declare its signature to be
</p>
<code>(((values integer? integer?) (values symbol? integer?) integer?) integer?)</code>
;; or would it be better to omit the 'values and just have a list of types?
<p>
If the function is defined in scheme, its signature is the value of the '+signature+ variable
in its closure:
</p>
<pre class="indented">
> (define f1 (let ((+documentation+ "helpful info")
(+signature+ '(boolean? real?)))
(lambda (x)
(positive? x))))
<em class="gray">f1</em>
> (documentation f1)
<em class="gray">"helpful info"</em>
> (signature f1)
<em class="gray">(boolean? real?)</em>
</pre>
<p>We can do the same thing using methods:
</p>
<pre class="indented">
> (define f1 (let ((documentation (lambda (f) "helpful info"))
(signature (lambda (f) '(boolean? real?))))
(<em class=red>openlet</em> ; openlet alerts s7 that f1 has methods
(lambda (x)
(positive? x)))))
> (documentation f1)
<em class="gray">"helpful info"</em>
> (signature f1)
<em class="gray">(boolean? real?)</em>
</pre>
<p>signature can also be used to implement CL's 'the:
</p>
<pre class="indented">
(define-macro (the value-type form)
`((let ((+signature+ (list ,value-type)))
(lambda ()
,form))))
(display (+ 1 (<em class="red">the</em> integer? (+ 2 3))))
</pre>
<p>but the optimizer currently doesn't know how to take advantage of this pattern.
</p>
<p>You can obviously add your own methods:
</p>
<pre class="indented">
(define my-add
(let ((<em class="red">tester</em> (lambda ()
(if (not (= (my-add 2 3) 5))
(format #t "oops: (myadd 2 3) -> ~A~%"
(my-add 2 3))))))
(lambda (x y)
(- x y))))
(define (auto-test) ; scan the symbol table for procedures with testers
(let ((st (symbol-table)))
(for-each (lambda (f)
(let* ((fv (and (defined? f)
(symbol->value f)))
(testf (and (procedure? fv)
((funclet fv) '<em class="red">tester</em>))))
(when (procedure? testf) ; found one!
(testf))))
st)))
> (auto-test)
<em class="gray">oops: (myadd 2 3) -> -1</em>
</pre>
<p>Even the setter can be set this way:
</p>
<pre class="indented">
(define flocals
(let ((x 1))
(let ((+setter+ (lambda (val) (set! x val))))
(lambda ()
x))))
> (flocals)
<em class="gray">1</em>
> (setter flocals)
<em class="gray">#<lambda (val)></em>
> (set! (flocals) 32)
<em class="gray">32</em>
> (flocals)
<em class="gray">32</em>
</pre>
<blockquote>
<br>
<div class="indented">
<pre>
(define (for-each-subset func args)
;; form each subset of args, apply func to the subsets that fit its arity
(let subset ((source args)
(dest ())
(len 0))
(if (null? source)
(if (<em class=red>aritable?</em> func len) ; does this subset fit?
(apply func dest))
(begin
(subset (cdr source) (cons (car source) dest) (+ len 1))
(subset (cdr source) dest len)))))
</pre>
</div>
</blockquote>
<div class="header" id="evalstring"><h4>eval</h4></div>
<p>
<b>eval</b> evaluates its argument, a list representing a piece of code. It takes an optional
second argument, the environment in which the evaluation should take place. <b>eval-string</b>
is similar, but its argument is a string.
</p>
<pre class="indented">
> (eval '(+ 1 2))
<em class="gray">3</em>
> (eval-string "(+ 1 2)")
<em class="gray">3</em>
</pre>
<p>Leaving aside a few special cases, eval-string could be defined:
</p>
<pre class="indented">
(define-macro* (eval-string x e)
`(eval (with-input-from-string ,x read) (or ,e (curlet))))
</pre>
<div class="header" id="IO"><h4>IO and other OS functions</h4></div>
<p>Besides files, ports can also represent strings and functions. The string port functions
are:
</p>
<pre class="indented">
(with-output-to-string thunk) ; open a string port as current-output-port, call thunk, return string
(with-input-from-string string thunk) ; open string as current-input-port, call thunk
(call-with-output-string proc) ; open a string port, apply proc to it, return string
(call-with-input-string string proc) ; open string as current-input-port, apply proc to it
(open-output-string) ; open a string output port
(get-output-string port clear) ; return output accumulated in the string output port
(open-input-string string) ; open a string input port reading string
(<em class=def id="openinputfunction">open-input-function</em> function) ; open a function input port
(<em class=def id="openoutputfunction">open-output-function</em> function) ; open a function output port
</pre>
<pre class="indented">
> (let ((result #f)
(p (<em class=red>open-output-string</em>)))
(format p "this ~A ~C test ~D" "is" #\a 3)
(set! result (<em class=red>get-output-string</em> p))
(close-output-port p)
result)
<em class="gray">"this is a test 3"</em>
</pre>
<p>In get-output-string, if the optional 'clear' argument is #t, the port is cleared (the default in r7rs I think).
Other functions:
</p>
<ul>
<li>read-byte and write-byte: binary IO
<li>read-line: line-at-a-time reads, optional second argument #t to include the newline
<li>read-string (r7rs)
<li>current-error-port, set-current-error-port
<li><em class=def id="portfilename">port-filename</em> and
<em class=def id="portlinenumber">port-line-number</em> (input ports)
<li><em class=def id="portposition">port-position</em> (input port, settable)
<li><em class=def id="portstring">port-string</em> (string port, settable)
<li><em class=def id="portfile">port-file</em>
</ul>
<p>Use length to get the length in bytes of an input port's file or string.
port-line-number is settable (for fancy *#readers*).
<b>port-position</b> is the position in bytes of the reader in the port. It is settable.
<b>port-string</b> is the string contents of a string port. It is also settable.
<b>port-file</b> is intended for use with the *libc* library. It returns a c-pointer
containing the FILE* pointer associated with the file port (except in Windows):
</p>
<pre class="indented">
(call-with-input-file "s7test.scm"
(lambda (p)
(with-let (sublet *libc* :file (<em class=red>port-file</em> p))
(fseek file 1000 SEEK_SET))))
</pre>
<p>The variable (*s7* 'print-length) sets
the upper limit on how many elements of a sequence are printed by object->string and format.
</p>
<p>
When running s7 behind a GUI, you often want input to come from and output to go to
arbitrary widgets. The function ports provide a way to redirect IO in C. See <a href="s7-ffi.html#functionportexample">redirect display</a>
for an example.
The function ports call a function rather than reading or writing the data to a string or file.
See nrepl.scm and s7test.scm for examples. The function-port function is accessible as
<code>((object->let function-port) 'function)</code>. These ports are even more esoteric than
their C-side cousins. An example that traps current-ouput-port output:
</p>
<pre class="indented">
(let* ((str ())
(stdout-wrapper (open-output-function
(lambda (c)
(set! str (cons c str))))))
(let-temporarily (((current-output-port) stdout-wrapper))
(write-char #\a)
...))
</pre>
<blockquote>
<div class="indented">
<p>
The end-of-file object is #<eof>.
When the read function encounters the constant #<eof> it returns #<eof>.
This is neither inconsistent nor unusual: read returns either a form or
#<eof>. If read encounters a form that contains #<eof>, it returns a
form containing #<eof>, just as with any other constant.
</p>
<pre class="indented">
> (with-input-from-string "(or x #<eof>)" read)
<em class="gray">(or x #<eof>)</em>
> (eof-object? (with-input-from-string "'#<eof>" read))
<em class="gray">#f</em>
</pre>
<p>If read hits the end of
the input while reading a form, it raises an error (e.g. "missing close paren").
If it encounters
#<eof> all by itself at the top level (this never happens),
it returns that #<eof>. But this is specific to read, not (for example) load:
</p>
<pre class="indented">
;; say we have "t234.scm" with:
(display "line 1") (newline)
#<eof>
(display "line 2") (newline)
;; end of t234.scm
> (load "t234.scm")
<em class="gray">line 1
line 2</em>
(with-input-from-file "t234.scm"
(lambda ()
(do ((c (read) (read)))
((eof-object? c))
(eval c))))
<em class="gray">line 1</em>
</pre>
<p>
Built-in #<eof> has lots of
uses, and as far as I can see, no drawbacks. For example,
it is common to call
read (or one of its friends) in a loop which first checks for #<eof>, then falls into
a case statement. In s7, we can dispense with the extra if (and let), and include
the #<eof> in the case statement: <code>(case (read-char) ((#<eof>) (quit-reading)) ((#\a)...))</code>.
Another example: <code>(or (eof-object? x) (eqv x 24)...)</code> can be instead: <code>(memv x '(#<eof> 24 ...)</code>.
(All the discussions online that I've seen of #<eof> or its equivalent confuse the thing (end of file indication) with its name (#<eof>).
</p>
</div>
<div class="indented">
<p>
The default IO ports are *stdin*, *stdout*, and *stderr*.
*stderr* is useful if you want to make sure output is flushed out immediately.
The default output port is *stdout* which buffers output until a newline is seen.
</p>
</div>
<div class="indented">
<p>An environment can be treated as an IO port, providing what Guile calls a "soft port":
</p>
<pre class="indented">
(define (call-with-input-vector v proc)
(let ((i -1))
(proc (openlet (inlet 'read (lambda (p) (v (set! i (+ i 1)))))))))
</pre>
<p>Here the IO port is an open environment that redefines the "read" function so that it
returns the next element of a vector. See stuff.scm for call-with-output-vector.
The "proc" argument above can also be a macro, giving you a kludgey way to get around
the dumb "lambda". Here are more useful examples:
</p>
<pre class="indented">
(openlet ; a soft port for format that sends its output to *stderr* and returns the string
(inlet 'format (lambda (port str . args)
(apply format *stderr* str args))))
(define (open-output-log name)
;; return a soft output port that does not hold its output file open
(define (logit name str)
(let ((p (open-output-file name "a")))
(display str p)
(close-output-port p)))
(openlet
(inlet :name name
:format (lambda (p str . args) (logit (p 'name) (apply format #f str args)))
:write (lambda (obj p) (logit (p 'name) (object->string obj #t)))
:display (lambda (obj p) (logit (p 'name) (object->string obj #f)))
:write-string (lambda (str p) (logit (p 'name) str))
:write-char (lambda (ch p) (logit (p 'name) (string ch)))
:newline (lambda (p) (logit (p 'name) (string #\newline)))
:output-port? (lambda (p) #t)
:close-output-port (lambda (p) #f)
:flush-output-port (lambda (p) #f))))
(let ((p (open-output-log "logit.data")))
(format p "this is a test~%")
(format p "line: ~A~%" 2))
</pre>
</div>
<div class="indented">
<p>binary-io.scm in the Snd package has functions that read and write integers and floats in
both endian choices in a variety of sizes.
</p>
</div>
</blockquote>
<p>If the compile time switch WITH_SYSTEM_EXTRAS is 1, several additional OS-related and
file-related functions are built-in. This is work in progress; currently this switch
adds:
</p>
<pre class="indented">
(directory? str) ; return #t if str is the name of a directory
(file-exists? str) ; return #t if str names an existing file
(delete-file str) ; try to delete the file, return 0 is successful, else -1
(getenv var) ; return the value of an environment variable: (getenv "HOME")
(directory->list dir) ; return contents of directory as a list of strings (if HAVE_DIRENT_H)
(system command) ; execute command, if optional second arg is #t output is returned as a string
</pre>
<p>But maybe this is not needed; see <a href="s7-scm.html#cload">cload.scm</a> below for
a more direct approach.
</p>
<div class="header" id="errors"><h4>error handling</h4></div>
<pre class="indented">
(error tag . info) ; signal an error of type tag with addition information
(catch tag body err) ; if error of type tag signalled in body (a thunk), call err with tag and info
(throw tag . info) ; jump to corresponding catch
</pre>
<p>s7's error handling mimics that of Guile. An error is signalled
via the error function, and can be trapped and dealt with via <em class=def id="catch">catch</em>.
</p>
<pre class="indented">
> (<em class=red>catch</em> 'wrong-number-of-args
(lambda () ; code protected by the catch
(abs 1 2))
(lambda args ; the error handler
(apply format #t (cadr args))))
<em class="gray">"abs: too many arguments: (1 2)"</em>
> (<em class=red>catch</em> 'division-by-zero
(lambda () (/ 1.0 0.0))
(lambda args (string->number "+inf.0")))
<em class="gray">+inf.0</em>
(define-macro (catch-all . body)
`(<em class=red>catch</em> #t (lambda () ,@body) (lambda args args)))
</pre>
<p>
catch has 3 arguments: a tag indicating what error to catch (#t = anything),
the code, a thunk, that the catch is protecting, and the function to call
if a matching error occurs during the evaluation of the thunk.
The tag is matched to the error type with eq?.
The error handler
takes a rest argument which will hold whatever the error function chooses to pass it.
The error function itself takes at least 2 arguments, the error type, a symbol,
and the error message. There may also be other arguments describing the error.
The default action, in the absence of any catch, is to treat the message as
a format control string, apply format to it and the other arguments, and
send that info to the current-error-port:
</p>
<pre class="indented">
(catch #t
(lambda ()
(error 'oops))
(lambda args
(format (current-error-port) "~A: ~A~%~A[~A]:~%~A~%"
(car args) ; the error type
(apply format #f (cadr args)) ; the error info
(port-filename) (port-line-number); error file location
(stacktrace)))) ; and a stacktrace
</pre>
<blockquote>
<div class="indented">
<p>Normally when reading a file, we have to check for #<eof>, but we can let s7
do that:
</p>
<pre>
(define (copy-file infile outfile)
(call-with-input-file infile
(lambda (in)
(call-with-output-file outfile
(lambda (out)
(<em class=red>catch</em> 'wrong-type-arg ; s7 raises this error if write-char gets #<eof>
(lambda ()
(do () () ; read/write until #<eof>
(write-char (read-char in) out)))
(lambda err
outfile)))))))
</pre>
<p>catch is not limited to error handling:
</p>
<pre class="indented">
(define (map-with-exit func . args)
;; map, but if early exit taken, return the accumulated partial result
;; func takes escape thunk, then args
(let* ((result ())
(escape-tag (gensym))
(escape (lambda () (throw escape-tag))))
(<em class=red>catch</em> escape-tag
(lambda ()
(let ((len (apply max (map length args))))
(do ((ctr 0 (+ ctr 1)))
((= ctr len) (reverse result)) ; return the full result if no throw
(let ((val (apply func escape (map (lambda (x) (x ctr)) args))))
(set! result (cons val result))))))
(lambda args
(reverse result))))) ; if we catch escape-tag, return the partial result
(define (truncate-if func lst)
(map-with-exit (lambda (escape x) (if (func x) (escape) x)) lst))
> (truncate-if even? #(1 3 5 -1 4 6 7 8))
<em class="gray">(1 3 5 -1)</em>
</pre>
<p>But this is less useful than map (it can't map over a hash-table for example),
and is mostly reimplementing built-in code. Perhaps s7 should have an extension
of map (and more usefully, for-each) that is patterned after dynamic-wind:
<code>(dynamic-for-each init-func main-func end-func . args)</code> where init-func
is called with one argument, the length of the shortest sequence argument (for-each
and map know this in advance); main-func takes n arguments where n matches
the number of sequences passed; and end-func is called even if a jump out of main-func
occurs (like dynamic-wind in this regard). In the dynamic-map case, the end-func
takes one argument, the current, possibly partial, result list. dynamic-for-each
then could easily (but maybe not efficiently) implement generic functions such as ->list, ->vector, and
->string (converting any sequence into a sequence of some other type).
map-with-exit would be
</p>
<pre class="indented">
(define (map-with-exit func . args)
(let ((result ()))
(call-with-exit
(lambda (quit)
(apply dynamic-map #f ; no init-func in this case
(lambda main-args
(apply func quit main-args))
(lambda (res)
(set! result res))
args)))
result))
</pre>
</div>
<div class="indented">
<p>With all the lambda boilerplate, nested catches are hard to read:
</p>
<pre class="indented">
(catch #t
(lambda ()
(catch 'division-by-zero
(lambda ()
(catch 'wrong-type-arg
(lambda ()
(abs -1))
(lambda args (format () "got a bad arg~%") -1)))
(lambda args 0)))
(lambda args 123))
</pre>
<p>Perhaps we need a macro:
</p>
<pre class="indented">
(define-macro (catch-case clauses . body)
(let ((base (cons 'lambda (cons () body))))
(for-each (lambda (clause)
(let ((tag (car clause)))
(set! base `(lambda ()
(catch ',(or (eq? tag 'else) tag)
,base
,@(cdr clause))))))
clauses)
(caddr base)))
;;; the code above becomes:
(catch-case ((wrong-type-arg (lambda args (format () "got a bad arg~%") -1))
(division-by-zero (lambda args 0))
(else (lambda args 123)))
(abs -1))
</pre>
<p>This is similar to r7rs scheme's "guard", but I don't want a pointless thunk for the body of the catch.
Along the same lines:
</p>
<pre class="indented">
(define (catch-if test func err)
(catch #t
func
(lambda args
(apply (if (test (car args)) err throw) args)))) ; if not caught, re-raise the error via throw
(define (catch-member lst func err)
(catch-if (lambda (tag) (member tag lst)) func err))
(define-macro (catch* clauses . error)
;; try each clause until one evaluates without error, else error:
;; (macroexpand (catch* ((+ 1 2) (- 3 4)) 'error))
;; (catch #t (lambda () (+ 1 2)) (lambda args (catch #t (lambda () (- 3 4)) (lambda args 'error))))
(define (builder lst)
(if (null? lst)
(apply values error)
`(catch #t (lambda () ,(car lst)) (lambda args ,(builder (cdr lst))))))
(builder clauses))
</pre>
</div>
<!--
(define (or-catch . funks)
(call-with-exit
(lambda (return)
(for-each
(lambda (f)
(catch #t
(lambda ()
(return (f)))
(lambda args
(case (car args)
((wrong-type-arg) ...)
(...)
(else (apply throw args))))))
funks))))
-->
</blockquote>
<p>When an error is encountered, and when s7 is interrupted via <a href="s7-ffi.html#beginhook">begin_hook</a>,
(<em class=def id="owlet">owlet</em>) returns an environment that contains
additional info about that error:
</p>
<ul>
<li>error-type: the error type or tag, e.g. 'division-by-zero
<li>error-data: the message or information passed by the error function
<li>error-code: the code that s7 thinks triggered the error
<li>error-line: the line number of that code
<li>error-file: the file name of that code
<li>error-history: previous evaluations leading to the error (a circular list)
</ul>
<p>The error-history field depends on the compiler flag WITH_HISTORY. See ow! in
stuff.scm for one way to display this data. The *s7* field 'history-size sets the size of the buffer.
</p>
<blockquote>
<div class="indented">
<p>To find a variable's value at the point of the error: <code>((owlet) var)</code>.
To list all the local bindings from the error outward:
</p>
<pre class="indented">
(do ((e (outlet (owlet)) (outlet e)))
((eq? e (rootlet)))
(format () "~{~A ~}~%" e))
</pre>
<p>To see the current s7 stack, <code>(stacktrace)</code>.
To evaluate the error handler in the environment of the error:
</p>
<pre class="indented">
(let ((x 1))
(catch #t
(lambda ()
(let ((y 2))
(error 'oops)))
(lambda args
(with-let (sublet (owlet) :args args) ; add the error handler args
(list args x y))))) ; we have access to 'y'
</pre>
<p>To limit the maximum size of the stack, set (*s7* 'max-stack-size).
</p>
</div>
</blockquote>
<p>The hook <em class=def id="errorhook">*error-hook*</em> provides a way to specialize error reporting.
Its arguments are named 'type and 'data. It is called if there are no catches.
</p>
<pre class="indented">
(set! (hook-functions *error-hook*)
(list (lambda (hook)
(apply format *stderr* (hook 'data))
(newline *stderr*))))
</pre>
<p><em class=def id="readerrorhook">*read-error-hook*</em> provides two hooks into the reader.
A major problem when reading code written for other Schemes is that each Scheme provides
a plethora of idiosyncratic #-names (even special character names), and \ escapes in string
constants. *read-error-hook* provides a way to handle these weird cases. If a #-name
is encountered that s7 can't deal with, *read-error-hook* is called with two arguments,
#t and the string representing the constant. If you set (hook 'result), that result is
returned to the reader. Otherwise a 'read-error is raised and you drop into the error handler.
Similarly, if some bizarre \ use occurs, *read-error-hook* is called with two arguments,
#f and the offending character. If you return a character, it is passed to the reader;
otherwise you get an error. lint.scm has an example.
</p>
<p><em class=def id="rootletredefinitionhook">*rootlet-redefinition-hook*</em> is called when
a top-level variable is redefined (via define and friends, not set!).
</p>
<pre class="indented">
(set! (hook-functions *rootlet-redefinition-hook*)
(list (lambda (hook)
(format *stderr* "~A ~A~%" (hook 'name) (hook 'value)))))
</pre>
<p>will print out the variable's name and the new value.
</p>
<div class="indented">
<p>The s7-built-in catch tags are 'wrong-type-arg, 'syntax-error, 'read-error, 'unbound-variable,
'out-of-memory, 'wrong-number-of-args, 'format-error, 'out-of-range, 'division-by-zero, 'io-error, and 'bignum-error.
</p>
</div>
<div class="header" id="autoload"><h4>autoload</h4></div>
<!-- INDEX autoload:autoload -->
<p>
If s7 encounters an unbound variable, it first looks to see if it has any autoload information about it.
This info can be declared via autoload, a function of two arguments, the
symbol that triggers the autoload, and either a filename or a function. If a filename, s7
loads that file; if a function, it is called with one argument, the current (calling) environment.
</p>
<pre class="indented">
(autoload 'channel-distance "dsp.scm")
;; now if we subsequently call channel-distance but forget to load "dsp.scm" first,
;; s7 loads "dsp.scm" itself, and uses its definition of channel-distance.
;; The C-side equivalent is s7_autoload.
;; here is the cload.scm case, loading j0 from the math library if it is called:
(autoload 'j0
(lambda (e)
(unless (provided? 'cload.scm)
(load "cload.scm"))
(c-define '(double j0 (double)) "" "math.h")
(varlet e 'j0 j0)))
</pre>
<p>The entity (hash-table or environment probably) that holds the autoload info is named *autoload*.
If after checking autoload, the symbol is still unbound, s7 calls
<em class=def id="unboundvariablehook">*unbound-variable-hook*</em>.
The offending symbol is named 'variable in the hook environment.
If after running *unbound-variable-hook*, the symbol is still unbound,
s7 calls the error handler.
</p>
<p>The autoloader knows about s7 environments used as libraries, so, for example,
you can <code>(autoload 'j0 "libm.scm")</code>, then use j0 in scheme code. The first
time s7 encounters j0, j0 is undefined, so
s7 loads libm.scm. That load returns the C math library as the environment *libm*.
s7 then automatically looks for j0 in *libm*, and defines it for you.
So the result is the same as if you had defined j0 yourself in C code.
You can use the r7rs library mechanism here, or with-let, or
whatever you want! (In Snd, libc, libm, libdl, and libgdbm are automatically
tied into s7 via autoload, so if you call, for example, frexp, libm.scm
is loaded, and frexp is exported from the *libm* environment, then the
evaluator soldiers on, as if frexp had always been defined in s7).
You can also import all of (say) gsl into the current environment
via <code>(varlet (curlet) *libgsl*)</code>.
</p>
<div class="header" id="constants"><h4>define-constant</h4></div>
<p>
<b><em class=def id="defineconstant">define-constant</em></b> defines a symbol whose value is always the same (within the current lexical scope),
<b><em class=def id="constantp">constant?</em></b> returns #t if its argument is a constant,
<b><em class=def id="immutableb">immutable!</em></b> declares a sequence to be immutable (its elements can't be changed), and
<b><em class=def id="immutablep">immutable?</em></b> returns #t if its argument is immutable.
</p>
<pre class="indented">
> (define v (immutable! (vector 1 2 3)))
<em class="gray">#(1 2 3)</em>
> (vector-set! v 0 23)
<em class="red">error</em><em class="gray">: can't vector-set! #(1 2 3) (it is immutable)</em>
> (immutable? v)
<em class="gray">#t</em>
> (define-constant var 32)
<em class="gray">var</em>
> (set! var 1)
<em class="gray">;set!: can't alter immutable object: var</em>
> (let ((var 1)) var)
<em class="gray">;can't bind or set an immutable object: var, line 1</em>
</pre>
<p>To make immutable a binding in a particular let, pass the symbol (quoted) as the first argument and
the let as the second. If the first argument is a list, the entire list is set to be immutable.
To set only the first n members of the list immutable, pass n as the second argument.
</p>
<p>There is one complication here. <code>(immutable! let)</code> closes the let in the sense
that you can't add locals to or delete locals from the let. You can still set! the locals. To make
the locals themselves immutable:
</p>
<pre class="indented">
(define (vars-immutable! L)
(with-let L
(for-each (lambda (f)
(immutable! (car f)))
(curlet)))
L)
</pre>
<p>Now <code>(vars-immutable! let)</code> makes it an error to set! any of the locals, but you
can add locals to the let.
You can speed up evaluation by doing this because it tells the optimizer that the current entries in the let will not change.
To completely petrify the let, <code>(immutable! (vars-immutable! let))</code>.
To make a function's documentation immutable: <code>(with-let (funclet 'f2) (immutable! '+documentation+))</code>,
and similarly for other function closure entries.
</p>
<p>
immutable! blocks changes from outside an object (via string-set! etc), but does not affect internal changes, so it has no effect on
iterators, ports, random-state objects, c-objects, or functions used as iterators. If (*s7* 'safety)
is greater than 0 (no safety), s7 raises a warning when immutable! is called with an argument that ignores it.
</p>
<p>define-constant blocks any attempt to set! or shadow the constant (lexically speaking of course),
so local constants behave as you'd expect:
</p>
<pre class="indented">
> (let () (define-constant x 3) (let ((x 32)) x))
<em class="red">error</em><em class="gray">: can't bind an immutable object: ((x 32))</em>
> (let ((x 3)) (set! x (let () (define-constant x 32) x))) ; outer x is not a constant
32
</pre>
<p>But watch out for deferred bindings:
</p>
<pre class="indented">
> (define (func a) (let ((cvar (+ a 1))) cvar))
<em class="gray">func</em>
> (define-constant cvar 23) ; cvar is now globally constant so it can't be shadowed
<em class="gray">23</em>
> (func 1) ; here we're trying to shadow cvar
<em class="red">error</em><em class="gray">: can't bind an immutable object: ((cvar (+ a 1)))</em>
> (let ((x 1))
(define z (let ()
(define-constant x 3)
(lambda (y)
(let ((x y)) ; this x is the inner constant x
x))))
(z 1)) ; so this is an error even though the outer x is not a constant
<em class="red">error</em><em class="gray">: can't bind an immutable object: ((x y))</em>
</pre>
<p>
A function can also be a constant. In some cases, the optimizer can take advantage
of this information to speed up function calls.
</p>
<p>Constants are very similar to things such as keywords (no set, always return itself as its value),
variable trace (informative function upon set or keeping a history of past values), typed variables (restricting a
variable's values or doing automatic conversions upon set), and notification upon set (either in Scheme
or in C; I wanted this many years ago in Snd). The notification function is especially useful if
you have a Scheme variable and want to reflect any change in its value immediately in C (see <a href="s7-ffi.html#notify">notification in C</a>).
In s7, setter sets this function.
</p>
<p>Each environment is a set of symbols and their associated values. setter places a function (or macro) between a symbol
and its value in a given environment. The setter function takes two arguments, the symbol and the new value, and
returns the value that is actually set. If the setter function accepts a third argument, the current (symbol-relative) environment
is also passed (the weird argument order is an historical artifact).
</p>
<pre class="indented">
(define e ; save environment for use below
(let ((x 3) ; will always be an integer
(y 3) ; will always keep its initial value
(z 3)) ; will report set!
(set! (setter 'x) (lambda (s v) (if (integer? v) v x)))
(set! (setter 'y) (lambda (s v) y))
(set! (setter 'z) (lambda (s v) (format *stderr* "z ~A -> ~A~%" z v) v))
(set! x 3.3) ; x does not change because 3.3 is not an integer
(set! y 3.3) ; y does not change
(set! z 3.3) ; prints "z 3 -> 3.3"
(curlet)))
> e
<em class="gray">(inlet 'x 3 'y 3 'z 3.3)</em>
>(begin (set! (e 'x) 123) (set! (e 'y) #()) (set! (e 'z) #f))
;; prints "z 3.3 -> #f"
> e
<em class="gray">(inlet 'x 123 'y 3 'z #f)</em>
> (define-macro (reflective-let vars . body)
`(let ,vars
,@(map (lambda (vr)
`(set! (setter ',(car vr))
(lambda (s v)
(format *stderr* "~S -> ~S~%" s v)
v)))
vars)
,@body))
<em class="gray">reflective-let</em>
> (reflective-let ((a 1)) (set! a 2))
<em class="gray">2</em> ; prints "a -> 2"
>(let ((a 0))
(set! (setter 'a)
(let ((history (make-vector 3 0))
(position 0))
(lambda (s v)
(set! (history position) v)
(set! position (+ position 1))
(if (= position 3) (set! position 0))
v)))
(set! a 1)
(set! a 2)
((funclet (setter 'a)) 'history))
<em class="gray">#(1 2 0)</em>
</pre>
<p>See also typed-let in stuff.scm.
define-constant is more restrictive than a setter that raises an error: the latter
does not block nested (possibly non-constant) bindings of the symbol. The setters
are kind of ugly. Here's a macro that lets you put the let variable's setter after
the initial value:
</p>
<pre class="indented">
(define-macro (let/setter vars . body)
;; (let/setter ((name value [setter])...) ...)
(let ((setters (map (lambda (binding)
(and (pair? (cddr binding))
(caddr binding)))
vars))
(gsetters (gensym)))
`(let ((,gsetters (list ,@setters))
,@(map (lambda (binding)
(list (car binding) (cadr binding)))
vars))
,@(do ((s setters (cdr s))
(var vars (cdr var))
(i 0 (+ i 1))
(result ()))
((null? s)
(reverse result))
(if (car s)
(set! result (cons `(set! (setter (quote ,(caar var))) (list-ref ,gsetters ,i)) result))))
,@body)))
(let ((a 3))
(let/setter ((a 1)
(b 2 (lambda (s v)
(+ v a)))) ; this is the outer "a"
(set! a (+ a 1))
(set! b (+ a b))
(display (list a b)) (newline)))
</pre>
<div class="header" id="miscellanea"><h4>marvels and curiousities</h4></div>
<p>
<b><em class=def id="loadpath">*load-path*</em></b> is a list of directories to search when loading a file.
<b><em class=def id="loadhook">*load-hook*</em></b> is a hook whose functions are called just before a file is loaded.
The hook function argument, named 'name, is the filename.
While loading, port-filename and
port-line-number of the current-input-port can tell you
where you are in the file. This data is also available after loading via <em class=def id="pairlinenumber">pair-line-number</em>
and <em class=def id="pairfilename">pair-filename</em>.
</p>
<pre class="indented">
(set! (hook-functions *load-hook*)
(list (lambda (hook)
(format () "loading ~S...~%" (hook 'name)))))
(set! (hook-functions *load-hook*)
(cons (lambda (hook)
(format *stderr* "~A~%"
(system (string-append "./snd lint.scm -e '(begin (lint \"" (hook 'name) "\") (exit))'") #t)))
(hook-functions *load-hook*)))
</pre>
<p>Here's a *load-hook* function that adds the loaded file's directory
to the *load-path* variable so that subsequent loads don't need to specify
the directory:
</p>
<pre class="indented">
(set! (hook-functions <em class=red>*load-hook*</em>)
(list (lambda (hook)
(let ((pos -1)
(filename (hook 'name)))
(do ((len (length filename))
(i 0 (+ i 1)))
((= i len))
(if (char=? (filename i) #\/)
(set! pos i)))
(if (positive? pos)
(let ((directory-name (substring filename 0 pos)))
(if (not (member directory-name <em class=red>*load-path*</em>))
(set! <em class=red>*load-path*</em> (cons directory-name *load-path*)))))))))
</pre>
<div class="separator"></div>
<p>As in Common Lisp, <b><em class=def id="featureslist">*features*</em></b> is a list describing what is currently loaded into s7. You can
check it with the <b>provided?</b> function, or add something to it with <b>provide</b>. In my version of Snd,
at startup *features* is:
</p>
<pre class="indented">
> *features*
<em class="gray">(snd-24.7 snd24 snd audio snd-s7 snd-motif gsl alsa xm clm6 clm
sndlib gcc linux autoload dlopen system-extras overflow-checks ieee-float
complex-numbers ratios s7-10.12 s7)</em>
> (provided? 'gsl)
<em class="gray">#t</em>
</pre>
<p>The other side of <code>provide</code> is <em class=def id="requires7">require</em>.
<code>(require . things)</code> finds each thing
(via <a href="#autoload">autoload</a>), and if that thing has not already been loaded,
loads the associated file. <code>(require integrate-envelope)</code>
loads "env.scm", for example; in this case it is equivalent to
simply using integrate-envelope, but if placed at the start of
a file, it documents that you're using that function.
In the more normal use, <code>(require snd-ws.scm)</code>
looks for the file that has <code>(provide 'snd-ws.scm)</code>
and if it hasn't already been loaded, loads it ("ws.scm" in this case).
To add your own files to this mechanism, add the provided symbol via <a href="#autoload">autoload</a>.
Since load can take an environment argument, *features* and its friends follow block structure.
So, for example, (let () (require stuff.scm) ...) loads "stuff.scm" into the local environment,
not globally.
</p>
<div class="indented">
<p>*features* is an odd variable: it is spread out across the chain of environments, and
can hold features in an intermediate environment that aren't in subsequent (nested) values.
One simple way this can happen is to load a file in a let, but cause the load to happen
at the top level. The provided entities get added to the top-level *features* value,
not the current let's value, but they are actually accessible locally. So *features*
is a merge of all its currently accessible values, vaguely like call-next-method in
CLOS. We can mimic this behavior:
</p>
<pre class="indented">
(let ((x '(a)))
(let ((x '(b)))
(define (transparent-memq sym var e)
(let ((val (symbol->value var e)))
(or (and (pair? val)
(memq sym val))
(and (not (eq? e (rootlet)))
(transparent-memq sym var (outlet e))))))
(let ((ce (curlet)))
(list (transparent-memq 'a 'x ce)
(transparent-memq 'b 'x ce)
(transparent-memq 'c 'x ce)))))
'((a) (b) #f)
</pre>
</div>
<!--
(let ((spread-function (lambda (x e) (+ x 1))))
(let ((spread-function (lambda (x e) (+ x 2))))
(let ((x 3))
(define (spread-function x e)
(let ((val x))
(do ((e1 e (outlet e1)))
((eq? e1 (rootlet)) val)
(let ((f (symbol->value 'spread-function e1)))
(if (procedure? f)
(set! val (f val (rootlet))))))))
(spread-function x (curlet)))))
6
-->
<div class="separator"></div>
<p>Multi-line and in-line comments can be enclosed in #| and |#.
<code>(+ #| add |# 1 2)</code>.
</p>
<div class="indented">
<p>Leaving aside this case and the booleans, #f and #t, you can specify your own handlers for
tokens that start with "#". <b><em class=def id="sharpreaders">*#readers*</em></b> is a list of pairs: <code>(char . func)</code>.
"char" refers to the first character after the sharp sign (#). "func" is a function of
one argument, the string that follows the #-sign up to the next delimiter. "func" is called
when #<char> is encountered. If it returns something other than #f, the #-expression
is replaced with that value. Scheme has several predefined #-readers for cases such
as #b1, #\a, and so on, but you can override these if you like. If the string
passed in is not the complete #-expression, the function can use read-char or read to get the
rest. Say we'd like #t<number> to interpret the number in base 12:
</p>
<pre class="indented">
(set! *#readers* (cons (cons #\t (lambda (str) (string->number (substring str 1) 12))) *#readers*))
> #tb
<em class="gray">11</em>
> #t11.3
<em class="gray">13.25</em>
</pre>
<p>Or have #C(real imag) be read as a complex number:
</p>
<pre class="indented">
(set! *#readers* (cons (cons #\C (lambda (str) (apply complex (read)))) *#readers*))
> #C(1 2)
<em class="gray">1+2i</em>
</pre>
<p>Here's a reader macro for read-time evaluation:
</p>
<pre class="indented">
(set! *#readers*
(cons (cons #\. (lambda (str)
(if (string=? str ".")
(eval (read)) ; e.g. #.(+ 1 2)
(symbol->value (string->symbol (substring str 1)))))) ; e.g. #.pi
*#readers*))
> '(1 2 #.(* 3 4) 5)
<em class="gray">(1 2 12 5)</em>
</pre>
<p>And a reader that implements #[...]# for literal hash-tables:
</p>
<pre class="indented">
> (set! *#readers*
(list (cons #\[ (lambda (str)
(let ((h (make-hash-table)))
(do ((c (read) (read)))
((eq? c ']#) h) ; ]# is a symbol from the reader's point of view
(set! (h (car c)) (cdr c))))))))
<em class="gray">((#\[ . #<lambda (str)>))</em>
> #[(a . 1) (b . #[(c . 3)]#)]#
<em class="gray">(hash-table '(b . (hash-table '(c . 3))) '(a . 1))</em>
</pre>
<p>To return no value from a reader, use <code>(values)</code>.
</p>
<pre class="indented">
> (set! *#readers* (cons (cons #\; (lambda (str) (if (string=? str ";") (read)) (values))) *#readers*))
<em class="gray">((#\; . #<lambda (str)>))</em>
> (+ 1 #;(* 2 3) 4)
<em class="gray">5</em>
</pre>
<p>Here is CL's #+ reader:
</p>
<pre class="indented">
(define (sharp-plus str)
;; str here is "+", we assume either a symbol or an expression involving symbols follows
(let ((e (if (string=? str "+")
(read) ; must be #+(...)
(string->symbol (substring str 1)))) ; #+feature
(expr (read))) ; this is the expression following #+
(if (symbol? e)
(if (provided? e)
expr
(values))
(if (not (pair? e))
(error 'wrong-type-arg "strange #+ chooser: ~S~%" e)
(begin ; evaluate the #+(...) expression as in cond-expand
(define (traverse tree)
(if (pair? tree)
(cons (traverse (car tree))
(case (cdr tree) ((())) (else => traverse)))
(if (memq tree '(and or not)) tree
(and (symbol? tree) (provided? tree)))))
(if (eval (traverse e))
expr
(values)))))))
</pre>
<p>See also the <a href="#circularlistreader">#n=</a> reader below.</p>
</div>
<div class="separator"></div>
<p id="makelist">(<b>make-list</b> length (initial-element #f)) returns a list of 'length' elements defaulting to 'initial-element'.
</p>
<div class="separator"></div>
<pre class="indented">
(<em class=def id="charposition">char-position</em> char-or-string searched-string (start 0))
(<em class=def id="stringposition">string-position</em> substring searched-string (start 0))
</pre>
<p>
<b>char-position</b> and <b>string-position</b> search a string for the occurrence of a character,
any of a set of characters, or a string. They return either #f if none is found, or the position
within the searched string of the first occurrence. The optional third argument sets where the
search starts in the second argument.
</p>
<p>If char-position's first argument is a string, it is treated as a set of characters, and
char-position looks for the first occurrence of any member of that set.
Currently, the strings involved are assumed to be C strings (don't expect embedded nulls
to work right in this context).
</p>
<pre class="indented">
(call-with-input-file "s7.c" ; report any lines with "static " but no following open paren
(lambda (file)
(let loop ((line (read-line file #t)))
(or (eof-object? line)
(let ((pos (<em class=red>string-position</em> "static " line)))
(if (and pos
(not (<em class=red>char-position</em> #\( (substring line pos))))
(if (> (length line) 80)
(begin (display (substring line 0 80)) (newline))
(display line))))
(loop (read-line file #t)))))))
</pre>
<div class="separator"></div>
<pre class="indented">
(<em class=def id="substringuncopied">substring-uncopied</em> str (start 0) end)
</pre>
<p>
<b>substring-uncopied</b> exists because there are cases where you want substring, but don't need a copy made
of the string. <code>substring-uncopied</code> does not GC protect the original string, but obviously depends on it; it is intended
for very brief uses where there is no chance that the GC will be called. Normally the optimizer can
find these cases, so for example, there's no need to use <code>substring-uncopied</code> in <code>(string-length (substring str 1))</code>.
</p>
<div class="separator"></div>
<p id="keywords">
Keywords exist mainly for define*'s benefit. The keyword functions are:
<b>keyword?</b>, <b>string->keyword</b>, <b>symbol->keyword</b>, and <b>keyword->symbol</b>.
A keyword is a symbol that starts or ends with a colon. The colon
is considered to be a part of the symbol name. A keyword is a constant that evaluates to itself.
</p>
<div class="separator"></div>
<pre class="indented">
(<em class=def id="symboltable">symbol-table</em>)
(<em class=def id="symboltovalue">symbol->value</em> sym (env (curlet)))
(<em class=def id="symboltodynamicvalue">symbol->dynamic-value</em> sym)
(<em class=def id="symbolinitialvalue">symbol-initial-value</em> sym) ; settable
(<em class=def id="definedp">defined?</em> sym (env (curlet)) ignore-rootlet)
</pre>
<p>
<code>defined?</code> returns #t if the symbol is defined in the environment:
</p>
<pre class="indented">
(define-macro (defvar name value)
`(unless (defined? ',name)
(define ,name ,value)))
</pre>
<p>If ignore-rootlet is #t, the search is confined to the given environment.
</p>
<p>
<code>symbol->value</code> returns the value (lexically) bound to the symbol, whereas <code>symbol->dynamic-value</code>
returns the value dynamically bound to it. symbol->dynamic-value has one gotcha in s7. If a function calls it, and
that function is called as the only thing in a let body, the let is not on the stack, so if that let binds some symbol that
we want to access via symbol->dynamic-value, the new value will not be seen. Almost any change will make it work:
</p>
<pre class="indented">
(let ()
(define (gx) (symbol->dynamic-value 'x))
(let ((x 12))
(gx))) ; returns #<undefined>
(let ()
(define (gx) (symbol->dynamic-value 'x))
(let ((x 12))
"comment"
(gx))) ; returns 12
</pre>
<p>This is a bug in s7, but I would rather remove symbol->dynamic-value than fix it.
</p>
<p>
<code>symbol-initial-value</code> is normally the built-in (start up) value of a function, accessed via #_abs for example.
For other symbols this value can only be set once, and the value should be protected from the GC (s7 does not protect it).
</p>
<p>
<code>symbol-table</code> returns a vector containing the symbols currently in the symbol-table.
Here we scan the symbol table looking for any function that doesn't have documentation:
</p>
<pre class="indented">
(for-each
(lambda (sym)
(if (<em class=red>defined?</em> sym)
(let ((val (<em class=red>symbol->value</em> sym)))
(if (and (procedure? val)
(string=? "" (documentation val)))
(format *stderr* "~S " sym)))))
(<em class=red>symbol-table</em>))
</pre>
<p>Or get a list of gensyms:</p>
<pre>
(map (lambda (sym) (if (gensym? sym) sym (values))) (<em class=red>symbol-table</em>))
</pre>
<div class="indented">
<p>An automatic software tester (see also tauto.scm and auto-tester.scm in the tools directory):
</p>
<pre class="indented">
(for-each
(lambda (sym)
(if (<em class=red>defined?</em> sym)
(let ((val (<em class=red>symbol->value</em> sym)))
(if (procedure? val)
(let ((max-args (cdr (arity val))))
(if (or (> max-args 4)
(memq sym '(exit abort)))
(format () ";skip ~S for now~%" sym)
(begin
(format () ";whack on ~S...~%" sym)
(let ((constants (list #f #t pi () 1 1.5 3/2 1.5+i)))
(let autotest ((args ()) (args-left max-args))
(catch #t (lambda () (apply func args)) (lambda any #f))
(if (> args-left 0)
(for-each
(lambda (c)
(autotest (cons c args) (- args-left 1)))
constants)))))))))))
(<em class=red>symbol-table</em>))
</pre>
</div>
<div class="separator"></div>
<p id="s7help"><b>help</b> tries to find information about its argument.
</p>
<pre class="indented">
> (help 'caadar)
<em class="gray">"(caadar lst) returns (car (car (cdr (car lst)))): (caadar '((1 (2 3)))) -> 2"</em>
</pre>
<div class="separator"></div>
<p id="s7gc"><b>gc</b> calls the garbage collector. <code>(gc #f)</code> turns off the GC, and <code>(gc #t)</code> turns it on.
</p>
<p>If you get an error complaining about a "free cell", this is usually a sign that the GC freed some object
that it should have left alone. In straight scheme code, it's an s7 bug; please send me mail about it!
In foreign code, it probably indicates that you need to protect some s7_pointer with s7_gc_protect.
</p>
<div class="separator"></div>
<pre class="indented">
(<b><em class=def id="equivalentp">equivalent?</em></b> x y)
</pre>
<p>
Say we want to check that two different computations came to the same result, and that result might
involve circular structures. Will equal? be our friend?
</p>
<pre class="indented">
> (equal? 2 2.0)
<em class="gray">#f</em>
> (let ((x +nan.0)) (equal? x x))
<em class="gray">#f</em>
> (equal? .1 1/10)
<em class="gray">#f </em>
> (= .1 1/10)
<em class="gray">#f</em>
> (= 0.0 0+1e-300i)
<em class="gray">#f</em>
</pre>
<p>No! We need an equality check that ignores epsilonic differences in real and
complex numbers, and knows that NaNs are equal for all practical purposes.
Leaving aside numbers,
closed ports are not equal, yet nothing can be done with them.
#() is not equal to #2d(). And two closures are never equal, even if their
arguments, environments, and bodies are equal.
Since there might be circles, it is not easy to write
a replacement for equal? in Scheme.
So, in s7, if one thing is basically the same as
some other thing, they satisfy the function equivalent?.
</p>
<pre class="indented">
> (equivalent? 2 2.0)
<em class="gray">#t</em>
> (equivalent? 1/0 1/0) ; NaN
<em class="gray">#t</em>
> (equivalent? .1 1/10)
<em class="gray">#t</em> ; floating-point epsilon here is 1.0e-15 or thereabouts
> (equivalent? 0.0 1e-300)
<em class="gray">#t</em>
> (equivalent? 0.0 1e-14)
<em class="gray">#f</em> ; its not always #t!
> (equivalent? (lambda () #f) (lambda () #f))
<em class="gray">#t</em>
</pre>
<p>The *s7* field equivalent-float-epsilon sets the floating-point fudge factor.
I can't decide how bignums should interact with equivalent?. Currently,
if a bignum is involved, either here or in a hash-table, s7 uses equal?.
Finally, if either argument is an environment with an 'equivalent? method,
that method is invoked.
</p>
<div class="separator"></div>
<p>
<b><em class=def id="expansion">define-expansion</em></b> defines a macro that expands at read-time.
It has the same syntax as
define-macro, and (in normal use) the same result, but it is much faster because it expands only once.
Similarly, <b>define-expansion*</b> defines a read-time macro*.
(See also define-with-macros in s7test.scm for a way to expand macros in a function body at definition time).
Since the reader knows almost nothing
about the code it is reading,
you need to make sure the expansion is defined at the top level and that its name is unique.
The reader does know about global variables, so:
</p>
<pre class="indented">
(define *debugging* #t)
(define-expansion (assert assertion)
(if *debugging* ; or maybe better, (eq? (symbol->value '*debugging*) #t)
`(unless ,assertion
(format *stderr* "~A: ~A failed~%" (*function*) ',assertion))
(values)))
</pre>
<p>Now the assertion code is only present in the function body (or wherever)
if *debugging* is #t; otherwise assert expands into nothing. Another very handy
use is to embed a source file line number into a message; see for example lint-format
in lint.scm.
Leaving aside
read-time expansion and splicing, the real difference between define-macro and define-expansion
is that the expansion's result is not evaluated.
I'm no historian, but I believe that means that define-expansion creates
a (gasp!) f*xpr. In fact:
</p>
<pre>
(define-macro (define-f*xpr name-and-args . body)
`(define ,(car name-and-args)
(apply define-expansion
(append (list (append (list (gensym)) ',(cdr name-and-args))) ',body))))
> (define-f*xpr (mac a) `(+ ,a 1))
<em class="gray">mac</em>
> (mac (* 2 3))
<em class="gray">(+ (* 2 3) 1)</em>
</pre>
<p>
You can do something similar with a normal macro, or make the indirection explicit:
</p>
<pre class="indented">
> (define-macro (fx x) `'(+ 1 ,x)) ; quote result to avoid evaluation
<em class="gray">fx</em>
> (let ((a 3)) (fx a))
<em class="gray">(+ 1 a)</em>
> (define-expansion (ex x) `(+ 1 ,x))
<em class="gray">ex</em>
> (let ((x ex) (a 3)) (x a)) ; avoid read-time splicing
<em class="gray">(+ 1 a)</em>
> (let ((a 3)) (ex a)) ; spliced in at read-time
<em class="gray">4</em>
</pre>
<p>As this example shows, the reader knows nothing about the program context,
so if it does not see a list whose first element is a expansion name, it does
not do anything special. In the <code>(x a)</code> case above, the
expansion happens when the code is evaluated, and the expansion result
is simply returned, unevaluated.
</p>
<p>You can also use macroexpand to cancel the evaluation of a macro's expansion:
</p>
<pre>
(define-macro (rmac . args)
(if (null? args)
()
(if (null? (cdr args))
`(display ',(car args))
(list 'begin
`(display ',(car args))
(apply macroexpand (list (cons 'rmac (cdr args))))))))
> (macroexpand (rmac a b c))
<em class="gray">(begin (display 'a) (begin (display 'b) (display 'c)))</em>
> (begin (rmac a b c d) (newline))
<em class="gray">abcd</em>
</pre>
<p>The main built-in expansion is <b><em class=def id="readercond">reader-cond</em></b>. The syntax is based on cond:
the car of each clause is evaluated (in the read-time context), and if it is not false,
the remainder of that clause is spliced into the code as if you had typed it from the start.
</p>
<pre class="indented">
> '(1 2 (reader-cond ((> 1 0) 3) (else 4)) 5 6)
<em class="gray">(1 2 3 5 6)</em>
> ((reader-cond ((> 1 0) list 1 2) (else cons)) 5 6)
<em class="gray">(1 2 5 6)</em>
</pre>
<p>Here is reader-if:
</p>
<pre>
(define-expansion (reader-if test true . false)
(let ((test-val (eval test)))
(if test-val
true
(and (pair? false)
(car false)))))
</pre>
<!-- from kanren
(define-syntax conj*
(syntax-rules ()
((conj*) succeed)
((conj* g) g)
((conj* g gs ...)
(conj g (lambda (s) ((conj* gs ...) s))))))
is the same (in that context) as:
(define-macro (conj* . args)
(if (null? args)
succeed
(if (null? (cdr args))
(car args)
`(conj ,(car args)
(lambda (s) ((conj* ,@(cdr args)) s))))))
-->
<div class="separator"></div>
<p id="profiling">
Whenever (*s7* 'profile) is positive, profiling is turned on.
As the program runs, the profiler collects data about each function it can identify.
At any time, you can call show-profile to see that data. The first timing is inclusive
(it includes the time spent in any nested calls), the second is exclusive (it is the time
spent just in the current function). In Linux and *BSD, we use clock_gettime() which is reasonably
fast, but there is some profiler overhead. In other systems, we use clock() which is
amazingly slow. The optimizer sometimes recasts tail recursion and similar cases as while loops,
so the number of calls listed may be less than you'd expect, but the overall time should be
correct. To clear out the current data, call clear-profile.
</p>
<div class="separator"></div>
<p id="s7env"><b>*s7*</b> is a let that gives access to some of s7's internal
state:
</p>
<pre class="indented">
version a string describing the current s7: e.g. "s7 10.0, 13-Jan-2022"
major-version an integer (10 in the example above)
minor-version an integer (0 in the example above)
scheme-version 's7, 'r7rs
print-length number of elements to print of a non-string sequence
max-string-length maximum size arg to make-string and read-string
max-list-length maximum size arg to make-list
max-vector-length maximum size arg to make-vector and make-hash-table
max-vector-dimensions make-vector dimensions limit
default-hash-table-length default size for make-hash-table (8, tables resize as needed)
initial-string-port-length 128, initial size of a input string port's buffer
max-string-port-length maximum size of a port data buffer
output-file-port-length 2048, size of an output port's buffer
history a circular buffer of recent eval entries stored backwards (use set! to add an entry)
history-size eval history buffer size if s7 built WITH_HISTORY=1
history-enabled is history buffer receiving additions (if WITH_HISTORY=1 as above)
debug determines debugging level (see debug.scm), default=0
profile profile switch (0=default, 1=gather profiling info)
profile-info the current profiling data; see profile.scm
profile-prefix name (a symbol) used to identify the current environment in profile data
default-rationalize-error 1e-12
equivalent-float-epsilon 1e-15
hash-table-float-epsilon 1e-12 (currently limited to less than 1e-3).
hash-table-missing-key-value #f
iterator-at-end-value #<eof>
bignum-precision bits for bignum floats (128)
float-format-precision digits to print for floats (16) in object->string and number->string
default-random-state the default arg for random
most-positive-fixnum if not using gmp, the most positive integer ("fixnum" comes from CL)
most-negative-fixnum as above, but negative
number-separator #\null
symbol-quote? #f, so in (quote x) "quote" is a #_quote (a c-function); set to #t to get quote as a symbol
symbol-printer #f, a function to print symbols whose names contain unusual characters
safety 0 (see below)
undefined-identifier-warnings #f
undefined-constant-warnings #f
accept-all-keyword-arguments #f
autoloading? #t
openlets #t, whether any let can be open globally (this overrides all openlets)
expansions? #t, whether expansions are handled at read-time
muffle-warnings? #f, if #t s7_warn does not output anything
cpu-time run time so far (proportional to cpu cycles consumed, not wall-clock seconds)
file-names or filenames currently loaded files (a list)
catches a list of the currently active catch tags
c-types a list of c-object type names (from s7_make_c_type, etc)
stack the current stack entries
stack-top current stack location
stack-size current stack size
max-stack-size maximum stack size
stacktrace-defaults stacktrace formatting info for error handler
rootlet-size the number of globals
heap-size total cells currently available
max-heap-size maximum heap size
free-heap-size the number of currently unused cells
gc-stats 0 (or #f), 1: show GC activity, 2: heap, 4: stack, 8: protected_objects, #t = 1
gc-freed number of cells freed by the last GC pass
gc-total-freed number of cells freed so far by the GC; the total allocated is probably close to
(with-let *s7* (+ (- heap-size free-heap-size) gc-total-freed))
gc-info a list: calls total-time ticks-per-second (see profile.scm)
gc-temps-size number of cells just allocated that are protected from the GC (256)
gc-resize-heap-fraction when to resize the heap (0.8); these two are aimed at GC experiments
gc-resize-heap-by-4-fraction when to get panicky about resizing the heap
gc-protected-objects vector of objects protected from the GC
memory-usage a let (environment) describing current s7 memory allocations
</pre>
<p>
Use the standard environment syntax to access these fields:
<code>(*s7* 'stack-top)</code>. stuff.scm has the function
*s7*->list that returns most of these fields in a list.
</p>
<p>The compile-time defaults for some of these fields can be set:
</p>
<pre class="indented">
heap-size: INITIAL_HEAP_SIZE (64000)
stack-size: INITIAL_STACK_SIZE (4096)
gc-temps-size: GC_TEMPS_SIZE (256)
bignum-precision: DEFAULT_BIGNUM_PRECISION (128)
history-size: DEFAULT_HISTORY_SIZE (8)
print-length: DEFAULT_PRINT_LENGTH (40)
gc-resize-heap-fraction: GC_RESIZE_HEAP_FRACTION (0.8)
output-file-port-length: OUTPUT_PORT_DATA_SIZE (2048)
See also WITH_WARNINGS, S7_ALIGNED, and GC_TRIGGER_SIZE.
</pre>
<p><code>(set! (*s7* 'autoloading) #f)</code> turns off the autoloader.
</p>
<p>The 'safety variable is an integer. Currently:
</p>
<pre class="indented">
0: default.
1: no remove_from_heap (a GC optimization)
infinite loop check in eval, sort! and some iterators
immutable object check in reverse!, sort!, and fill!
more info in (*s7* 'history) for s7_apply_function, s7_call and s7_eval
less aggressive optimization in with-let and lambda
warnings about syntax redefinition
incoming s7_pointer checks in some FFI functions
bignum int to s7_int conversion checks
2: vector, string, and pair constants are immutable (but checks for this are currently sparse)
</pre>
<p>The debug variable controls where <a href="s7-scm.html#debug">debug.scm</a> is active. If it is (if debug > 0), it inserts
trace calls in functions and so on. It uses <em class=def id="dynamicunwind">dynamic-unwind</em>
to establish a catcher for the return value. <code>(dynamic-unwind function arg)</code> causes
<code>function</code> to be called after the traced function has returned, passing it <code>arg</code>
and the returned value.
</p>
<p><code>(*s7* 'stacktrace-defaults)</code> is a list of four integers and a boolean that tell the error
handler how to format stacktrace information. The four integers are:
how many frames to display,
how many columns are devoted to code display,
how many columns are available for a line of data,
and where to place comments.
The boolean sets whether the entire output should be displayed as a comment.
The defaults are '(30 50 80 50 #f).
</p>
<p>This will display s7 memory usage sort of like the top program:
</p>
<pre class="indented">
(format *stderr* "~C[~D;~DH" #\escape 0 0)
(format *stderr* "~C[J" #\escape)
(display (with-output-to-string (lambda() (<em class="red">*s7* 'memory-usage</em>))))
</pre>
<p>(Ideally we'd only redisplay the changed fields).
</p>
<p>The standard time macro:</p>
<pre class="indented">
(define-macro (time expr)
`(let ((start (<em class="red">*s7* 'cpu-time</em>)))
(let ((res (list ,expr))) ; expr might return multiple values
(list (car res)
(- (<em class="red">*s7* 'cpu-time</em>) start)))))
</pre>
<p>Add automatic log10 recalculation to (*s7* 'bignum-precision):</p>
<pre class="indented">
(define log10 (log (bignum 10)))
(define bignum-precision (dilambda (lambda ()
(<em class="red">*s7* 'bignum-precision</em>))
(lambda (val)
(set! (<em class="red">*s7* 'bignum-precision</em>) val)
(set! log10 (log (bignum 10)))
val)))
</pre>
<p>The stack, history and gc-protected-objects fields are intended for debugging. Don't keep
these hanging around and expect good things to happen!
</p>
<p>The *s7* field 'number-separator refers to what some languages call "numeric literal separator",
a character that can appear in a number as a separator to make it more readable: "123,321"
as opposed to "123321". If the compile time flag WITH_NUMBER_SEPARATOR is set, and
(*s7* 'number-separator) is not #\null (the default), then that character can appear anywhere
in a number (as long as it is between two digits), and the reader will ignore it. The *features*
list will have the entry 'number-separator if s7 was compiled with WITH_NUMBER_SEPARATOR defined.
(Number separators don't work with bignums).
</p>
<p>(*s7* 'symbol-printer) is invoked by object->string when it has to print a symbol whose
name can normally only be handled by the <a href="#weirdsymbols">symbol</a> function.
</p>
<div class="separator"></div>
<pre class="indented">
(<em class=def id="cobject">c-object?</em> obj)
(<em class=def id="cobjecttypew">c-object-type</em> obj)
(<em class=def>c-object-let</em> obj)
(<em class=def id="cpointer">c-pointer?</em> obj)
(<em class=def id="cpoint">c-pointer</em> int type info weak1 weak2)
(<em class=def id="cpointtype">c-pointer-type</em> obj)
(<em class=def id="cpointinfo">c-pointer-info</em> obj)
(<em class=def id="cpointweak1">c-pointer-weak1</em> obj) ; also weak2
(<em class=def id="cpointertolist">c-pointer->list</em> obj)
</pre>
<p>
c-object? returns #t is its argument is a c-object.
c-object-type returns the object's type tag (otherwise #f of course). This tag is also the position
of the object's type in the (*s7* 'c-types) list.
(*s7* 'c-types) returns a list of the types created by s7_make_c_type.
c-object-let returns the c-object's local let. See <a href="s7-ffi.html#ccobjects">c-objects</a> for
more info.
</p>
<p>
You can wrap up raw C pointers and
pass them around in s7 code. The function c-pointer returns a wrapped pointer,
and c-pointer? returns #t if passed one. <code>(define NULL (c-pointer 0))</code>.
If the type field is a symbol, it is used to check types in s7_c_pointer with_type.
If the 'info field of a c-pointer is a let, that pointer can participate in
the generic functions mechanism, much like a c-object:
</p>
<pre class="indented">
> (let ((ptr (c-pointer 1 'abc
(inlet 'object->string
(lambda (obj . args)
(let ((lt (object->let obj)))
(format #f "I am pointer ~A of type '~A!"
(lt 'c-pointer) ; we need c-pointer-type etc
(lt 'c-type))))))))
(openlet ptr)
(object->string ptr))
<em class="gray">"I am pointer 1 of type 'abc!"</em>
</pre>
<p>c-pointer->list returns (list pointer-as-int type info).
The "weak1" and "weak2" fields are intended for custom "weak" references. The weak
fields values are not marked during the GC sweep, much like a key in a weak-hash-table.
If either value is GC'd, that field is set to #f by the GC. The weak fields are
ignored by equal? and equivalent? when comparing c-pointers, and by object->string
of a c-pointer even if :readable is specified.
</p>
<div class="separator"></div>
<p>There are several tree-oriented functions currently built into s7:
</p>
<pre class="indented">
(<em class=def id="treecyclic">tree-cyclic?</em> tree) returns #t if tree contains a cycle.
(<em class=def id="treeleaves">tree-leaves</em> tree) returns the number of leaves in tree.
(<em class=def id="treememq">tree-memq</em> obj tree) returns #t if obj is in tree (using eq?).
(<em class=def id="treesetmemq">tree-set-memq</em> set tree) returns #t if any member of the set (using eq?) is in tree.
(<em class=def id="treecount">tree-count</em> obj tree) returns how many times obj is in tree.
</pre>
<div class="separator"></div>
<p>s7 originally had Scheme-level multithreading support, but I removed it in August, 2011.
It turned out to be less useful than I hoped,
mainly because s7 threads shared the heap and therefore had to coordinate
all cell allocations. It was faster and simpler to use multiple
processes each running a separate s7 interpreter, rather than one s7
running multiple s7 threads. In CLM, there was also contention for access
to the output stream. In GUI-related situations,
threads were not useful mainly because the GUI toolkits are not thread safe.
Last but not least, the effort to make the non-threaded
s7 faster messed up parts of the threaded version. Rather than
waste a lot of time fixing this, I chose to flush multithreading.
s7 is thread-safe:
</p>
<blockquote>
<div class="indented">
<pre>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include "s7.h"
#define NUM_THREADS 16
static pthread_t threads[NUM_THREADS];
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
static void *run_thread(void *obj)
{
s7_scheme *sc = (s7_scheme *)obj;
const char *str = s7_object_to_c_string(sc, s7_make_integer(sc, 123));
s7_eval_c_string(sc, "(let () \
(define (f) \
(do ((i 0 (+ i 1))) ((= i 10)) \
(do ((k 0 (+ k 1))) ((= k 1000000))) \
(format *stderr* \"~D \" i))) \
(f))");
pthread_mutex_lock(&lock);
fprintf(stderr, "%s\n", str);
pthread_mutex_unlock(&lock);
}
int main(int argc, char **argv)
{
for (int32_t i = 0; i < NUM_THREADS; i++)
pthread_create(&threads[i], NULL, run_thread, (void *)s7_init());
for (int32_t i = 0; i < NUM_THREADS; i++)
pthread_join(threads[i], NULL);
exit(0);
}
/* linux: gcc -o threads threads.c s7.o -Wl,-export-dynamic -pthread -lm -I. -ldl
* mac: clang -o threads threads.c s7.o -pthread -lm -I. -ldl
* g++ can compile s7.c, but clang++ can't.
*/
</pre>
<div class="separator"></div>
<small>
<p id="gthreads">Here's an example using gdbm to handle a variable global to the threads:
</p>
<pre>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <gdbm.h>
#include "s7.h"
#define GDBM_DB "test.gdbm"
GDBM_FILE gdb;
#define NUM_THREADS 1024
static pthread_t threads[NUM_THREADS];
static void *run_thread(void *obj)
{
s7_scheme *sc = (s7_scheme *)obj;
datum key, rtn;
key.dptr = "global_int";
key.dsize = 10;
rtn = gdbm_fetch(gdb, key);
if (rtn.dptr)
{
/* this makes a local copy of the global variable and displays its value */
/* s7_define_variable(sc, "global-int", s7_make_integer(sc, strtol((const char *)rtn.dptr, NULL, 10))); */
/* s7_display(sc, s7_name_to_value(sc, "global-int"), s7_current_error_port(sc)); */
/* this increments the global variable and displays it */
datum val;
char buf[128];
int bytes;
long int ctr = strtol((const char *)rtn.dptr, NULL, 10);
bytes = snprintf(buf, 128, "%ld", ++ctr);
val.dptr = buf;
val.dsize = bytes + 1;
gdbm_store(gdb, key, val, GDBM_REPLACE);
fprintf(stderr, "%s ", buf);
free(rtn.dptr);
}
else fprintf(stderr, "oops ");
s7_free(sc);
}
int main(int argc, char **argv)
{
int32_t i, k, rtn, last_i = 0;
datum key, val;
key.dptr = "global_int";
key.dsize = 10;
val.dptr = "0";
val.dsize = 2;
gdb = gdbm_open(GDBM_DB, 1024, GDBM_NEWDB, 0664, NULL);
gdbm_store(gdb, key, val, GDBM_REPLACE);
for (i = 0; i < NUM_THREADS; i++)
{
rtn = pthread_create(&threads[i], NULL, run_thread, (void *)s7_init());
if (rtn)
{
fprintf(stderr, "failed to create thread %d\n", i);
exit(0);
}
if ((i - last_i) > 16)
{
for (k = last_i; k < i; k++)
pthread_join(threads[k], NULL);
last_i = i;
}}
gdbm_close(gdb);
}
/* linux: gcc -o gthreads gthreads.c s7.o -O -g -Wl,-export-dynamic -pthread -lgdbm -lm -I. -ldl
*/
</pre>
<p>See <a href="s7-scm.html#libgdbm">libgdbm</a> for a Scheme side example.</p>
</small>
</div>
</blockquote>
<div class="separator"></div>
<blockquote>
<div class="indented">
<p id="s7vsr5rs">Some other differences from r5rs:
</p>
<ul style="list-style-type:disc;">
<li>no force or delay (see <a href="#r7rs">below</a>).
<li>no syntax-rules or any of its friends.
<li>no scheme-report-environment, null-environment, or interaction-environment (use curlet).
<li>no transcript-on or transcript-off.
<li>begin returns the value of the last form; it can contain both definitions and other statements.
<li>#<unspecified>, #<eof>, and #<undefined> are first-class objects.
<li>for-each and map accept different length arguments; the operation stops when any argument reaches its end.
<li>for-each and map accept any applicable object as the first argument, and any sequence or iterator as a trailing argument.
<li>letrec*, but without conviction.
<li>set! and *-set! return the new value (modulo setter), not #<unspecified>.
<li>define and its friends return the new value.
<li>port-closed?
<li>list? means "pair or null", proper-list? is r5rs list?, float? = real and not rational, sequence? = length, byte? = unsigned byte.
<!-- a vector can be a member of itself, and yet vector? returns #t, why is list? different; we even call it a circular list! -->
<li>the default IO ports are named *stdin*, *stdout*, and *stderr*.
<li>#f as an output port means nothing is output (#f is /dev/null, I guess).
<li>member and assoc accept an optional third argument, the comparison function (equal? is the default).
<li>case accepts => much like cond (the function argument is the selector).
<li>if WITH_SYSTEM_EXTRAS is 1, the following are built-in: directory?, file-exists?, delete-file, system, directory->list, getenv.
<li>s7 is case sensitive.
<li>when and unless (for r7rs), returning the value of the last form.
<li>the "d", "f", "s", and "l" exponent markers are not supported by default (use "e", "E", or "@").
<li>quasiquoted vector constants are not supported (read-time expansions can be used here; see s7test.scm).
<li><em class=def id="typeof">type-of</em> returns a type indicator for its argument.
<li>'<datum> is (#_quote <datum>), see <a href="#quotediff">below</a>.
<li>s7 symbol names can begin with a digit: <code>(define (1+ x) (+ x 1))</code>.
<li>eq? is the r4rs version of eq? It returns #t if its arguments are identical.
</ul>
<p>In s7 if a built-in function like gcd is referred to in a function
body, the optimizer is free to replace it with #_function. That is, <code>(gcd ...)</code> can be changed
to <code>(#_gcd ...)</code> at s7's whim, if gcd has its original value at the time the optimizer
sees the expression using it. A subsequent <code>(set! gcd +)</code> does not affect this optimized call.
I think I could wave my hands and mumble about "aggressive lexical scope" or something, but actually the
choice here is that speed trumps that ol' hobgoblin consistency. If you want to change gcd to +, do it before
loading code that calls gcd.
I think most Schemes handle macros this way: the macro call is replaced by its expansion using its current
definition, and a later redefinition does not affect earlier uses.
Guile behaves like s7:
</p>
<pre class="indented">
(define (add1 x) (+ x 1))
(set! + -)
(display (add1 3))) ; 4 in both s7 and Guile 3.0.4
</pre>
<p>But if a Scheme function is involved, things get messy:
</p>
<pre class="indented">
(define (fib n) (if (< n 2) n (+ (fib (- n 1)) (fib (- n 2)))))
(define oldfib fib)
(set! fib 32)
(display (oldfib 10))) ; s7 says 55, Guile says "wrong type to apply: 32"
</pre>
<p>I can't decide which way is correct: s7 looks more consistent,
but:
</p>
<pre class="indented">
(define (fib n) 32)
(set! fib (lambda (n) (if (< n 2) n (+ (fib (- n 1)) (fib (- n 2))))))
(define oldfib fib)
(set! fib 32)
(display (oldfib 10)) ; "attempt to apply an integer 32 to..."
</pre>
<p>So s7 is inconsistent too! (Actually this was consistent until Jan 2021 when I suddenly thought it was
a mistake and "fixed" it; now I'm having second thoughts).
</p>
<!-- (eq? (if #f #f) (apply values ())) is #t, but memq and assq don't treat them as equal -->
</div>
<div class="indented">
<p>Here are some changes I'd make to s7 if I didn't care about compatibility with other Schemes:
</p>
<ul style="list-style-type:disc;">
<li>remove the exact/inexact distinction including #i and #e (done! #i means int-vector constant).
<li>remove call-with-values and its friends
<li>remove char-ready?
<li>change eof-object? to eof? or just omit it (you can use eq? #<eof>)
<li>change make-rectangular to complex (done!), and remove make-polar.
<li>remove unquote (the name, not the functionality).
<li>remove cond-expand.
<li>remove *-ci functions
<li>remove #d (done!)
</ul>
<p>(most of these are removed if you set the compiler flag WITH_PURE_S7), and perhaps:
</p>
<ul style="list-style-type:disc;">
<li>remove even? and odd?, gcd and lcm.
<li>remove string-length and vector-length.
<!-- <li>remove list-ref, list-set!, string-ref, string-set!, vector-ref, vector-set!, hash-table-ref, hash-table-set!, set-car!, set-cdr!, and set-current-*-port. -->
<li>change file-exists? to file? (or omit it and assume the use of libc.scm — why reinvent the wheel?).
<li>remove all the conversion and copy functions like vector->list and vector-copy (use copy or map).
<li>change string->symbol to symbol (what to do with symbol->string in that case?)
<li>change with-output-to-* and with-input-from-* to omit the pointless lambda.
<li>remove the with-* IO functions (e.g. with-input-from-string), keeping the call-with-* versions (call-with-input-string).
<li>remove assq, assv, memq, and memv (these are pointless now that assoc and member can be passed eq? and eqv?).
<li>move all the "*var*" names to *s7*: *load-hook* becomes (*s7* 'load-hook) for example.
</ul>
<p>Currently WITH_PURE_S7:
</p>
<ul style="list-style-type:disc;">
<li>places 'pure-s7 in *features*
<li>omits char-ready, char-ci*, string-ci*
<li>omits string-fill!, vector-fill!, vector-append
<li>omits list->string, list->vector, string->list, vector->list, let->list
<li>omits string-length and vector-length
<li>omits cond-expand, multiple-values-bind|set!, call-with-values
<li>omits unquote (the name)
<li>omits d/f/s/l exponents
<li>omits make-polar and make-rectangular (use complex)
<li>omits exact?, inexact?, exact->inexact, inexact->exact
<li>omits set-current-output-port and set-current-input-port
</ul>
<p>With the move to s7_setter and s7_set_setter (setter in Scheme),
dilambda and dilambda? have been reduced to trivial conveniences, so perhaps they can also be
removed.
</p>
<p>string-copy has 3 extra arguments to allow strings to be copied directly into other strings.
In vectors, we can use subvector, but substring returns a new string (copying its argument) unless
the optimizer notices that the copy is not needed. Copy almost works, but its start and end arguments
refer to the source, not the destination. substring should be like subvector, but that is not backwards compatible.
</p>
<p>There are several less-than-ideal names.
get-output-string should be current-output-string. write-char behaves like display, not write.
provided? should be feature? or *features* should be *provisions*.
list-ref, list-set!, and list-tail actually only apply to pairs.
let-temporarily should be templet, set-temporarily, or maybe just "with". define-expansion should be define-reader-macro, but
that name collides with reader macros in Common Lisp. *cload-directory* should be *cload-path*.
There should not be two names for the same thing: call/cc and call-with-current-continuation: flush the latter!
The CL-inspired "log*" names such as logand look very old-fashioned. Standard scheme opts
for the name "bitwise*"; why not "integerwise" or "bytevectorwise"? The "wise" business is just noise; are they thinking of The Hobbit?
<code>(define & logand) (define | logior) (define ~ lognot)</code>, but ^ for logxor
(as in C) is not ideal; ^ should be expt. Finally, I think the notion of a current input or output port is
a mistake: the IO functions should always get an explicit port.
</p>
<p>
cond-expand is dumb and its name is dumber.
Take libgsl.scm; different versions of the GSL library have different functions. We need to know
when we're building the FFI what GSL version we're dealing with. It would be nuts to start pushing and checking dozens
of library version symbols when all we actually want is <code>(> version 23.19)</code>.
In place of cond-expand, s7 uses <a href="#readercond">reader-cond</a>,
so the read-time decision involves normal Scheme evaluation.
</p>
<blockquote>
<div class="indented">
<p>In the section about cond-expand, the r7rs spec says "If none of the <feature requirement>s evaluate to #t,
then if there is an else clause, its <expression>s are included. Otherwise, the cond-expand has no effect."
I read that to mean that <code>(begin 23 (cond-expand (surreals 1)))</code> should evaluate to 23,
and <code>(abs -1 (cond-expand (surreals 1)))</code> should be 1. Currently s7 returns #<unspecified> for the
first, and an error, "abs: too many arguments: (abs -1 #<unspecified>)" for the second.
reader-cond behaves in a way that fits the r7rs spec: <code>(begin 23 (reader-cond ((provided? 'surreals) 1)))</code>
returns 23, and <code>(abs -1 (reader-cond ((provided? 'surreals) 1)))</code> returns 1, but these examples make
me unhappy. Even worse: <code>(define (f a (reader-cond ((provided? 'surreals) b))) a)</code> which adds
the argument "b" if surreals are provided.
Maybe reader-cond (and expansions in general) should not magically evaporate in such cases.
(I just noticed that the corrected r7rs.pdf says that the result in cond-expand is unspecified).
</p>
<!--
There's no statement in the r7rs spec that cond-expand can only happen at top-level, and in s7 you can load a
file into any environment, so there's no way to tell if some code is being spliced in at the top-level, even if
it's at the top level of the file's code, so it doesn't help to try to restrict reader-cond in that way.
-->
</div>
</blockquote>
<p>Then there's the case case: a case clause without a result appears to be an error in r7rs.
But the notation used to indicate that is the same as that used for begin,
so if we allow <code>(begin)</code>, we should allow case clauses to have no explicit result.
In cond,
the "implicit progn" (in CL terminology) includes the test expression, so a clause without a result returns
the test result (if true of course). In the case case, s7 returns the selector.
<code>(case x ((0 1)))</code> is equivalent to <code>(case x ((0 1) => values))</code>,
just as <code>(cond (A))</code> is equivalent to <code>(cond (A => values))</code>.
One application is method lookup: <code>((case (obj 'abs) ((#<undefined>) abs) (else)) ...)</code>;
we would otherwise have to save the lookup result or do it twice.
This choice has a ripple
effect on do: if no result is specified for do, s7 returns the test result.
It also affects
hash-tables. Currently hash-table-ref returns #f if the key is not in the table,
mimicking assoc and aimed at cond with =>, but if we also use case and #<undefined>,
it seems more useful and maybe intuitive to mimic let-ref instead. But if hash-table-ref returns
#<undefined>, it's harder to use hash-tables as sets. Hmm.
In any case,
the fall-through value of case should be (and is in s7)
#<unspecified>: case is a form of if, so
<code>(if #f #f)</code>, <code>(cond (#f #f))</code>, and <code>(case #t ((#f) #f))</code> should be equal.
</p>
<p>
Better ideas are always welcome!
</p>
<p>Here are the built-in s7 variables:
</p>
<ul>
<li>*features* ; a list of symbols
<li>*libraries* ; a list of (filename . let) pairs
<li>*load-path* ; a list of directories
<li>*cload-directory* ; directory for cload output
<li>*autoload* ; autoload info
<li>*#readers* ; a list of (char . handler) pairs
</ul>
<p>And the built-in constants:
</p>
<ul style="list-style-type:disc;">
<li>pi
<li>*stdin* *stdout* *stderr*
<li>*s7*
<li>+nan.0 -nan.0 +inf.0 -inf.0 (what crappy names! +nan.0 is a positive inexact integer that is not a number?)
<li>*unbound-variable-hook* *missing-close-paren-hook* *load-hook* *autoload-hook*
<li>*error-hook* *read-error-hook* *rootlet-redefinition-hook*
</ul>
<p>Is it odd that the "+" in +nan.0 can't be omitted, but as used in a complex number, someone drops a "+": 1+nan.0i?
</p>
<p>(<b><em class=def id="currentfunction">*function*</em></b>) returns the name (or name and location) of the function currently being called.
<code>(define (example) (*function*))</code> returns <code>'example</code>.
Here is an example using a bacro (to access the call-time environment) and an openlet to implement a probe;
it reports any operation that the probe participates in, using *function* to get the calling function name:
</p>
<pre class="indented">
(define (probe-eval val)
(let ((all-let (inlet)))
(for-each
(lambda (sym)
(unless (immutable? sym) ; apply-values etc
(let ((func (symbol->value sym (rootlet))))
(when (procedure? func)
(varlet all-let sym
(apply <em class=red>bacro</em> 'args
`((let-temporarily (((*s7* 'openlets) #f))
(let ((clean-args (map (lambda (arg)
(if (eq? arg probe-eval)
(probe-eval 'value)
arg))
args)))
(format *stderr* "(~S ~{~S~^ ~}) ; ~S~%"
,sym clean-args
(<em class=red>*function*</em> (outlet (outlet (curlet)))))
(apply ,func clean-args))))))))))
(symbol-table))
(varlet all-let 'value val)
(<em class=red>openlet</em> all-let)))
(define (call-any x)
(+ x 21))
(call-any (probe-eval 42)) ; prints "(+ 42 21) ; call-any", returns 63
</pre>
<p>
The second argument to *function* is the let from which to start searching for a function.
In the example above, we start the search from the let outside the bacro, since we hope to find the bacro's caller.
As a convenience, *function* takes an optional third argument specifying what information you want
about the current function. An example: <code>(*function* (curlet) 'name)</code>.
<code>name</code> returns the name (a symbol) of the current function.
<code>line</code> returns the function's definition line number.
<code>file</code> returns the function's definition file.
Other possibilities are <code>signature</code>, <code>documentation</code>,
<code>arity</code>, <code>arglist</code>, <code>value</code>, and <code>source</code>.
<code>funclet</code> returns the current function's funclet.
</p>
</div>
<div class="indented">
<p>Schemes differ in their treatment of (). s7 considers it a constant that evaluates to itself,
so you don't need to quote it. <code>(eq? () '())</code> is #t.
This is consistent with, for example,
<code>(eq? #f '#f)</code> which is also #t.
The standard says "the empty list is a special object of its own type", so surely either choice is
acceptable in that regard (but, sigh, the standard stupidly goes on to deny that () can evaluate to itself).
(I'm told that "is an error" means "is not portable" in the standard's weasely abuse of English; if
they mean "is not portable" why not say that?).
Some of the confusion appears to be caused by the word "list". I would describe the evaluator: "if it gets a
constant (and () is a constant) it returns that constant; if a symbol, it returns the value
associated with that symbol; if a pair, it looks at the pair's
car to decide what to do".
</p>
<!--
One place where the quote matters is in a case statement; the selector is
evaluated but the key is not:
</p>
<pre class="indented">
> (case '() ((()) 2) (else 1)) ; in s7 this is the same as (case () ((()) 2) (else 1))
<em class="gray">2</em>
> (case '() (('()) 2) (else 1)) ; (eqv? '() ''()) is #f
<em class="gray">1</em>
;;; which parallels #f (or a number such as 2 etc):
> (case '#f ((#f) 2) (else 1))
<em class="gray">2</em>
> (case '#f (('#f) 2) (else 1)) ; (eqv? '#f ''#f) is #f
<em class="gray">1</em>
</pre>
-->
<p>Similarly, in s7, vector constants do not have to be quoted. A list constant is quoted
to keep it from being evaluated, but
#(1 2 3) is as unproblematic as "123" or 123.
</p>
<!-- there's another sense in which () is a constant: you can't apply it to anything. (() 0) -> error
-->
<p>These examples bring up another odd corner of scheme: else. In <code>(cond (else 1))</code>
the 'else is evaluated (like any cond test), so its value might be #f; in <code>(case 0 (else 1))</code>
it is not evaluated (like any case key), so it's just a symbol.
Since setters are local in s7,
someone can <code>(let ((else #f)) (cond (else 1)))</code> even if we protect the rootlet 'else.
Of course, in scheme this kind of trouble is pervasive, so rather than make 'else a constant
I think the best path is to use unlet:
<code>(let ((else #f)) (cond (#_else 1)))</code>. This is 1 (not ()) because the initial value of 'else
can't be changed.
</p>
</div>
<div class="indented">
<p id="quotediff">s7 treats <code>'<datum></code> as <code>(#_quote <datum>)</code> which is not the same as the r7rs standard <code>(quote <datum>)</code>.
The name 'quote' can be captured by the local context, whereas the function #_quote can't. Apostrophe should be
something that does not require you to worry about name capture; the form <code>'a</code> does not contain
the name 'quote', so it is annoying that its result can be altered by redefining 'quote'. Here are a few examples
of the difference (I'm using guile because it is available on this machine):
</p>
<pre class="indented">
(let ((quote "Friends, Romans...")) 'x) ; guile Unbound variable: x, s7 x
(let (' 1) quote) ; guile 1, s7 error (#_quote is not a symbol)
(let ((quote 32)) (length '(1 2))) ; guile error Wrong type to apply: 1, s7 2
(let ((quote cos)) '0) ; guile 1, s7 0
(let ((quote -) (x 1)) 'x) ; guile -1, s7 x
(let ('(lambda (x) (+ x 1))) '1) ; guile 2, s7 error (#_quote is not a symbol)
((lambda 'x (+ 'x 1)) cos 0) ; guile 2, s7 error (lambda parameter #_quote is a constant)
(define-macro (m x) `(length ',x)) (let ((quote 32)) (m (1 2 3))) ; guile "wrong type to apply: 1", s7 3
</pre>
<p>
Perhaps these simple examples will clarify s7's way of handling the apostrophe.
</p>
<pre class="indented">
(syntax? #_quote) -> #t
(syntax? 'quote) -> #f ; the symbol quote
(equal? quote #_quote) -> #t
(equal? 'quote quote) -> #f ; quote is not self-evaluating
(equal? 'quote #_quote) -> #f
(equal? '#f (quote #f)) -> #t
</pre>
<p>If you want the standard scheme approach, <code>(set! (*s7* 'symbol-quote?) #t)</code>.</p>
</div>
<div class="indented">
<p>s7 handles circular lists and vectors and dotted lists with its customary aplomb.
You can pass them to memq, or print them, for example; you can even evaluate them.
The print syntax is borrowed from CL:
</p>
<pre class="indented">
> (let ((lst (list 1 2 3)))
(set! (cdr (cdr (cdr lst))) lst)
lst)
<em class="gray">#1=(1 2 3 . #1#)</em>
> (let* ((x (cons 1 2))
(y (cons 3 x)))
(list x y))
<em class="gray">(#1=(1 . 2) (3 . #1#))</em>
</pre>
<p id="circularlistreader">
But should this syntax be readable as well? I'm inclined to say no because
then it is part of the language, and it doesn't look like the rest of the language.
(I think it's kind of ugly). Perhaps we could implement it via *#readers*:
</p>
<pre>
(define circular-list-reader
(let ((known-vals #f)
(top-n -1))
(lambda (str)
(define (replace-syms lst)
;; walk through the new list, replacing our special keywords
;; with the associated locations
(define (replace-sym tree getter)
(if (keyword? (getter tree))
(let ((n (string->number (symbol->string (keyword->symbol (getter tree))))))
(if (integer? n)
(let ((lst (assoc n known-vals)))
(if lst
(set! (getter tree) (cdr lst))
(format *stderr* "#~D# is not defined~%" n)))))))
(let walk-tree ((tree (cdr lst)))
(if (pair? tree)
(begin
(if (pair? (car tree)) (walk-tree (car tree)) (replace-sym tree car))
(if (pair? (cdr tree)) (walk-tree (cdr tree)) (replace-sym tree cdr))))
tree))
;; str is whatever followed the #, first char is a digit
(let* ((len (length str))
(last-char (str (- len 1))))
(and (memv last-char '(#\= #\#)) ; is it #n= or #n#?
(let ((n (string->number (substring str 0 (- len 1)))))
(and (integer? n)
(begin
(if (not known-vals) ; save n so we know when we're done
(begin
(set! known-vals ())
(set! top-n n)))
(if (char=? last-char #\=) ; #n=
(and (eqv? (peek-char) #\() ; eqv? since peek-char can return #<eof>
(let ((cur-val (assoc n known-vals)))
;; associate the number and the list it points to
;; if cur-val, perhaps complain? (#n# redefined)
(let ((lst (catch #t
read
(lambda args ; a read error
(set! known-vals #f) ; so clear our state
(apply throw args))))) ; and pass the error on up
(if cur-val
(set! (cdr cur-val) lst)
(set! known-vals
(cons (set! cur-val (cons n lst)) known-vals))))
(if (= n top-n) ; replace our special keywords
(let ((result (replace-syms cur-val)))
(set! known-vals #f) ; '#1=(#+gsl #1#) -> '(:1)!
result)
(cdr cur-val))))
; #n=<not a list>?
;; else it's #n# — set a marker for now since we may not
;; have its associated value yet. We use a symbol name that
;; string->number accepts.
(symbol->keyword
(symbol (number->string n) (string #\null) " "))))))
; #n<not an integer>?
))))) ; #n<something else>?
(do ((i 0 (+ i 1)))
((= i 10))
;; load up all the #n cases
(set! *#readers*
(cons (cons (integer->char (+ i (char->integer #\0))) circular-list-reader)
*#readers*)))
<!-- ) -->
> '#1=(1 2 . #1#)
<em class="gray">#1=(1 2 . #1#)</em>
> '#1=(1 #2=(2 . #2#) . #1#)
<em class="gray">#2=(1 #1=(2 . #1#) . #2#)</em>
</pre>
<p>And of course, we can treat these as labels:
</p>
<pre class="indented">
(let ((ctr 0)) #1=(begin (format () "~D " ctr) (set! ctr (+ ctr 1)) (if (< ctr 4) #1# (newline))))
</pre>
<p>which prints "0 1 2 3" and a newline.
</p>
<br>
<p>Length returns +inf.0 if passed a circular list, and returns a negative
number if passed a dotted list. In the dotted case, the absolute value of the length is the list length not counting
the final cdr. <code>(define (circular? lst) (infinite? (length lst)))</code>.
</p>
<p>
<em class=def id="cyclicsequences">cyclic-sequences</em> returns a list of the cyclic
sequences in its argument, or nil.
<code>(define (cyclic? obj) (pair? (cyclic-sequences obj)))</code>.
</p>
<p>Here's an amusing use of circular lists:
</p>
<pre class="indented">
(define (for-each-permutation func vals)
;; apply func to every permutation of vals:
;; (for-each-permutation (lambda args (format () "~{~A~^ ~}~%" args)) '(1 2 3))
(define (pinner cur nvals len)
(if (= len 1)
(apply func (car nvals) cur)
(do ((i 0 (+ i 1))) ; I suppose a named let would be more Schemish
((= i len))
(let ((start nvals))
(set! nvals (cdr nvals))
(let ((cur1 (cons (car nvals) cur))) ; add (car nvals) to our arg list
(set! (cdr start) (cdr nvals)) ; splice out that element and
(pinner cur1 (cdr start) (- len 1)) ; pass a smaller circle on down, "wheels within wheels"
(set! (cdr start) nvals)))))) ; restore original circle
(let ((len (length vals)))
(set-cdr! (list-tail vals (- len 1)) vals) ; make vals into a circle
(pinner () vals len)
(set-cdr! (list-tail vals (- len 1)) ()))) ; restore its original shape
</pre>
</div>
<div id="weirdsymbols" class="indented">
<p>s7 and Snd use "*" in a variable name, *features* for example, to indicate
that the variable is predefined. It may occur unprotected in a macro, for
example. The "*" doesn't mean that the variable is special in the CL sense of dynamic scope,
but some clear marker is needed for a global variable so that the programmer
doesn't accidentally step on it.
</p>
<p>Although a variable name's first character is more restricted, currently
only #\null, #\newline, #\tab, #\space, #\), #\(, #\", and #\; can't
occur within the name. I did not originally include double-quote in this set, so wild stuff like
<code>(let ((nam""e 1)) nam""e)</code>
would work, but that means that <code>'(1 ."hi")</code> is parsed as a 1 and the
symbol <code>."hi"</code>, and <code>(string-set! x"hi")</code> is an error.
The first character should not be #\#, #\', #\`, #\,, #\:, or any of those mentioned above,
and some characters can't occur by themselves. For example, "." is not a legal variable
name, but ".." is.
These weird symbols have to be printed sometimes:
</p>
<pre class="indented">
> (list 1 (string->symbol (string #\; #\" #\\)) 2)
<em class="gray">(1 ;"\ 2)</em> <!-- " -->
> (list 1 (string->symbol (string #\.)) 2)
<em class="gray">(1 . 2)</em>
</pre>
<p>which is a mess. Guile prints the first as <code>(1 #{\;\"\\}# 2)</code>.
In CL and some Schemes:
</p>
<pre class="indented">
[1]> (list 1 (intern (coerce (list #\; #\" #\\) 'string)) 2) ; thanks to Rob Warnock
<em class="gray">(1 |;"\\| 2)</em> <!-- " -->
[2]> (equalp 'A '|A|) ; in CL case matters here
<em class="gray">T</em>
</pre>
<p>This is clean, and has the weight of tradition behind it, but
I think I'll use "symbol" instead:
</p>
<pre class="indented">
> (list 1 (string->symbol (string #\; #\" #\\)) 2)
<em class="gray">(1 (symbol ";\"\\") 2)</em> <!-- " -->
</pre>
<p>
This output is readable, and does not eat up perfectly good
characters like vertical bar, but it means we can't easily use
variable names like "| e t c |". We could allow a name to
contain any characters if it starts and ends with "|",
but then one vertical bar is trouble. We can define a reader
that turns <code>#symbol<...></code> into <code>(symbol "...")</code>,
making it possible to use odd names more widely:
</p>
<pre class="indented">
(set! *#readers*
(list (cons #\s
(lambda (str)
(let ((len (length str)))
(and (string=? (substring str 0 7) "symbol<")
(if (char=? (str (- len 1)) #\>) ; pointless use of #symbol!
(symbol (substring str 7 (- len 1)))
(do ((sym (substring str 7))
(c (read-char) (read-char)))
((memq c (list #\> #<eof>))
(string->symbol sym))
(set! sym (string-append sym (string c)))))))))))
> (let ((#symbol<a b c> 32)) (+ #symbol<a b c> 1))
<em class="gray">33</em>
</pre>
<p>But there's a problem: if we try to call object->string with :readable
on these symbol tokens, it does not know that we want it to use our "#symbol<...>"
reader-macro. We need to set the *s7* field <code>'symbol-printer</code>:
</p>
<pre class="indented">
> (define f (apply lambda (list () (list 'let (list (list (symbol "a b") 3)) (symbol "a b")))))
<em class="gray">f</em>
> (f)
<em class="gray">3</em>
> (object->string f :readable)
<em class="gray">"(lambda () (let (((symbol \"a b\") 3)) (symbol \"a b\")))"</em> ; not actually readable!
> (set! (*s7* 'symbol-printer) (lambda (obj) (string-append "#symbol<" (symbol->string obj) ">")))
<em class="gray">#<lambda (obj)></em>
> (object->string f :readable)
<em class="gray">"(lambda () (let ((#symbol<a b> 3)) #symbol<a b>))"</em>
</pre>
<p>
The <code>symbol</code> function
accepts any number of string arguments which it concatenates
to form the new symbol name.
</p>
<p>
These symbols are not just an optimization of string comparison:
</p>
<pre class="indented">
> (define-macro (hi a)
(let ((funny-name (string->symbol ";")))
`(let ((,funny-name ,a)) (+ 1 ,funny-name))))
<em class="gray">hi</em>
> (hi 2)
<em class="gray">3</em>
> (macroexpand (hi 2))
<em class="gray">(let ((; 2)) (+ 1 ;))</em> ; for a good time, try (string #\")
> (define-macro (hi a)
(let ((funny-name (string->symbol "| e t c |")))
`(let ((,funny-name ,a)) (+ 1 ,funny-name))))
<em class="gray">hi</em>
> (hi 2)
<em class="gray">3</em>
> (macroexpand (hi 2))
<em class="gray">(let ((| e t c | 2)) (+ 1 | e t c |))</em>
> (let ((funny-name (string->symbol "| e t c |"))) ; now use it as a keyword arg to a function
(apply define* `((func (,funny-name 32)) (+ ,funny-name 1)))
;; (procedure-source func) is (lambda* ((| e t c | 32)) (+ | e t c | 1))
(apply func (list (symbol->keyword funny-name) 2)))
<em class="gray">3</em>
</pre>
<p>I hope that makes you as happy as it makes me!
</p>
</div>
<div class="indented">
<p id="legolambda">The built-in syntactic forms, such as "begin", are almost first-class citizens.
</p>
<pre class="indented">
> (let ((progn begin))
(progn
(define x 1)
(set! x 3)
(+ x 4)))
<em class="gray">7</em>
> (let ((function lambda))
((function (a b) (list a b)) 3 4))
<em class="gray">(3 4)</em>
> (apply begin '((define x 3) (+ x 2)))
<em class="gray">5</em>
> ((lambda (n) (apply n '(((x 1)) (+ x 2)))) let)
<em class="gray">3</em>
(define-macro (symbol-set! var val) ; like CL's set
`(apply set! ,var ',val ())) ; trailing nil is just to make apply happy — apply*?
(define-macro (progv vars vals . body)
`(apply (apply lambda ,vars ',body) ,vals))
> (let ((s '(one two)) (v '(1 2))) (progv s v (+ one two)))
<em class="gray">3</em>
</pre>
<p>We can snap together program fragments ("look Ma, no macros!"):
</p>
<pre class="indented">
(let* ((x 3)
(arg '(x))
(body `((+ ,x x 1))))
((apply lambda arg body) 12)) ; "legolambda"?
(define (engulph form)
(let ((body `(let ((L ()))
(do ((i 0 (+ i 1)))
((= i 10) (reverse L))
(set! L (cons ,form L))))))
(define function (apply lambda () (list (copy body))))
(function)))
(let ()
(define (hi a) (+ a x))
((apply let '((x 32)) (list (procedure-source hi))) 12)) ; one function, many closures?
(let ((ctr -1)) ; (enum zero one two) but without using a macro
(apply begin
(map (lambda (symbol)
(set! ctr (+ ctr 1))
(list 'define symbol ctr)) ; e.g. '(define zero 0)
'(zero one two)))
(+ zero one two))
</pre>
<p>But there's a prettier way to implement enum ("transparent-for-each"):
</p>
<pre class="indented">
> (define-macro (enum . args)
`(for-each define ',args (iota (length ',args))))
<em class="gray">enum</em>
> (enum a b c)
<em class="gray">#<unspecified></em>
> b
<em class="gray">1</em>
</pre>
<p>Now we notice that <code>(case 0.0 ((0.0) 1) (else 0))</code> is 1, but
how to get pi into a key list?
</p>
<pre class="indented">
> (apply case 'pi `(((,pi) 1) (else 0)))
<em class="gray">1</em>
> (let ((lst '(1 2))) (apply case 'lst `(((,lst) 1) (else 0))))
<em class="gray">1</em> ; same trick puts a list in the keys
> (apply case '+nan.0 `(((,+nan.0) 1) (else 0)))
<em class="gray">0</em> ; (eqv? +nan.0 +nan.0) is #f
</pre>
<p><code>(apply define ...)</code> is similar to CL's set.
</p>
<pre class="indented">
> ((apply define-macro '((m a) `(+ 1 ,a))) 3)
<em class="gray">4</em>
> ((apply define '((hi a) (+ a 1))) 3)
<em class="gray">4</em>
</pre>
<p>Apply let is very similar to eval:
</p>
<pre>
> (apply let '((a 2) (b 3)) '((+ a b)))
<em class="gray">5</em>
> (eval '(+ a b) (inlet 'a 2 'b 3))
<em class="gray">5</em>
> ((apply lambda '(a b) '((+ a b))) 2 3)
<em class="gray">5</em>
> (apply let '((a 2) (b 3)) '((list + a b))) ; a -> 2, b -> 3
<em class="gray">(+ 2 3)</em>
</pre>
<p>The redundant-looking double lists are for apply's benefit. We could
use a trailing null instead (mimicking apply* in some ancient lisps):
</p>
<pre>
> (apply let '((a 2) (b 3)) '(list + a b) ())
<em class="gray">(+ 2 3)</em>
</pre>
<p>Scheme claims that it evaluates the car of an expression, then calls the
result with the rest of the expression. So <code>((if x + -) y z)</code> calls either
<code>(+ y z)</code> or <code>(- y z)</code> depending on x.
But only s7, as far as I know, handles <code>((if x or and) y z)</code>.
</p>
<p>catch, dynamic-wind, and many of the other functions that take function
arguments in standard Scheme, accept macros in s7, and dynamic-wind accepts
#f as the initial and final entries.
</p>
<p>
Currently, you can't set! a built-in syntactic keyword to some new value:
<code>(set! if 3)</code>.
let-temporarily uses set!, so <code>(let-temporarily ((if 3))...)</code>
is also unlikely to work.
</p>
</div>
<div class="indented">
<p>Speaking of speed... It is widely believed
that a Scheme with first class everything can't hope to compete with any
"real" Scheme. Humph I say. Take this little example (which is not
so misleading that I feel guilty about it):
</p>
<pre class="indented">
(define (do-loop n)
(do ((i 0 (+ i 1)))
((= i n))
(if (zero? (modulo i 1000))
(display ".")))
(newline))
(for-each do-loop (list 1000 1000000 10000000))
</pre>
<p>In s7, that takes 0.09 seconds on my home machine. In tinyScheme, from
whence we sprang, it takes 85 seconds. In the chicken interpreter, 5.3
seconds, and after compilation (using -O2) of the chicken compiler output,
0.75 seconds. So, s7 is comparable to chicken in speed, even though chicken
is compiling to C. I think Guile 2.0.9 takes about 1 second.
The equivalent in CL:
clisp interpreted 9.3 seconds, compiled 0.85 seconds; sbcl 0.21 seconds.
Similarly, s7 computes (fib 40) in 0.8 seconds, approximately the same as sbcl.
Guile 2.2.3 takes 7 seconds.
</p>
<div class="small">
<p>
s7's timing tests are in its tools directory. The script
valcall.scm runs them through callgrind. The results
can be found at the end of s7.c.
If you're interested in the standard Scheme benchmarks, it
is possible to add s7 to that package. First, s7-prelude.scm
and s7-postlude.scm need to be added to the benchmarks src directory.
s7-postlude.scm can be empty. My version of s7-prelude.scm is:
</p>
<pre>
(define (this-scheme-implementation-name) "s7")
(define exact-integer? integer?)
(define (exact-integer-sqrt i) (let ((sq (floor (sqrt i)))) (values sq (- i (* sq sq)))))
(define inexact exact->inexact)
(define exact inexact->exact)
(define (square x) (* x x))
(define (vector-map f v) (copy v)) ; for quicksort.scm
(define-macro (import . args) #f)
(define (jiffies-per-second) 1000)
(define (current-jiffy) (round (* (jiffies-per-second) (*s7* 'cpu-time))))
(define (current-second) (floor (*s7* 'cpu-time)))
(define make-bytevector make-byte-vector)
(define bytevector-u8-set! byte-vector-set!)
(set! (*s7* 'symbol-quote?) #t)
</pre>
<p>
If you want to run gcbench, add the define-record-type macro from r7rs.scm.
Here are the diffs for the bench script:
</p>
<pre>
141a142
> S7=${S7:-"/home/bil/motif-snd/repl"}
187a189
> s7 for s7
406a409,421
> # Definitions specific to s7
>
> s7_comp ()
> {
> :
> }
>
> s7_exec ()
> {
> time ${S7} "$1" < "$2"
> }
>
> # -----------------------------------------------------------------------------
940a957,966
>
> s7) NAME='s7'
> COMP=s7_comp
> EXEC=s7_exec
> COMPOPTS=""
> EXTENSION="scm"
> EXTENSIONCOMP="scm"
> COMPCOMMANDS=""
> EXECCOMMANDS=""
> ;;
</pre>
<p>
I call the standalone version of s7 "repl", so its path
is /home/bil/motif-snd/repl. To build repl, get s7.tar.gz
from https://ccrma.stanford.edu/software/s7/s7.tar.gz;
if not using gcc or clang, add the empty file mus-config.h to the tarball's contents,
then (in Linux):
</p>
<pre>
gcc s7.c -o repl -DWITH_MAIN -I. -O2 -g -ldl -lm -Wl,-export-dynamic
;; tcc -o s7 s7.c -I. -lm -DWITH_MAIN -ldl -rdynamic -DWITH_C_LOADER
</pre>
<p>For timing tests, I add "-fomit-frame-pointer -funroll-loops -march=native".
mus-config.h normally has
</p>
<pre>
#define HAVE_COMPLEX_NUMBERS 1
#define HAVE_COMPLEX_TRIG 1
</pre>
<p>
but s7.c has defaults, so mus-config.h can be empty, or absent.
Finally, go back to the benchmarks directory and
</p>
<pre>
bench s7 all
</pre>
<p>
pi.scm and chudnovsky.scm need the gmp version of s7.
As of 24-Oct-23, s7 treats '<> as (#_quote <>) so dynamic.scm doesn't run, and peval.scm gets the wrong result,
but (set! (*7s* 'symbol-quote?) #t) fixes this problem.
I ran the bench script on an AMD 3950X machine, and got these results (in seconds):
ack: 6.6, array1: 6.4, browse: 11.2, bv2string: 4.1, cat: 0.4,
compiler: 16.9, conform: 30.0, cpstak: 42.8, ctak: 16.6, deriv: 9.7,
destruc: 8.6, diviter: 3.7, divrec: 4.6, dynamic: 12.6, earley: 25.5,
equal: 0.3, fft: 12.5, fib: 6.1, fibc: 8.6, fibfp: 1.1, gcbench: 12.9,
graphs: 72.5, lattice: 63.4, matrix: 21.0, maze: 11.4, mazefun: 9.8,
mbrot: 12.6, mbrotZ: 8.0, mperm: 18.9, nboyer: 20.1, nqueens: 27.0,
ntakl: 8.0, nucleic: 8.3, paraffins: 4.4, parsing: 20.7, peval: 15.2,
pnpoly: 9.8, primes: 10.2, puzzle: 10.2, quicksort: 40.0, ray: 8.3,
read1: 0.2, sboyer: 19.1, scheme: 29.5, simplex: 26.9, slatex: 4.2,
string: 0.3, sum1: 0.2, sum: 4.1, sumfp: 2.2, tail: 0.1, tak: 7.1,
takl: 8.1, triangl: 16.4, wc: 4.9. In the gmp case, chudnovsky: 0.017, pi: .01.
</p>
</div>
</div>
<div class="indented">
<p>In s7, there is only one kind of begin statement,
and it can contain both definitions and expressions. These are evaluated in the order
in which they occur, and in the environment at the point of the evaluation. I think
of it as being a little REPL. begin does not introduce a new frame in
the current environment, so defines happen in the enclosing environment.
Finally, begin, explicit or otherwise, does not pretend to emulate letrec*.
</p>
<p>If we allow defines anywhere, the notion of "lexical scope" becomes problematic.
Scheme is already a mess in that regard: take
</p>
<pre class="indented">
(let ((x 1))
(do ((y x x)
(x 3))
((> y 1) y)))
</pre>
<p>In <code>(y x x)</code> the first x is the outer one, and the second is the
following do variable, so this returns 3! But sticking to define, in
</p>
<pre class="indented">
(let ((x 1))
(define y x)
(define x 2)
y)
</pre>
<p>s7 returns 1 even though technically the second x is in y's environment.
Since we treat this as a REPL, y gets its value from the only x defined at
the point it is defined. However,
</p>
<pre class="indented">
(let ((x 1))
(define y (lambda () x))
(define x 2)
(y))
</pre>
<p>returns 2 in s7 because the x in y's function body is not evaluated
until after the second x is defined.
The define propagates backwards, but:
<code>(list x (define x 0))</code>, or <code>(list x (begin (define x 0) x))</code>.
</p>
</div>
<div class="indented">
<p id="r7rs">The r7rs compatibility code is in r7rs.scm, and also built into s7.
<code>(set (*s7* 'scheme-version) 'r7rs)</code> to get r7rs rather than native s7.
None of the error handling routines in r7rs are implemented; see the comment in r7rs.scm
for some details. floor/ and truncate/ can't work as intended: they assume that multiple values
are not spliced. The "division library" is a trivial, pointless micro-optimization.
s7 has no built-in parameters.
</p>
<p>r7rs.scm has the command-line function that makes it easier (on Linux anyway) to
run s7 as a scripting engine. Say we have a s7's repl.c compiled and loaded to the file "repl",
and a file named "runit" with these contents:
</p>
<pre class="indented">
#!repl
!#
(load "r7rs.scm")
(display (command-line))
(newline)
(exit)
</pre>
<p>Now make runit executable via chmod, and run it with some arguments:
</p>
<pre class="indented">
runit 123 abc
</pre>
<p>and it prints: ("repl" "runit" "123" "abc")
</p>
</div>
<!--
<div class="indented">
<p>"Life", a poem.
</p>
<pre class="indented">
(+(*(+))(*)(+(+)(+)(*)))
(((((lambda () (lambda () (lambda () (lambda () 1))))))))
(+ (((lambda () values)) 1 2 3))
(map apply (list map) (list map) (list (list *)) '((((1 2)) ((3 4 5)))))
(do ((do do do)) (do do do))
(*(*)(*) (+)(+) 1)
</pre>
</div>
-->
</blockquote>
<br>
<div class="separator"></div>
<div class="related">
related documentation:
<a href="s7-ffi.html">s7-ffi </a>
<a href="s7-scm.html">s7-scm </a>
</div>
</body>
</html>
|