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
|
\chapter{Built-in predicates} \label{sec:builtin}
\section{Notation of Predicate Descriptions} \label{sec:preddesc}
We have tried to keep the predicate descriptions clear and concise.
First the predicate name is printed in bold face, followed by the
arguments in italics. Arguments are preceded by a `+', `-' or `?' sign.
`+' indicates the argument is input to the predicate, `-' denotes output
and `?' denotes `either input or output'.%
\footnote{These marks do \strong{not} suggest instantiation (e.g.\
var(+Var)).} Constructs like `op/3' refer to the predicate `op' with
arity `3'.
\section{Character representation} \label{sec:chars}
In traditional (Edinburgh-) Prolog, characters are represented using
\jargon{character-codes}. Character codes are integer indices into
a specific character set. Traditionally the character set was 7-bits
US-ASCII. 8-bit character sets have been allowed for a long time, providing
support for national character sets, of which iso-latin-1 (ISO 8859-1)
is applicable to many western languages. Text-files are supposed to
represent a sequence of character-codes.
ISO Prolog introduces three types, two of which are used for characters
and one for accessing binary streams (see open/4). These types are:
\begin{itemlist}
\item [code]
A \jargon{character-code} is an integer representing a single character.
As files may use multi-byte encoding for supporting different character
sets (\idx{utf-8} encoding for example), reading a code from a text-file
is in general not the same as reading a byte.
\item [char]
Alternatively, characters may be represented as
\jargon{one-character-atoms}. This is a very natural representation,
hiding encoding problems from the programmer as well as providing much
easier debugging.
\item [byte]
Bytes are used for accessing binary-streams.
\end{itemlist}
The current version of SWI-Prolog does not provide support for
multi-byte character encoding. This implies for example that it is not
capable of breaking a multi-byte encoded atom into characters. For
SWI-Prolog, bytes and codes are the same and one-character-atoms are
simple atoms containing one byte.
To ease the pain of these multiple representations, SWI-Prolog's
built-in predicates dealing with character-data work as flexible as
possible: they accept data in any of these formats as long as the
interpretation is unambiguous. In addition, for output arguments
that are instantiated, the character is extracted before unification.
This implies that the following two calls are identical, both testing
whether the next input characters is an \const{a}.
\begin{code}
peek_code(Stream, a).
peek_code(Stream, 97).
\end{code}
These multiple-representations are handled by a large number of built-in
predicates, all of which are ISO-compatible. For converting betweem code
and character there is char_code/2. For breaking atoms and numbers into
characters are are atom_chars/2, atom_codes/2, number_codes/2 and
number_chars/2. For character I/O on streams there is get_char/[1,2],
get_code/[1,2], get_byte/[1,2], peek_char/[1,2], peek_code/[1,2],
peek_byte/[1,2], put_code/[1,2], put_char/[1,2] and put_byte/[1,2]. The
prolog-flag \const{double_quotes} (see current_prolog_flag/2) controls
how text between double-quotes is interpreted.
\section{Loading Prolog source files} \label{sec:consulting}
This section deals with loading Prolog source-files. A Prolog source
file is a text-file (often referred to as \jargon{ASCII-file})
containing a Prolog program or part thereof. Prolog source files
come in three flavours:
\begin{description}
\item [ A traditional ] Prolog source file contains a Prolog
clauses and directives, but no \jargon{module-declaration}. They
are normally loaded using consult/1 or ensure_loaded/1.
\item [ A module ] Prolog source file starts with a module
declaration. The subsequent Prolog code is loaded into the
specified module and only the \jargon{public} predicates are
made available to the context loading the module. Module files
are normally loaded using use_module/[1,2]. See \chapref{modules}
for details.
\item [ An include ] Prolog source file is loaded using
the include/1 directive and normally contains only directives.
\end{description}
Prolog source-files are located using absolute_file_name/3 with
the following options:
\begin{code}
locate_prolog_file(Spec, Path) :-
absolute_file_name(Spec,
[ file_type(prolog),
access(read)
],
Path).
\end{code}
The \term{file_type}{prolog} option is used to determine the extension
of the file using prolog_file_type/2. The default extension is
\fileext{pl}. \arg{Spec} allows for the \jargon{path-alias} construct
defined by absolute_file_name/3. The most commonly used path-alias
is \term{library}{LibraryFile}. The example below loads the library
file \file{oset.pl} (containing predicates for manipulating ordered
sets).
\begin{code}
:- use_module(library(oset)).
\end{code}
SWI-Prolog recognises grammar rules (\idx{DCG}) as defined in
\cite{Clocksin:87}. The user may define additional compilation of the
source file by defining the dynamic predicate term_expansion/2.
Transformations by this predicate overrule the systems grammar rule
transformations. It is not allowed to use assert/1, retract/1 or any
other database predicate in term_expansion/2 other than for local
computational purposes.%
\footnote{It does work for normal loading, but not for qcompile/1.}
Directives may be placed anywhere in a source file, invoking any
predicate. They are executed when encountered. If the directive fails,
a warning is printed. Directives are specified by :-/1 or ?-/1. There
is no difference between the two.
SWI-Prolog does not have a separate reconsult/1 predicate. Reconsulting
is implied automatically by the fact that a file is consulted which is
already loaded.
\begin{description}
\predicate{load_files}{2}{+Files, +Options}
The predicate load_files/2 is the parent of all the other loading
predicates. It currently supports a subset of the options of Quintus
load_files/2. \arg{Files} is either specifies a single, or a list of
source-files. The specification for a source-file is handled
absolute_file_name/2. See this predicate for the supported expansions.
\arg{Options} is a list of options using the format
\begin{quote}
\arg{OptionName}(\arg{OptionValue})
\end{quote}
The following options are currently supported:
\begin{description}
\termitem{if}{Condition}
Load the file only if the specified condition is satisfied. The value
\const{true} loads the file unconditionally, \const{changed} loads the
file if it was not loaded before, or has been modified since it was
loaded the last time, \const{not_loaded} loads the file if it was not
loaded before.
\termitem{must_be_module}{Bool}
If \const{true}, raise an error if the file is not a module file. Used by
use_module/[1,2].
\termitem{imports}{ListOrAll}
If \const{all} and the file is a module file, import all public
predicates. Otherwise import only the named predicates. Each predicate
is refered to as <name>/<arity>. This option has no effect if the file
is not a module file.
\termitem{silent}{Bool}
If \const{true}, load the file without printing a message. The specified
value is the default for all files loaded as a result of loading the
specified files.
\termitem{autoload}{Bool}
If \const{true} (default \const{false}), indicate this load is a
\jargon{demand} load. This implies that, depending on the setting of the
prolog-flag \const{verbose_autoload} the load-action is printed at
level \const{informational} or \const{silent}. See also print_message/2
and current_prolog_flag/2.
\end{description}
\predicate{consult}{1}{+File}
Read \arg{File} as a Prolog source file. \arg{File} may be a list of
files, in which case all members are consulted in turn. \arg{File} may
start with the csh(1) special sequences \file{~}, \file{~<user>} and
\file{\$<var>}. \arg{File} may also be \file{library(Name)}, in which
case the libraries are searched for a file with the specified name. See
also library_directory/1 and file_search_path/2. consult/1 may be
abbreviated by just typing a number of file names in a list. Examples:
\begin{center}\begin{tabular}{ll}
\exam{?- consult(load).} & \% consult \file{load} or \file{load.pl} \\
\exam{?- [library(quintus)]}. & \% load Quintus compatibility library \\
\end{tabular}\end{center}
Equivalent to load_files(Files, []).
\predicate{ensure_loaded}{1}{+File}
If the file is not already loaded, this is equivalent to consult/1.
Otherwise, if the file defines a module, import all public predicates.
Finally, if the file is already loaded, is not a module file and the
context module is not the global user module, ensure_loaded/1 will
call consult/1.
With the semantics, we hope to get as closely possible to the clear
semantics without the presence of a module system. Applications using
modules should consider using use_module/[1,2].
Equivalent to load_files(Files, [if(changed)]).
\predicate{include}{1}{+File}
Pretend the terms in \arg{File} are in the source-file in which
\exam{:- include(File)} appears. The include construct is only
honnoured if it appears as a directive in a source-file. Normally
\arg{File} contains a sequence of directives.
\predicate{require}{1}{+ListOfNameAndArity}
Declare that this file/module requires the specified predicates to be
defined ``with their commonly accepted definition''. This predicate
originates from the Prolog portability layer for XPCE. It is intended
to provide a portable mechanism for specifying that this module requires
the specified predicates.
The implementation normally first verifies whether the predicate is
already defined. If not, it will search the libraries and load the
required library.
SWI-Prolog, having autoloading, does {\bf not} load the library. Instead
it creates a procedure header for the predicate if it does not exist.
This will flag the predicate as `undefined'. See also check/0 and
autoload/0.
\predicate{make}{0}{}
Consult all source files that have been changed since they were
consulted. It checks \arg{all} loaded source files: files loaded into a
compiled state using \exam{pl -c \ldots} and files loaded using consult
or one of its derivatives. The predicate make/0 is called after
edit/1, automatically reloading all modified files. It the user uses
an external editor (in a separate window), make/0 is normally used to
update the program after editing.
\predicate{library_directory}{1}{?Atom}
Dynamic predicate used to specify library directories. Default
\file{./lib}, \file{~/lib/prolog} and the system's library
(in this order) are defined. The user may add library directories
using assert/1, asserta/1 or remove system defaults using retract/1.
\predicate{file_search_path}{2}{+Alias, ?Path}
Dynamic predicate used to specify `path-aliases'. This feature is
best described using an example. Given the definition
\begin{code}
file_search_path(demo, '/usr/lib/prolog/demo').
\end{code}
the file specification \file{demo(myfile)} will be expanded to
\file{/usr/lib/prolog/demo/myfile}. The second argument of
file_search_path/2 may be another alias.
Below is the initial definition of the file search path. This path
implies \file{swi(<Path>)} refers to a file in the SWI-Prolog home
directory. The alias \file{foreign(<Path>)} is intended for storing
shared libraries (\fileext{so} or \fileext{DLL} files). See also
load_foreign_library/[1,2].
\begin{code}
user:file_search_path(library, X) :-
library_directory(X).
user:file_search_path(swi, Home) :-
current_prolog_flag(home, Home).
user:file_search_path(foreign, swi(ArchLib)) :-
current_prolog_flag(arch, Arch),
atom_concat('lib/', Arch, ArchLib).
user:file_search_path(foreign, swi(lib)).
\end{code}
The file_search_path/2 expansion is used by all loading predicates as
well as by absolute_file_name/[2,3].
The prolog-flag \const{verbose_file_search} can be set to \const{true}
to help debugging Prolog's search for files.
\predicate{expand_file_search_path}{2}{+Spec, -Path}
Unifies \arg{Path} with all possible expansions of the file name
specification \arg{Spec}. See also absolute_file_name/3.
\predicate{prolog_file_type}{2}{?Extension, ?Type}
This dynamic multifile predicate defined in module \module{user}
determines the extensions considered by file_search_path/2.
\arg{Extension} is the filename extension without the leading dot,
\arg{Type} denotes the type as used by the \term{file_type}{Type}
option of file_search_path/2. Here is the initial definition of
prolog_file_type/2:
\begin{code}
user:prolog_file_type(pl, prolog).
user:prolog_file_type(Ext, prolog) :-
current_prolog_flag(associate, Ext),
Ext \== pl.
user:prolog_file_type(qlf, qlf).
user:prolog_file_type(Ext, executable) :-
current_prolog_flag(shared_object_extension, Ext).
\end{code}
Users may wish to change the extension used for Prolog source files
to avoid conflicts (for example with \program{perl}) as well as to
be compatible with some specific implementation. The preferred
alternative extension is \fileext{pro}.
\predicate{source_file}{1}{?File}
Succeeds if \arg{File} is a loaded Prolog source file. \arg{File} is
the absolute and canonical path to the source-file.
\predicate{source_file}{2}{?Pred, ?File}
Is true if the predicate specified by \arg{Pred} was loaded from file
\arg{File}, where \arg{File} is an absolute path name (see
absolute_file_name/2). Can be used with any instantiation pattern,
but the database only maintains the source file for each predicate.
See also clause_property/2.
\predicate{prolog_load_context}{2}{?Key, ?Value}
Determine loading context. The following keys are defined:
\begin{center}
\begin{tabular}{|l|p{4in}|}
\hline
\bf Key & \bf Description \\
\hline
\const{module} & Module into which file is loaded \\
\const{file} & File loaded \\
\const{stream} & Stream identifier (see current_input/1) \\
\const{directory} & Directory in which \arg{File} lives. \\
\const{term_position} & Position of last term read. Term
of the form \mbox{\tt '\$stream_position'(0,<Line>,0,0,0)} \\
\hline
\end{tabular}
\end{center}
Quintus compatibility predicate. See also source_location/2.
\predicate{source_location}{2}{-File, -Line}
If the last term has been read from a physical file (i.e., not from the
file \const{user} or a string), unify \arg{File} with an absolute path to
the file and \arg{Line} with the line-number in the file. New code
should use prolog_load_context/2.
\predicate{term_expansion}{2}{+Term1, -Term2}
Dynamic predicate, normally not defined. When defined by the user all
terms read during consulting that are given to this predicate. If the
predicate succeeds Prolog will assert \arg{Term2} in the database rather
then the read term (\arg{Term1}). \arg{Term2} may be a term of a the
form `?- \arg{Goal}' or `:- \arg{Goal}'. \arg{Goal} is then treated as
a directive. If \arg{Term2} is a list all terms of the list are stored
in the database or called (for directives). If \arg{Term2} is of the
form below, the system will assert \arg{Clause} and record the indicated
source-location with it.
\begin{quote}
\mbox{\tt '\$source_location'(<File>, <Line>):<Clause>}
\end{quote}
When compiling a module (see \chapref{modules} and the directive module/2),
expand_term/2 will first try term_expansion/2 in the module being
compiled to allow for term-expansion rules that are local to a module.
If there is no local definition, or the local definition fails to
translate the term, expand_term/2 will try term_expansion/2 in module
\module{user}. For compatibility with SICStus and Quintus Prolog, this
feature should not be used. See also expand_term/2, goal_expansion/2 and
expand_goal/2.
\predicate{expand_term}{2}{+Term1, -Term2}
This predicate is normally called by the compiler to perform preprocessing.
First it calls term_expansion/2. If this predicate fails it performs
a grammar-rule translation. If this fails it returns the first argument.
\predicate{goal_expansion}{2}{+Goal1, -Goal2}
Like term_expansion/2, goal_expansion/2 provides for macro-expansion
of Prolog source-code. Between expand_term/2 and the actual compilation,
the body of clauses analysed and the goals are handed to expand_goal/2,
which uses the goal_expansion/2 hook to do user-defined expansion.
The predicate goal_expansion/2 is first called in the module that is
being compiled, and then on the \const{user} module.
Only goals apearing in the body of clauses when reading a source-file
are expanded using mechanism, and only if they appear literally in the
clause, or as an argument to the meta-predicates not/1, call/1 or
forall/2. A real predicate definition is required to deal with
dynamically constructed calls.
\predicate{expand_goal}{2}{+Goal1, -Goal2}
This predicate is normally called by the compiler to perform
preprocessing. First it calls goal_expansion/2. If this fails it returns
the first argument.
\predicate{at_initialization}{1}{+Goal}
Register \arg{Goal} to be run when the system initialises.
Initialisation takes place after reloading a .qlf (formerly .wic) file
as well as after reloading a saved-state. The hooks are run in the
order they were registered. A warning message is issued if \arg{Goal}
fails, but execution continues. See also at_halt/1
\predicate{at_halt}{1}{+Goal}
Register \arg{Goal} to be run when the system halts. The hooks are run
in the order they were registered. Success or failure executing a hook
is ignored. These hooks may not call halt/[0,1].
\predicate{initialization}{1}{+Goal}
Call \arg{Goal} and register it using at_initialization/1. Directives
that do other things than creating clauses, records, flags or setting
predicate attributes should normally be written using this tag to
ensure the initialisation is executed when a saved system starts.
See also qsave_program/[1,2].
\predicate{compiling}{0}{}
Succeeds if the system is compiling source files with the \cmdlineoption{-c}
option into an intermediate code file. Can be used to perform code
optimisations in expand_term/2 under this condition.
\predicate{preprocessor}{2}{-Old, +New}
Read the input file via a Unix process that acts as preprocessor. A
preprocessor is specified as an atom. The first occurrence of the string
`\const{\%f}' is replaced by the name of the file to be loaded. The
resulting atom is called as a Unix command and the standard output of
this command is loaded. To use the Unix C preprocessor one should
define:
\begin{code}
?- preprocessor(Old, '/lib/cpp -C -P %f'), consult(...).
Old = none
\end{code}
\end{description}
\subsection{Quick load files} \label{sec:qlf}
SWI-Prolog supports compilation of individual or multiple Prolog
source files into `Quick Load Files'. A `Quick Load Files' (\fileext{qlf}
file) stores the contents of the file in a precompiled format.
These files load considerably faster than source files and are normally
more compact. They are machine independent and may thus be loaded
on any implementation of SWI-Prolog. Note however that clauses are
stored as virtual machine instructions. Changes to the compiler will
generally make old compiled files unusable.
Quick Load Files are created using qcompile/1. They are loaded using
consult/1 or one of the other file-loading predicates described in
\secref{consulting}. If consult is given the explicit \fileext{pl} file,
it will load the Prolog source. When given the \fileext{qlf} file, it
will load the file. When no extension is specified, it will load the
\fileext{qlf} file when present and the \fileext{pl} file otherwise.
\begin{description}
\predicate{qcompile}{1}{+File}
Takes a single file specification like consult/1 (i.e., accepts
constructs like \file{library(LibFile)} and creates a Quick Load
File from \arg{File}. The file-extension of this file is \fileext{qlf}.
The base name of the Quick Load File is the same as the input file.
If the file contains `\exam{:- consult(\arg{+File})}' or `\exam{:-
[\arg{+File}]}' statements, the referred files are compiled into the
same \fileext{qlf} file. Other directives will be stored in the
\fileext{qlf} file and executed in the same fashion as when loading the
\fileext{pl} file.
For term_expansion/2, the same rules as described in
\secref{compilation} apply.
Source references (source_file/2) in the Quick Load File refer to
the Prolog source file from which the compiled code originates.
\end{description}
\section{Listing and Editor Interface} \label{sec:listing}
SWI-Prolog offers an extensible interface which allows the user to
edit objects of the program: predicates, modules, files, etc. The
editor interface is implemented by edit/1 and consists of three parts:
{\em locating}, {\em selecting} and {\em starting the editor}.
Any of these parts may be extended or redefined by adding clauses to
various multi-file (see multifile/1) predicates defined in the module
\module{prolog_edit}.
The built-in edit specifications for edit/1 (see prolog_edit:locate/3)
are described below.
\begin{center}
\begin{tabular}{|l|p{3.5in}|}
\hline
\multicolumn{2}{|c|}{\bf Fully specified objects} \\
\hline
<Module>:<Name>/<Arity> & Refers a predicate \\
module(<Module>) & Refers to a module \\
file(<Path>) & Refers to a file \\
source_file(<Path>) & Refers to a loaded source-file \\
\hline
\multicolumn{2}{|c|}{\bf Ambiguous specifications} \\
\hline
<Name>/<Arity> & Refers this predicate in any module \\
<Name> & Refers to (1) named predicate in any
module with any arity, (2) a (source) file or
(3) a module. \\
\hline
\end{tabular}
\end{center}
\begin{description}
\predicate{edit}{1}{+Specification}
First exploits prolog_edit:locate/3 to translate \arg{Specification}
into a list of \jargon{Locations}. If there is more than one `hit', the
user is allows to select from the found locations. Finally,
prolog_edit:edit_source/1 is used to invoke the user's preferred editor.
\predicate{prolog_edit:locate}{3}{+Spec, -FullSpec, -Location}
Where \arg{Spec} is the specification provided through edit/1. This
multifile predicate is used to enumerate locations at with an object
satisfying the given \arg{Spec} can be found. \arg{FullSpec} is unified
with the complete specification for the object. This distinction is used
to allow for ambiguous specifications. For example, if \arg{Spec} is
an atom, which appears as the base-name of a loaded file and as the
name of a predicate, \arg{FullSpec} will be bound to \term{file}{Path}
or \arg{Name}/\arg{Arity}.
\arg{Location} is a list of attributes of the location. Normally, this
list will contain the term \term{file}{File} and ---if available--- the
term \term{line}{Line}.
\predicate{prolog_edit:locate}{2}{+Spec, -Location}
Same as prolog_edit:locate/3, but only deals with fully-sepecified
objects.
\predicate{prolog_edit:edit_source}{1}{+Location}
Start editor on \arg{Location}. See prolog_edit:locate/3 for the format
of a location term. This multi-file predicate is normally not defined.
If it succeeds, edit/1 assumes the editor is started.
If it fails, edit/1 will invoke an external editor. The editor
to be invoked is determined from the evironment variable \env{EDITOR},
which may be set from the operating system or from the Prolog
initialisation file using setenv/2. If no editor is defined,
\program{vi} is the default in Unix systems, and \program{notepad}
on Windows.
The predicate prolog_edit:edit_command/2 defines how the editor will
be invoked.
\predicate{prolog_edit:edit_command}{2}{+Editor, -Command}
Determines how \arg{Editor} is to be invoked using shell/1.
\arg{Editor} is the determined editor (see edit_source/1), without
the full path specification, and without possible (exe) extension.
\arg{Command} is an atom describing the command. The pattern
\verb$%f$ is replaced by the full file-name of the location, and
\verb$%d$ by the line number. If the editor can deal with starting
at a specified line, two clauses should be provided, one holding only
the \verb$%f$ pattern, and one holding both patterns.
The default contains definitions for \program{vi}, \program{emacs},
\program{emacsclient}, \program{vim} and \program{notepad} (latter
without line-number version).
Please contribute your specifications to \email{jan@swi.psy.uva.nl}.
\predicate{prolog_edit:load}{0}{}
Normally not-defined multifile predicate. This predicate may be defined
to provide loading hooks for user-extensions to the edit module. For
example, XPCE provides the code below to load \pllib{swi_edit}, containing
definitions to locate classes and methods as well as to bind this package
to the PceEmacs built-in editor.
\begin{code}
:- multifile prolog_edit:load/0.
prolog_edit:load :-
ensure_loaded(library(swi_edit)).
\end{code}
\predicate{listing}{1}{+Pred}
List specified predicates (when an atom is given all predicates with
this name will be listed). The listing is produced on the basis of the
internal representation, thus losing user's layout and variable name
information. See also portray_clause/1.
\predicate{listing}{0}{}
List all predicates of the database using listing/1.
\predicate{portray_clause}{1}{+Clause}
Pretty print a clause. A clause should be specified as a term
`\exam{<Head> :- <Body>}'. Facts are represented as `\exam{<Head> :-
true}'.
\end{description}
\section{Verify Type of a Term} \label{sec:typetest}
\begin{description}
\predicate{var}{1}{+Term}
Succeeds if \arg{Term} currently is a free variable.
\predicate{nonvar}{1}{+Term}
Succeeds if \arg{Term} currently is not a free variable.
\predicate{integer}{1}{+Term}
Succeeds if \arg{Term} is bound to an integer.
\predicate{float}{1}{+Term}
Succeeds if \arg{Term} is bound to a floating point number.
\predicate{number}{1}{+Term}
Succeeds if \arg{Term} is bound to an integer or a floating point number.
\predicate{atom}{1}{+Term}
Succeeds if \arg{Term} is bound to an atom.
\predicate{string}{1}{+Term}
Succeeds if \arg{Term} is bound to a string.
\predicate{atomic}{1}{+Term}
Succeeds if \arg{Term} is bound to an atom, string, integer or floating
point number.
\predicate{compound}{1}{+Term}
Succeeds if \arg{Term} is bound to a compound term. See also functor/3
and =../2.
\predicate{callable}{1}{+Term}
Succeeds if \arg{Term} is bound to an atom or a compound term, so it can
be handed without type-error to call/1, functor/3 and =../2.
\predicate{ground}{1}{+Term}
Succeeds if \arg{Term} holds no free variables.
\end{description}
\section{Comparison and Unification or Terms} \label{sec:compare}
\subsection{Standard Order of Terms} \label{sec:standardorder}
Comparison and unification of arbitrary terms. Terms are ordered in the
so called ``standard order''. This order is defined as follows:
\begin{enumerate}
\item $\arg{Variables} < \arg{Atoms} < \arg{Strings}
< \arg{Numbers} < \arg{Terms}$%
\footnote{Strings might be considered atoms in future versions. See
also \secref{strings}}
\item $\arg{Old~Variable} < \arg{New~Variable}$%
\footnote{In fact the variables are compared on their (dereferenced)
addresses. Variables living on the global stack are always
$<$ than variables on the local stack. Programs
should not rely on the order in which variables are sorted.}
\item \arg{Atoms} are compared alphabetically.
\item \arg{Strings} are compared alphabetically.
\item \arg{Numbers} are compared by value. Integers and floats are
treated identically.
\item \arg{Compound} terms are first checked on their arity, then
on their functor-name (alphabetically) and finally recursively
on their arguments, leftmost argument first.
\end{enumerate}
If the prolog_flag (see current_prolog_flag/2) \const{iso} is defined,
all floating point numbers precede all integers.
\begin{description}
\infixop{==}{+Term1}{+Term2}
Succeeds if \arg{Term1} is equivalent to \arg{Term2}. A variable is only
identical to a sharing variable.
\infixop{\==}{+Term1}{+Term2}
Equivalent to \exam{\Snot Term1 == Term2}.
\infixop{=}{+Term1}{+Term2}
Unify \arg{Term1} with \arg{Term2}. Succeeds if the unification succeeds.
\predicate{unify_with_occurs_check}{2}{+Term1, +Term2}
As \predref{=}{2}, but using \jargon{sound-unification}. That is, a
variable only unifies to a term if this term does not contain the
variable itself. To illustrate this, consider the two goals below:
\begin{code}
1 ?- A = f(A).
A = f(f(f(f(f(f(f(f(f(f(...))))))))))
2 ?- unify_with_occurs_check(A, f(A)).
No
\end{code}
I.e.\ the first creates a \jargon{cyclic-term}, which is printed as
an infinitely nested \functor{f}{1} term (see the \const{max_depth}
option of write_term/2). The second executes logically sound unification
and thus fails.
\infixop{\=}{+Term1}{+Term2}
Equivalent to \exam{\Snot Term1 = Term2}.
\infixop{=@=}{+Term1}{+Term2}
Succeeds if \arg{Term1} is `structurally equal' to \arg{Term2}.
Structural equivalence is weaker than equivalence (\predref{==}{2}), but
stronger than unification (\predref{=}{2}). Two terms are structurally equal if
their tree representation is identical and they have the same `pattern'
of variables. Examples:
\begin{quote}
\begin{tabular}{rclc}
\tt a & \tt =@= & \tt A & false \\
\tt A & \tt =@= & \tt B & true \\
\tt x(A,A) & \tt =@= & \tt x(B,C) & false \\
\tt x(A,A) & \tt =@= & \tt x(B,B) & true \\
\tt x(A,B) & \tt =@= & \tt x(C,D) & true \\
\end{tabular}
\end{quote}
\infixop{\=@=}{+Term1}{+Term2}
Equivalent to \exam{`\Snot Term1 =@= Term2'}.
\infixop{@<}{+Term1}{+Term2}
Succeeds if \arg{Term1} is before \arg{Term2} in the standard order of terms.
\infixop{@=<}{+Term1}{+Term2}
Succeeds if both terms are equal (\predref{==}{2}) or \arg{Term1} is before \arg{Term2} in
the standard order of terms.
\infixop{@>}{+Term1}{+Term2}
Succeeds if \arg{Term1} is after \arg{Term2} in the standard order of terms.
\infixop{@>=}{+Term1}{+Term2}
Succeeds if both terms are equal (\predref{==}{2}) or \arg{Term1} is after \arg{Term2} in
the standard order of terms.
\predicate{compare}{3}{?Order, +Term1, +Term2}
Determine or test the \arg{Order} between two terms in the standard
order of terms. \arg{Order} is one of \const{<}, \const{>} or \const{=},
with the obvious meaning.
\end{description}
\section{Control Predicates} \label{sec:control}
The predicates of this section implement control structures. Normally
these constructs are translated into virtual machine instructions by
the compiler. It is still necessary to implement these constructs
as true predicates to support meta-calls, as demonstrated in the
example below. The predicate finds all currently defined atoms of 1
character long. Note that the cut has no effect when called via one
of these predicates (see !/0).
\begin{code}
one_character_atoms(As) :-
findall(A, (current_atom(A), atom_length(A, 1)), As).
\end{code}
\begin{description}
\predicate{fail}{0}{}
Always fail. The predicate fail/0 is translated into a single virtual
machine instruction.
\predicate{true}{0}{}
Always succeed. The predicate true/0 is translated into a single virtual
machine instruction.
\predicate{repeat}{0}{}
Always succeed, provide an infinite number of choice points.
\predicate{!}{0}{}
Cut. Discard choice points of parent frame and frames created after the
parent frame. As of SWI-Prolog 3.3, the semantics of the cut are
compliant with the ISO standard. This implies that the cut is
transparent to \predref{;}{2}, \predref{->}{2} and \predref{*->}{2}.
Cuts appearing in the {\em condition} part of \predref{->}{2} and
\predref{*->}{2} as well as in \predref{\+}{1} are local to the
condition.%
\footnote{Up to version 4.0.6, the sequence X=!, X acted as a true
cut. This feature has been deleted for ISO compliance.}
\begin{center}\begin{tabular}{ll}
\exam{t1 :- (a, !, fail ; b).} & \% cuts {a}/0 and {t1}/0 \\
\exam{t2 :- (a -> b, ! ; c).} & \% cuts {b}/0 and {t2}/0 \\
\exam{t3 :- call((a, !, fail ; b)).} & \% cuts {a}/0 \\
\exam{t4 :- \Snot (a, !, fail ; b).} & \% cuts {a}/0 \\
\end{tabular}\end{center}
\infixop{,}{+Goal1}{+Goal2}
Conjunction. Succeeds if both `Goal1' and `Goal2' can be proved. It is
defined as (this definition does not lead to a loop as the second comma
is handled by the compiler):
\begin{code}
Goal1, Goal2 :- Goal1, Goal2.
\end{code}
\infixop{;}{+Goal1}{+Goal2}
The `or' predicate is defined as:
\begin{code}
Goal1 ; _Goal2 :- Goal1.
_Goal1 ; Goal2 :- Goal2.
\end{code}
\infixop{|}{+Goal1}{+Goal2}
Equivalent to \predref{;}{2}. Retained for compatibility only. New code
should use \predref{;}{2}.
\infixop{->}{+Condition}{+Action}
If-then and If-Then-Else. The \predref{->}{2} construct commits to
the choices made at its left-hand side, destroying choice-points created
inside the clause (by \predref{;}{2}), or by goals called by
this clause. Unlike \predref{!}{0}, the choicepoint of the predicate as
a whole (due to multiple clauses) is \strong{not} destroyed. The
combination \predref{;}{2} and \predref{->}{2} is
defines as:
\begin{code}
If -> Then; _Else :- If, !, Then.
If -> _Then; Else :- !, Else.
If -> Then :- If, !, Then.
\end{code}
Note that the operator precedence relation between \const{;} and
\const{->} ensure \exam{If -> Then ; Else} is actually a term of the
form \exam{;(->(If, Then), Else)}. The first two clauses belong to
the definition of \predref{;}{2}), while only the last defines
\predref{->}{2}.
\infixop{*->}{+Condition}{+Action ; +Else}
This construct implements the so-called `soft-cut'. The control is
defined as follows: If \arg{Condition} succeeds at least once, the
semantics is the same as (\arg{Condition}, \arg{Action}). If
\arg{Condition} does not succeed, the semantics is that of
(\arg{Condition}, \arg{Else}). In other words, If \arg{Condition}
succeeds at least once, simply behave as the conjunction of
\arg{Condition} and \arg{Action}, otherwise execute \arg{Else}.
\prefixop{\+}{+Goal}
Succeeds if `Goal' cannot be proven (mnemonic: \chr{+} refers to {\em
provable} and the backslash (\chr{\}) is normally used to
indicate negation).
\end{description}
\section{Meta-Call Predicates} \label{sec:metacall}
Meta call predicates are used to call terms constructed at run time.
The basic meta-call mechanism offered by SWI-Prolog is to use
variables as a subclause (which should of course be bound to a valid
goal at runtime). A meta-call is slower than a normal call as it
involves actually searching the database at runtime for the predicate,
while for normal calls this search is done at compile time.
\begin{description}
\predicate{call}{1}{+Goal}
Invoke \arg{Goal} as a goal. Note that clauses may have variables as
subclauses, which is identical to call/1, except when the argument is
bound to the cut. See \predref{!}{0}.
\predicate{call}{2}{+Goal, +ExtraArg1, \ldots} % 2..
Append \arg{ExtraArg1, ExtraArg2, \ldots} to the argument list of
\arg{Goal} and call the result. For example, \exam{call(plus(1), 2, X)}
will call plus/3, binding \arg{X} to 3.
The call/[2..] construct is handled by the compiler, which implies that
redefinition as a predicate has no effect. The predicates call/[2-6]
are defined as true predicates, so they can be handled by interpreted
code.
\predicate{apply}{2}{+Term, +List}
Append the members of \arg{List} to the arguments of \arg{Term} and call
the resulting term. For example: \exam{apply(plus(1), [2, X])} will
call \exam{plus(1, 2, X)}. apply/2 is incorporated in the virtual
machine of SWI-Prolog. This implies that the overhead can be compared to
the overhead of call/1. New code should use call/[2..] if the length of
\arg{List} is fixed, which is more widely supported and faster because
there is no need to build and examine the argument list.
\predicate{not}{1}{+Goal}
Succeeds when \arg{Goal} cannot be proven. Retained for compatibility
only. New code should use \predref{\+}{1}.
\predicate{once}{1}{+Goal}
Defined as:
\begin{code}
once(Goal) :-
Goal, !.
\end{code}
once/1 can in many cases be replaced with \predref{->}{2}. The only
difference is how the cut behaves (see !/0). The following two clauses
are identical:
\begin{code}
1) a :- once((b, c)), d.
2) a :- b, c -> d.
\end{code}
\predicate{ignore}{1}{+Goal}
Calls \arg{Goal} as once/1, but succeeds, regardless of whether
\arg{Goal} succeeded or not. Defined as:
\begin{code}
ignore(Goal) :-
Goal, !.
ignore(_).
\end{code}
\predicate{call_with_depth_limit}{3}{+Goal, +Limit, -Result}
If \arg{Goal} can be proven without recursion deeper than \arg{Limit}
levels, call_with_depth_limit/3 succeeds, binding \arg{Result} to the
deepest recursion level used during the proof. Otherwise, \arg{Result}
is unified with \const{depth_limit_exceeded} if the limit was exceeded
during the proof, or the entire predicate fails if \arg{Goal} fails
without exceeding \arg{Limit}.
The depth-limit is guarded by the internal machinery. This may differ
from the depth computed based on a theoretical model. For example,
true/0 is translated into an inlined virtual machine instruction. Also,
repeat/0 is not implemented as below, but as a non-deterministic foreign
predicate.
\begin{code}
repeat.
repeat :-
repeat.
\end{code}
As a result, call_with_depth_limit/3 may still loop inifitly on programs
that should theoretically finish in finite time. This problem can be
cured by using Prolog equivalents to such built-in predicates.
This predicate may be used for theorem-provers to realise techniques
like \jargon{iterrative deepening}. It was implemented after discussion
with Steve Moyle \email{smoyle@ermine.ox.ac.uk}.
\predicate{call_cleanup}{3}{:Goal, +Catcher, :Cleanup}
Calls \arg{Goal}. If \arg{Goal} is completely finished, either
by deterministic success, failure, its choicepoint being cut or
raising an exception and \arg{Catcher} unifies to the termination
code (see below), \arg{Cleanup} is called. Success or failure of
\arg{Cleanup} is ignored and possibly choicepoints it created are
destroyed (as once/1). If cleanup throws an exception this is
executed as normal.
\arg{Catcher} is unified with a term describing how the call has
finished. If this unification fails, \arg{Cleanup} is \emph{not}
called.
\begin{description}
\termitem{exit}{}
\arg{Goal} succeeded without leaving any choicepoints.
\termitem{fail}{}
\arg{Goal} failed.
\termitem{!}{}
\arg{Goal} succeeded with choicepoints and these are now discarded
by the execution of a cut (or orther pruning of the search tree such as
if-then-else).
\termitem{exception}{Exception}
\arg{Goal} raised the given \arg{Exception}.
\end{description}
Typical use of this predicate is cleanup of permanent data storage
required to execute \arg{Goal}, close file-descriptors, etc. The example
below provides a non-deterministic search for a term in a file, closing
the stream as needed.
\begin{code}
term_in_file(Term, File) :-
open(File, read, In),
call_cleanup(term_in_stream(Term, In), _, close(In)).
term_in_stream(Term, In) :-
repeat,
read(In, T),
( T == end_of_file
-> !, fail
; T = Term
).
\end{code}
Note that this predicate is impossible to implement in Prolog other then
reading all terms into a list, close the file and call member/2 because
without call_cleanup/3 there is no way to gain control if the
choicepoint left by repeat is killed by a cut.
This predicate is a SWI-Prolog extension. See also call_cleanup/2 for
compatibility to other Prolog implementations.
\predicate{call_cleanup}{2}{:Goal, :Cleanup}
This predicate is equivalent to \term{call_cleanup}{Goal, _, Cleanup},
calling \arg{Cleanup} regardless of the reason for termination and
without providing information. This predicate provides compatibility
to a number of other Prolog implementations.
\end{description}
\section{ISO compliant Exception handling} \label{sec:exception}
SWI-Prolog defines the predicates catch/3 and throw/1 for ISO compliant
raising and catching of exceptions. In the current implementation
(4.0.6), most of the built-in predicates generate exceptions, but
some obscure predicates merely print a message, start the debugger and
fail, which was the normal behaviour before the introduction of
exceptions.
\begin{description}
\predicate{catch}{3}{:Goal, +Catcher, :Recover}
Behaves as call/1 if no exception is raised when executing \arg{Goal}.
If a exception is raised using throw/1 while \arg{Goal} executes, and
the \arg{Goal} is the innermost goal for which \arg{Catcher} unifies
with the argument of throw/1, all choicepoints generated by \arg{Goal}
are cut, the system backtracks to the start of catch/3 while preserving
the thrown exception term and \arg{Recover} is called as in call/1.
The overhead of calling a goal through catch/3 is very comparable to
call/1. Recovery from an exception is much slower, especially if the
exception-term is large due to the copying thereof.
\predicate{throw}{1}{+Exception}
Raise an exception. The system looks for the innermost catch/3
ancestor for which \arg{Exception} unifies with the \arg{Catcher}
argument of the catch/3 call. See catch/3 for details.
ISO demands throw/1 to make a copy of \arg{Exception}, walk up the stack
to a catch/3 call, backtrack and try to unify the copy of
\arg{Exception} with \arg{Catcher}. SWI-Prolog delays making a copy of
\arg{Exception} and backtracking until it actually found a matching
catch/3 goal. The advantage is that we can start the debugger at the
first possible location while preserving the entire exception context if
there is no matching catch/3 goal. This aproach can lead to different
behaviour if \arg{Goal} and \arg{Catcher} of catch/3 call share
variables. We assume this to be highly unlikely and could not think
of a scenario where this is useful.%
\footnote{I'd like to acknowledge Bart Demoen for his
clarifications on these matters.}
If an exception is raised in a callback from C (see \chapref{foreign})
and not caught in the same call-back, PL_next_solution() fails and
the exception context can be retrieved using PL_exception().
\end{description}
\subsection{Debugging and exceptions}
\index{exceptions,debugging}%
\index{debugging,exceptions}%
Before the introduction of exceptions in SWI-Prolog a runtime error was
handled by printing an error message, after which the predicate failed.
If the prolog_flag (see current_prolog_flag/2) \const{debug_on_error}
was in effect (default), the tracer was switched on. The combination of
the error message and trace information is generally sufficient to
locate the error.
With exception handling, things are different. A programmer may wish to
trap an exception using catch/3 to avoid it reaching the user. If the
exception is not handled by user-code, the interactive toplevel will
trap it to prevent termination.
If we do not take special precautions, the context information
associated with an unexpected exception (i.e, a programming error) is
lost. Therefore, if an exception is raised, which is not caught using
catch/3 and the toplevel is running, the error will be printed, and the
system will enter trace mode.
If the system is in an non-interactive callback from foreign code and
there is no catch/3 active in the current context, it cannot determine
whether or not the exception will be caught by the external routine
calling Prolog. It will then base its behaviour on the prolog_flag
debug_on_error:
\begin{itemlist}
\item [current_prolog_flag(debug_on_error, false)]
The exception does not trap the debugger and is returned to the foreign
routine calling Prolog, where it can be accessed using PL_exception().
This is the default.
\item [current_prolog_flag(debug_on_error, true)]
If the exception is not caught by Prolog in the current context, it will
trap the tracer to help analysing the context of the error.
\end{itemlist}
While looking for the context in which an exception takes place, it is
advised to switch on debug mode using the predicate debug/0.
\subsection{The exception term} \label{sec:exceptterm}
Builtin predicates generates exceptions using a term
\term{error}{Formal, Context}. The first argument is the `formal'
description of the error, specifying the class and generic defined
context information. When applicable, the ISO error-term definition
is used. The second part describes some additional context to help
the programmer while debugging. In its most generic form this is
a term of the form \term{context}{Name/Arity, Message}, where
\arg{Name}/\arg{Arity} describes the built-in predicate that raised
the error, and \arg{Message} provides an additional description of
the error. Any part of this structure may be a variable if no
information was present.
\subsection{Printing messages} \label{sec:printmsg}
The predicate print_message/2 may be used to print a message term
in a human readable format. The other predicates from this section
allow the user to refine and extend the message system. The most
common usage of print_message/2 is to print error messages from
exceptions. The code below prints errors encountered during the
execution of \arg{Goal}, without further propagating the exception
and without starting the debugger.
\begin{code}
...,
catch(Goal, E,
( print_message(error, E),
fail
)),
...
\end{code}
Another common use is to defined message_hook/3 for printing messages
that are normally \jargon{silent}, suppressing messages, redirecting
messages or make something happen in addition to printing the message.
\begin{description}
\predicate{print_message}{2}{+Kind, +Term}
The predicate print_message/2 is used to print messages, notably from
exceptions in a human-readable format. \arg{Kind} is one of
\const{informational}, \const{banner}, \const{warning}, \const{error},
\const{help} or \const{silent}. A human-readable message is printed to
the stream \const{user_error}.
\index{silent}\index{quiet}%
If the prolog flag (see current_prolog_flag/2) \const{verbose} is
\const{silent}, messages with \arg{Kind} \const{informational},
or \const{banner} are treated as silent. See \cmdlineoption{-q}.
This predicate first translates the \arg{Term} into a list of
`message lines' (see print_message_lines/3 for details). Next it will
call the hook message_hook/3 to allow the user intercepting the message.
If message_hook/3 fails it will print the message unless \arg{Kind} is
silent.
The print_message/2 predicate and its rules are in the file
\file{<plhome>/boot/messages.pl}, which may be inspected for more
information on the error messages and related error terms.
See also message_to_string/2.
\predicate{print_message_lines}{3}{+Stream, +Prefix, +Lines}
Print a message (see print_message/2) that has been translated to
a list of message elements. The elements of this list are:
\begin{description}
\definition{<Format>-<Args>}
Where \arg{Format} is an atom and \arg{Args} is a list
of format argument. Handed to format/3.
\definition{\const{flush}}
If this appears as the last element, \arg{Stream} is flushed
(see flush_output/1) and no final newline is generated.
\definition{\const{at_same_line}}
If this appears as first element, no prefix is printed for
the first line and the line-position is not forced to 0
(see format/1, \verb$~N$).
\definition{<Format>}
Handed to format/3 as \exam{format(Stream, Format, [])}.
\definition{nl}
A new line is started and if the message is not complete
the \arg{Prefix} is printed too.
\end{description}
See also print_message/2 and message_hook/3.
\predicate{message_hook}{3}{+Term, +Kind, +Lines}
Hook predicate that may be define in the module \const{user} to
intercept messages from print_message/2. \arg{Term} and \arg{Kind} are
the same as passed to print_message/2. \arg{Lines} is a list of format
statements as described with print_message_lines/3. See also
message_to_string/2.
This predicate should be defined dynamic and multifile to allow other
modules defining clauses for it too.
\predicate{message_to_string}{2}{+Term, -String}
Translates a message-term into a string object (see \secref{strings}.
Primarily intended to write messages to Windows in XPCE (see
\secref{xpce}) or other GUI environments.
\end{description}
\section{Handling signals} \label{sec:signal}
As of version 3.1.0, SWI-Prolog is capable to handle software interrupts
(signals) in Prolog as well as in foreign (C) code (see \secref{csignal}).
Signals are used to handle internal errors (execution of a non-existing
CPU intruction, arithmetic domain errors, illegal memory access,
resource overflow, etc.), as well as for dealing asynchronous
inter-process communication.
Signals are defined by the Posix standard and part of all Unix machines.
The MS-Windows Win32 provides a subset of the signal handling routines,
lacking the vital funtionality to raise a signal in another thread for
achieving asynchronous inter-process (or inter-thread) communication
(Unix kill() function).
\begin{description}
\predicate{on_signal}{3}{+Signal, -Old, :New}
Determines the reaction on \arg{Signal}. \arg{Old} is unified with
the old behaviour, while the behaviour is switched to \arg{New}. As
with similar environment-control predicates, the current value is
retrieved using \exam{on_signal(Signal, Current, Current)}.
The action description is an atom denoting the name of the predicate
that will be called if \arg{Signal} arrives. on_signal/3 is a meta
predicate, which implies that <Module>:<Name> refers the <Name>/1 in
the module <Module>.
Two predicate-names have special meaning. \const{throw} implies Prolog
will map the signal onto a Prolog exception as described in
\secref{exception}. \const{default} resets the handler to the settings
active before SWI-Prolog manipulated the handler.
Signals bound to a foreign function through PL_signal() are reported
using the term \term{\$foreign_function}{Address}.
After receiving a signal mapped to \const{throw}, the exception raised
has the structure
\begin{quote}\tt
error(signal(<SigName>, <SigNum>), <Context>)
\end{quote}
One possible usage of this is, for example, to limit the time spent
on proving a goal. This requires a little C-code for setting the
alarm timer (see \chapref{foreign}):
\begin{code}
#include <SWI-Prolog.h>
#include <unistd.h>
foreign_t
pl_alarm(term_t time)
{ double t;
if ( PL_get_float(time, &t) )
{ alarm((long)(t+0.5));
PL_succeed;
}
PL_fail;
}
install_t
install()
{ PL_register_foreign("alarm", 1, pl_alarm, 0);
}
\end{code}
Next, we can define the following Prolog code:
\begin{code}
:- load_foreign_library(alarm).
:- on_signal(alrm, throw).
:- module_transparent
call_with_time_limit/2.
call_with_time_limit(Goal, MaxTime) :-
alarm(MaxTime),
catch(Goal, error(signal(alrm, _), _), fail), !,
alarm(0).
call_with_time_limit(_, _) :-
alarm(0),
fail.
\end{code}
The signal names are defined by the C-Posix standards as symbols of the
form {\tt SIG_}<SIGNAME>. The Prolog name for a signal is the lowercase
version of <SIGNAME>. The predicate current_signal/3 may be used to map
between names and signals.
Initially, some signals are mapped to \const{throw}, while all
other signals are \const{default}. The following signals throw
an exception: \const{ill}, \const{fpe}, \const{segv}, \const{pipe},
\const{alrm}, \const{bus}, \const{xcpu}, \const{xfsz} and
\const{vtalrm}.
\predicate{current_signal}{3}{?Name, ?Id, ?Handler}
Enumerate the currently defined signal handling. \arg{Name} is the
signal name, \arg{Id} is the numerical identifier and \arg{Handler}
is the currently defined handler (see on_signal/3).
\end{description}
\subsection{Notes on signal handling}
Before deciding to deal with signals in your application, please
consider the following:
\begin{itemlist}
\item[Portibility]
On MS-Windows, the signal interface is severely limited. Different Unix
brands support different sets of signals, and the relation between
signal name and number may vary.
\item[Safety]
Signal handling is not completely safe in the current implementation,
especially if \const{throw} is used in combination with external foreign
code. The system will use the C longjmp() construct to direct control to
the innermost PL_next_solution(), thus forcing an external procedure to
be abandoned at an arbitrary moment. Most likely not all SWI-Prologs own
foreign code is (yet) safe too.
\item[Garbage Collection]
The garbage collector will block all signals that are handled by Prolog.
While handling a signal, the garbage-collector is disabled.
\item[Time of delivery]
Normally delivery is immediate (or as defined by the operating system
used). Signals are blocked when the garbage collector is active, and
internally delayed if they occur within in a `critical section'. The
critical sections are generally very short.
\end{itemlist}
\section{The `block' control-structure} \label{sec:block3}
The block/3 predicate and friends have been introduced before ISO
compatible catch/3 exception handling for compatibility with some
Prolog implementation. The only feature not covered by catch/3
and throw/1 is the posibility to execute global cuts. New code
should use catch/3 and throw/1 to deal with exceptions.
\begin{description}
\predicate{block}{3}{+Label, +Goal, -ExitValue}
Execute \arg{Goal} in a \jargon{block}. \arg{Label} is the name of the
block. \arg{Label} is normally an atom, but the system imposes
no type constraints and may even be a variable. \arg{ExitValue}
is normally unified to the second argument of an exit/2 call
invoked by \arg{Goal}.
\predicate{exit}{2}{+Label, +Value}
Calling exit/2 makes the innermost \arg{block} which \arg{Label} unifies
exit. The block's \arg{ExitValue} is unified with \arg{Value}. If this
unification fails the block fails.
\predicate{fail}{1}{+Label}
Calling fail/1 makes the innermost \arg{block} which \arg{Label}
unifies fail immediately. Implemented as
\begin{code}
fail(Label) :- !(Label), fail.
\end{code}
\predicate{!}{1}{+Label}
Cut all choice-points created since the entry of the innermost
\arg{block} which \arg{Label} unifies.
\end{description}
\section{DCG Grammar rules} \label{sec:DCG}
\index{DCG}%
Grammar rules form a comfortable interface to \jargon{difference-lists}.
They are designed both to support writing parsers that build a parse-tree
from a list as for generating a flat list from a term. Unfortunately,
Definite Clause Grammar (DCG) handling is not part of the Prolog
standard. Most Prolog engines implement DCG, but the details differ
slightly.
Grammar rules look like ordinary clauses using \functor{-->}{2} for
separating the head and body rather then \functor{:-}{2}. Expanding
grammar rules is done by expand_term/2, which adds two additional
argument to each term for representing the difference list. We will
illustrate the behaviour by defining a rule-set for parsing an integer.
\begin{code}
integer(I) -->
digit(D0),
digits(D),
{ number_chars(I, [D0|D])
}.
digits([D|T]) -->
digit(D), !,
digits(T).
digits([]) -->
[].
digit(D) -->
[D],
{ code_type(D, digit)
}.
\end{code}
The body of a grammar rule can contain three types of terms. A compound
term interpreted as a reference to a grammar-rule. Code between
\verb${$\ldots\verb$}$ is interpreted as a reference to ordinary Prolog
code and finally, a list is interpreted as a sequence of literals. The
Prolog control-constructs (\functor{\+}{1}, \functor{->}{2},
\functor{;}/2, \functor{,}{2} and \functor{!}{0}) can be used in grammar
rules.
Grammar rule-sets are called using the builtin predicates phrase/2
and phrase/3:
\begin{description}
\predicate{phrase}{2}{+RuleSet, +InputList}
Equivalent to \exam{phrase(\arg{RuleSet}, \arg{InputList}, [])}.
\predicate{phrase}{3}{+RuleSet, +InputList, -Rest}
Activate the rule-set with given name. `InputList' is the list of tokens
to parse, `Rest' is unified with the remaining tokens if the sentence is
parsed correctly. The example below calls the rule-set `integer' defined
above.
\begin{code}
?- phrase(integer(X), "42 times", Rest).
X = 42
Rest = [32, 116, 105, 109, 101, 115]
\end{code}
\end{description}
\section{Database} \label{sec:db}
SWI-Prolog offers three different database mechanisms. The first one is
the common assert/retract mechanism for manipulating the clause
database. As facts and clauses asserted using assert/1 or one of its
derivatives become part of the program these predicates compile the term
given to them. retract/1 and retractall/1 have to unify a term and
therefore have to decompile the program. For these reasons the
assert/retract mechanism is expensive. On the other hand, once compiled,
queries to the database are faster than querying the recorded database
discussed below. See also dynamic/1.
The second way of storing arbitrary terms in the database is using the
``recorded database''. In this database terms are associated with a
\arg{key}. A key can be an atom, integer or term. In the last case
only the functor and arity determine the key. Each key has a chain of
terms associated with it. New terms can be added either at the head or
at the tail of this chain. This mechanism is considerably faster than
the assert/retract mechanism as terms are not compiled, but just copied
into the heap.
The third mechanism is a special purpose one. It associates an integer
or atom with a key, which is an atom, integer or term. Each key can only
have one atom or integer associated with it. It is faster than the
mechanisms described above, but can only be used to store simple status
information like counters, etc.
\begin{description}
\predicate{abolish}{1}{:PredicateIndicator}
Removes all clauses of a predicate with functor \arg{Functor} and arity
\arg{Arity} from the database. All predicate attributes (dynamic,
multifile, index, etc.) are reset to their defaults. Abolishing an
imported predicate only removes the import link; the predicate will keep
its old definition in its definition module.
According to the ISO standard, abolish/1 can only be applied to dynamic
procedures. This is odd, as for dealing with dynamic procedures there
is already retract/1 and retractall/1. The abolish/1 predicate has been
introduced in DEC-10 Prolog precisely for dealing with static procedures.
In SWI-Prolog, abolish/1 works on static procedures, unless the prolog
flag \const{iso} is set to \const{true}.
It is advised to use retractall/1 for erasing all clauses of a dynamic
predicate.
\predicate{abolish}{2}{+Name, +Arity}
Same as \exam{abolish(Name/Arity)}. The predicate abolish/2 conforms to
the Edinburgh standard, while abolish/1 is ISO compliant.
\predicate{redefine_system_predicate}{1}{+Head}
This directive may be used both in module \const{user} and in normal
modules to redefine any system predicate. If the system definition is
redefined in module \const{user}, the new definition is the default
definition for all sub-modules. Otherwise the redefinition is local
to the module. The system definition remains in the module \const{system}.
Redefining system predicate facilitates the definition of compatibility
packages. Use in other context is discouraged.
\predicate{retract}{1}{+Term}
When \arg{Term} is an atom or a term it is unified with the first unifying fact
or clause in the database. The fact or clause is removed from the database.
\predicate{retractall}{1}{+Head}
All facts or clauses in the database for which the \arg{head}
unifies with \arg{Head} are removed.
\predicate{assert}{1}{+Term}
Assert a fact or clause in the database. \arg{Term} is asserted as the last
fact or clause of the corresponding predicate.
\predicate{asserta}{1}{+Term}
Equivalent to assert/1, but \arg{Term} is asserted as first clause or fact
of the predicate.
\predicate{assertz}{1}{+Term}
Equivalent to assert/1.
\predicate{assert}{2}{+Term, -Reference}
Equivalent to assert/1, but \arg{Reference} is unified with a unique
reference to the asserted clause. This key can later be used with
clause/3 or erase/1.
\predicate{asserta}{2}{+Term, -Reference}
Equivalent to assert/2, but \arg{Term} is asserted as first clause or fact
of the predicate.
\predicate{assertz}{2}{+Term, -Reference}
Equivalent to assert/2.
\predicate{recorda}{3}{+Key, +Term, -Reference}
Assert \arg{Term} in the recorded database under key \arg{Key}. \arg{Key} is an
integer, atom or term. \arg{Reference} is unified with a unique reference
to the record (see erase/1).
\predicate{recorda}{2}{+Key, +Term}
Equivalent to \exam{recorda(\arg{Key}, \arg{Value}, _)}.
\predicate{recordz}{3}{+Key, +Term, -Reference}
Equivalent to recorda/3, but puts the \arg{Term} at the tail of the terms
recorded under \arg{Key}.
\predicate{recordz}{2}{+Key, +Term}
Equivalent to \exam{recordz(\arg{Key}, \arg{Value}, _)}.
\predicate{recorded}{3}{+Key, -Value, -Reference}
Unify \arg{Value} with the first term recorded under \arg{Key} which does
unify. \arg{Reference} is unified with the memory location of the record.
\predicate{recorded}{2}{+Key, -Value}
Equivalent to \exam{recorded(\arg{Key}, \arg{Value}, _)}.
\predicate{erase}{1}{+Reference}
Erase a record or clause from the database. \arg{Reference} is an
integer returned by recorda/3 or recorded/3, clause/3, assert/2,
asserta/2 or assertz/2. Other integers might conflict with the internal
consistency of the system. Erase can only be called once on a record or
clause. A second call also might conflict with the internal consistency
of the system.%
\bug{The system should have a special type for pointers, thus avoiding
the Prolog user having to worry about consistency matters. Currently some
simple heuristics are used to determine whether a reference is valid.}
\predicate{flag}{3}{+Key, -Old, +New}
\arg{Key} is an atom, integer or term. Unify \arg{Old} with the old
value associated with \arg{Key}. If the key is used for the first time
\arg{Old} is unified with the integer 0. Then store the value of
\arg{New}, which should be an integer, float, atom or arithmetic
expression, under \arg{Key}. flag/3 is a very fast mechanism for storing
simple facts in the database. Example:
\begin{code}
:- module_transparent succeeds_n_times/2.
succeeds_n_times(Goal, Times) :-
( flag(succeeds_n_times, Old, 0),
Goal,
flag(succeeds_n_times, N, N+1),
fail
; flag(succeeds_n_times, Times, Old)
).
\end{code}
\end{description}
\subsection{Update view} \label{sec:update}
\index{logical,update view}%
\index{immediate, update view}%
\index{update view}%
Traditionally, Prolog systems used the \jargon{immediate update view}:
new clauses became visible to predicates backtracking over dynamic
predicates immediately and retracted clauses became invisible
immediately.
Starting with SWI-Prolog 3.3.0 we adhere the \jargon{logical update
view}, where backtrackable predicates that enter the definition of a
predicate will not see any changes (either caused by assert/1 or
retract/1) to the predicate. This view is the ISO standard, the
most commonly used and the most `safe'.%
\footnote{For example, using the immediate update view, no call to a
dynamic predicate is deterministic.}
Logical updates are realised by keeping reference-counts on predicates
and \jargon{generation} information on clauses. Each change to the
database causes an increment of the generation of the database. Each
goal is tagged with the generation in which it was started. Each clause
is flagged with the generation it was created as well as the generation
it was erased. Only clauses with `created' \ldots `erased' interval
that encloses the generation of the current goal are considered visible.
\subsection{Indexing databases}
By default, SWI-Prolog, as most other implementations, indexes
predicates on their first argument. SWI-Prolog allows indexing
on other and multiple arguments using the declaration index/1.
For advanced database indexing, it defines hash_term/2:
\begin{description}
\predicate{hash_term}{2}{+Term, -HashKey}
If \arg{Term} is a ground term (see ground/1), \arg{HashKey} is
unified with a positive integer value that may be used as a hash-key
to the value. If \arg{Term} is not ground, the predicate succeeds
immediately, leaving \arg{HashKey} an unbound variable.
This predicate may be used to build hash-tables as well as to exploit
argument-indexing to find complex terms more quickly.
The hash-key does not rely on temporary information like addresses of
atoms and may be assumed constant over different invocations of
SWI-Prolog.
\end{description}
\section{Declaring predicates properties} \label{ch:dynamic}
\label{sec:declare}
This section describes directives which manipulate attributes of
predicate definitions. The functors dynamic/1, multifile/1 and
discontiguous/1 are operators of priority 1150 (see op/3), which
implies the list of predicates they involve can just be a comma
separated list:
\begin{code}
:- dynamic
foo/0,
baz/2.
\end{code}
On SWI-Prolog all these directives are just predicates. This implies
they can also be called by a program. Do not rely on this feature if
you want to maintain portability to other Prolog implementations.
\begin{description}
\prefixop{dynamic}{+Functor/+Arity, \ldots}
Informs the interpreter that the definition of the predicate(s) may change
during execution (using assert/1 and/or retract/1). Currently dynamic/1
only stops the interpreter from complaining about undefined predicates (see
unknown/2). Future releases might prohibit assert/1 and retract/1 for
not-dynamic declared procedures.
\prefixop{multifile}{+Functor/+Arity, \ldots}
Informs the system that the specified predicate(s) may be defined over
more than one file. This stops consult/1 from redefining a predicate
when a new definition is found.
\prefixop{discontiguous}{+Functor/+Arity, \ldots}
Informs the system that the clauses of the specified predicate(s) might
not be together in the source file. See also style_check/1.
\predicate{index}{1}{+Head}
Index the clauses of the predicate with the same name and arity as
\arg{Head} on the specified arguments. \arg{Head} is a term of which all
arguments are either `1' (denoting `index this argument') or `0'
(denoting `do not index this argument'). Indexing has no implications
for the semantics of a predicate, only on its performance. If indexing
is enabled on a predicate a special purpose algorithm is used to select
candidate clauses based on the actual arguments of the goal. This
algorithm checks whether indexed arguments might unify in the clause
head. Only atoms, integers and compound terms are considered. Compound
terms are indexed on the combination of their name and arity. Indexing
is very useful for predicates with many clauses representing facts.
Due to the representation technique used at most 4 arguments can be
indexed. All indexed arguments should be in the first 32 arguments of
the predicate. If more than 4 arguments are specified for indexing only
the first 4 will be accepted. Arguments above 32 are ignored for indexing.
By default all predicates with $<arity> \geq 1$ are indexed on their
first argument. It is possible to redefine indexing on predicates that
already have clauses attached to them. This will initiate a scan
through the predicates clause list to update the index summary
information stored with each clause.
If---for example---one wants to represents sub-types using a fact list
\mbox{`sub_type(Sub, Super)'} that should be used both to determine sub- and
super types one should declare {sub_type}/2 as follows:
\begin{code}
:- index(sub_type(1, 1)).
sub_type(horse, animal).
...
...
\end{code}
\end{description}
\section{Examining the program} \label{sec:examineprog}
\begin{description}
\predicate{current_atom}{1}{-Atom}
Successively unifies \arg{Atom} with all atoms known to the system.
Note that current_atom/1 always succeeds if \arg{Atom} is instantiated to
an atom.
\predicate{current_functor}{2}{?Name, ?Arity}
Successively unifies \arg{Name} with the name and \arg{Arity} with the
arity of functors known to the system.
\predicate{current_flag}{1}{-FlagKey}
Successively unifies \arg{FlagKey} with all keys used for flags (see
flag/3).
\predicate{current_key}{1}{-Key}
Successively unifies \arg{Key} with all keys used for records (see
recorda/3, etc.).
\predicate{current_predicate}{2}{?Name, ?Head}
Successively unifies \arg{Name} with the name of predicates currently
defined and \arg{Head} with the most general term built from \arg{Name}
and the arity of the predicate. This predicate succeeds for all
predicates defined in the specified module, imported to it, or in one of
the modules from which the predicate will be imported if it is called.
\predicate{current_predicate}{1}{:Name/Arity}
ISO compliant implementation of current_predicate/2. Unlike
current_predicate/2, the current implementation of current_predicate/1
does not consider predicates that can be autoloaded `current'.
\predicate{predicate_property}{2}{?Head, ?Property}
Succeeds if \arg{Head} refers to a predicate that has property
\arg{Property}. Can be used to test whether a predicate has a certain
property, obtain all properties known for \arg{Head}, find all
predicates having \arg{property} or even obtaining all information
available about the current program. \arg{Property} is one of:
\begin{description}
\termitem{interpreted}{}
Is true if the predicate is defined in Prolog. We return true on this
because, although the code is actually compiled, it is completely
transparent, just like interpreted code.
\termitem{built_in}{}
Is true if the predicate is locked as a built-in predicate. This
implies it cannot be redefined in its definition module and it can
normally not be seen in the tracer.
\termitem{foreign}{}
Is true if the predicate is defined in the C language.
\termitem{dynamic}{}
Is true if the predicate is declared dynamic using the dynamic/1
declaration.
\termitem{multifile}{}
Is true if the predicate is declared multifile using the multifile/1
declaration.
\termitem{undefined}{}
Is true if a procedure definition block for the predicate exists,
but there are no clauses in it and it is not declared dynamic. This is
true if the predicate occurs in the body of a loaded predicate, an
attempt to call it has been made via one of the meta-call predicates or
the predicate had a definition in the past. See the library package
\arg{check} for example usage.
\termitem{transparent}{}
Is true if the predicate is declared transparent using the
module_transparent/1 declaration.
\termitem{exported}{}
Is true if the predicate is in the public list of the context module.
\termitem{imported_from}{Module}
Is true if the predicate is imported into the context module from
module \arg{Module}.
\termitem{indexed}{Head}
Predicate is indexed (see index/1) according to \arg{Head}. \arg{Head}
is a term whose name and arity are identical to the predicate. The
arguments are unified with `1' for indexed arguments, `0' otherwise.
\termitem{file}{FileName}
Unify \arg{FileName} with the name of the source file in which the
predicate is defined. See also source_file/2.
\termitem{line_count}{LineNumber}
Unify \arg{LineNumber} with the line number of the first clause of the
predicate. Fails if the predicate is not associated with a file. See
also source_file/2.
\termitem{number_of_clauses}{ClauseCount}
Unify \arg{ClauseCount} to the number of clauses associated with the
predicate. Fails for foreign predicates.
\end{description}
\predicate{dwim_predicate}{2}{+Term, -Dwim}
`Do What I Mean' (`dwim') support predicate. \arg{Term} is a term,
which name and arity are used as a predicate specification. \arg{Dwim}
is instantiated with the most general term built from \arg{Name} and the
arity of a defined predicate that matches the predicate specified by
\arg{Term} in the `Do What I Mean' sense. See dwim_match/2 for `Do
What I Mean' string matching. Internal system predicates are
not generated, unless \exam{style_check(+dollar)} is active. Backtracking
provides all alternative matches.
\predicate{clause}{2}{?Head, ?Body}
Succeeds when \arg{Head} can be unified with a clause head and \arg{Body} with the corresponding clause body. Gives alternative clauses on
backtracking. For facts \arg{Body} is unified with the atom \arg{true}.
Normally clause/2 is used to find clause definitions for a predicate, but it
can also be used to find clause heads for some body template.
\predicate{clause}{3}{?Head, ?Body, ?Reference}
Equivalent to clause/2, but unifies \arg{Reference} with a unique reference to
the clause (see also assert/2, erase/1). If \arg{Reference} is instantiated
to a reference the clause's head and body will be unified with \arg{
Head} and \arg{Body}.
\predicate{nth_clause}{3}{?Pred, ?Index, ?Reference}
Provides access to the clauses of a predicate using their index number.
Counting starts at 1. If \arg{Reference} is specified it unifies \arg{Pred}
with the most general term with the same name/arity as the predicate and
\arg{Index} with the index-number of the clause. Otherwise the name and
arity of \arg{Pred} are used to determine the predicate. If \arg{Index}
is provided \arg{Reference} will be unified with the clause reference.
If \arg{Index} is unbound, backtracking will yield both the indices and
the references of all clauses of the predicate. The following example
finds the 2nd clause of member/2:
\begin{code}
?- nth_clause(member(_,_), 2, Ref), clause(Head, Body, Ref).
Ref = 160088
Head = system : member(G575, [G578|G579])
Body = member(G575, G579)
\end{code}
\predicate{clause_property}{2}{+ClauseRef, -Property}
Queries properties of a clause. \arg{ClauseRef} is a reference to a
clause as produced by clause/3, nth_clause/3 or prolog_frame_attribute/3.
\arg{Property} is one of the following:
\begin{description}
\termitem{file}{FileName}
Unify \arg{FileName} with the name of the source file in which the
clause is defined. Fails if the clause is not associated to a file.
\termitem{line_count}{LineNumber}
Unify \arg{LineNumber} with the line number of the clause. Fails if
the clause is not associated to a file.
\termitem{fact}{}
True if the clause has no body.
\termitem{erased}{}
True if the clause has been erased, but not yet reclaimed because
it is referenced.
\end{description}
\end{description}
\section{Input and output} \label{sec:IO}
SWI-Prolog provides two different packages for input and output. One
confirms to the Edinburgh standard. This package has a notion of
`current-input' and `current-output'. The reading and writing
predicates implicitly refer to these streams. In the second package,
streams are opened explicitly and the resulting handle is used as
an argument to the reading and writing predicate to specify the source
or destination. Both packages are fully integrated; the user may
switch freely between them.
\subsection{Input and output using implicit source and destination}
The package for implicit input and output destination is upwards
compatible to DEC-10 and C-Prolog. The reading and writing predicates
refer to resp. the current input- and output stream. Initially these
streams are connected to the terminal. The current output stream is
changed using tell/1 or append/1. The current input stream is changed
using see/1. The streams current value can be obtained using telling/1
for output- and seeing/1 for input streams. The table below shows the
valid stream specifications. The reserved names \const{user_input},
\const{user_output} and \const{user_error} are for neat integration with
the explicit streams.
\begin{center}
\begin{tabular}{|l|p{3in}|}
\hline
\const{user} & This reserved name refers to the terminal \\
\const{user_input} & Input from the terminal \\
\const{user_output} & Output to the terminal \\
\const{user_error} & Unix error stream (output only) \\
<Atom> & Name of a Unix file \\
\const{pipe(<Atom>)} & Name of a Unix command \\
\hline
\end{tabular}
\end{center}
Source and destination are either a file, one of the reserved words
above, or a term `pipe(\arg{Command})'. In the predicate descriptions
below we will call the source/destination argument `\arg{SrcDest}'.
Below are some examples of source/destination specifications.
\begin{center}\begin{tabular}{ll}
\exam{?- see(data).} & \% Start reading from file `data'. \\
\exam{?- tell(user_error).} & \% Start writing on the error stream. \\
\exam{?- tell(pipe(lpr)).} & \% Start writing to the printer.
\end{tabular}\end{center}
Another example of using the \functor{pipe}{1} construct is shown below.
Note that the \functor{pipe}{1} construct is not part of Prolog's
standard I/O repertoire.
\begin{code}
getwd(Wd) :-
seeing(Old), see(pipe(pwd)),
collect_wd(String),
seen, see(Old),
atom_codes(Wd, String).
collect_wd([C|R]) :-
get0(C), C \== -1, !,
collect_wd(R).
collect_wd([]).
\end{code}
\begin{description}
\predicate{see}{1}{+SrcDest}
Make \arg{SrcDest} the current input stream. If \arg{SrcDest} was
already opened for reading with see/1 and has not been closed since,
reading will be resumed. Otherwise \arg{SrcDest} will be opened and the
file pointer is positioned at the start of the file.
\predicate{tell}{1}{+SrcDest}
Make \arg{SrcDest} the current output stream. If \arg{SrcDest} was
already opened for writing with tell/1 or append/1 and has not been
closed since, writing will be resumed. Otherwise the file is created
or---when existing---truncated. See also append/1.
\predicate{append}{1}{+File}
Similar to tell/1, but positions the file pointer at the end of \arg{File}
rather than truncating an existing file. The pipe construct is not
accepted by this predicate.
\predicate{seeing}{1}{?SrcDest}
Unify the name of the current input stream with \arg{SrcDest}.
\predicate{telling}{1}{?SrcDest}
Unify the name of the current output stream with \arg{SrcDest}.
\predicate{seen}{0}{}
Close the current input stream. The new input stream becomes
\arg{user}.
\predicate{told}{0}{}
Close the current output stream. The new output stream becomes
\arg{user}.
\end{description}
\subsection{Explicit Input and Output Streams}
The predicates below are part of the Quintus compatible stream-based
I/O package. In this package streams are explicitly created using the
predicate open/3. The resulting stream identifier is then passed as a
parameter to the reading and writing predicates to specify the source
or destination of the data.
\begin{description}
\predicate{open}{4}{+SrcDest, +Mode, -Stream, +Options}
ISO compliant predicate to open a stream. \arg{SrcDes} is either an
atom, specifying a Unix file, or a term `\exam{pipe(\arg{Command})}',
just like see/1 and tell/1. \arg{Mode} is one of \const{read},
\const{write}, \const{append} or \const{update}. Mode \const{append}
opens the file for writing, positioning the file-pointer at the end.
Mode \const{update} opens the file for writing, positioning the
file-pointer at the beginning of the file without truncating the file.
See also stream_position/3. \arg{Stream} is either a variable, in which
case it is bound to an integer identifying the stream, or an atom, in
which case this atom will be the stream identifier. The \arg{Options}
list can contain the following options:
\begin{description}
\termitem{type}{Type}
Using type \const{text} (default), Prolog will write a text-file in
an operating-system compatible way. Using type \const{binary} the
bytes will be read or written without any translation. Note there is no
difference between the two on Unix systems.
\termitem{alias}{Atom}
Gives the stream a name. Below is an example. Be careful with this
option as stream-names are global. See also set_stream/2.
\begin{code}
?- open(data, read, Fd, [alias(input)]).
...,
read(input, Term),
...
\end{code}
\termitem{eof_action}{Action}
Defines what happens if the end of the input stream is reached. Action
\const{eof_code} makes get0/1 and friends return -1 and read/1 and friends
return the atom \const{end_of_file}. Repetitive reading keeps yielding the
same result. Action \const{error} is like \const{eof_code}, but repetitive
reading will raise an error. With action \const{reset}, Prolog will
examine the file again and return more data if the file has grown.
\termitem{buffer}{Buffering}
Defines output buffering. The atom \const{full} (default) defines full
buffering, \const{line} buffering by line, and \const{false} implies the
stream is fully unbuffered. Smaller buffering is useful if another
process or the user is waiting for the output as it is being produced.
See also flush_output/[0,1]. This option is not an ISO option.
\termitem{close_on_abort}{Bool}
If \const{true} (default), the stream is closed on an abort (see
abort/0). If \const{false}, the stream is not closed. If it is an output
stream, it will be flushed however. Useful for logfiles and if the
stream is associated to a process (using the \functor{pipe}{1}
construct).
\termitem{lock}{LockingMode}
Try to obtain a lock on the open file. Default is \const{none}, which
does not lock the file. The value \const{read} or \const{shared} means
other processes may read the file, but not write it. The value
\const{write} or \const{exclusive} means no other process may read
or write the file.
Locks are acquired through the POSIX function fcntl() using the command
\const{F_SETLKW}, which makes a blocked call wait for the lock to be
released. Please note that fcntl() locks are {\em advisory} and
therefore only other applications using the same advisory locks
honour your lock. As there are many issues around locking in Unix,
expecially related to NFS (network file system), please study the
fcntl() manual page before trusting your locks!
The \const{lock} option is a SWI-Prolog extension.
\end{description}
The option \const{reposition} is not supported in SWI-Prolog. All streams
connected to a file may be repositioned.
\predicate{open}{3}{+SrcDest, +Mode, ?Stream}
Equivalent to open/4 with an empty option-list.
\predicate{open_null_stream}{1}{?Stream}
Open a stream that produces no output. All counting functions are
enabled on such a stream. An attempt to read from a null-stream will
immediately signal end-of-file. Similar to Unix \file{/dev/null}.
\arg{Stream} can be an atom, giving the null-stream an alias name.
\predicate{close}{1}{+Stream}
Close the specified stream. If \arg{Stream} is not open an error
message is displayed. If the closed stream is the current input or
output stream the terminal is made the current input or output.
\predicate{close}{2}{+Stream, +Options}
Provides \term{close}{Stream, [force(true)]} as the only option. Called
this way, any resource error (such as write-errors while flushing the
output buffer) are ignored.
\predicate{stream_property}{2}{?Stream, ?StreamProperty}
ISO compatible predicate for querying status of open I/O streams.
\arg{StreamProperty} is one of:
\begin{description}
\termitem{file_name}{Atom}
If \arg{Stream} is associated to a file, unify \arg{Atom} to the
name of this file.
\termitem{mode}{IOMode}
Unify \arg{IOMode} to the mode given to open/4 for opening the stream.
Values are: \const{read}, \const{write}, \const{append} and the
SWI-Prolog extension \const{update}.
\termitem{input}{}
True if \arg{Stream} has mode \const{read}.
\termitem{output}{}
True if \arg{Stream} has mode \const{write}, \const{append} or
\const{update}.
\termitem{alias}{Atom}
If \arg{Atom} is bound, test of the stream has the specified alias.
Otherwise unify \arg{Atom} with the first alias of the stream.%
\bug{Backtracking does not give other aliases.}
\termitem{position}{Term}
Unify \arg{Term} with the current stream-position. A stream-position
is a term of format \term{\$stream_position}{CharIndex, LineNo,
LinePos}. See also term_position/3.
\termitem{end_of_stream}{E}
If \arg{Stream} is an input stream, unify \arg{E} with one of the
atoms \const{not}, \const{at} or \const{past}. See also
at_end_of_stream/[0,1].
\termitem{eof_action}{A}
Unify \arg{A} with one of \const{eof_code}, \const{reset} or
\const{error}. See open/4 for details.
\termitem{reposition}{Bool}
Unify \arg{Bool} with \arg{true} if the position of the stream can
be set (see seek/4). It is assumed the position can be set if the
stream has a \jargon{seek-function} and is not based on a POSIX
file-descriptor that is not associated to a regular file.
\termitem{type}{T}
Unify \arg{Bool} with \const{text} or \const{binary}.
\termitem{file_no}{Integer}
If the stream is associated with a POSIX file-descriptor, unify
\arg{Integer} with the descriptor number. SWI-Prolog extension used
primarily for integration with foreign code. See also Sfileno() from
\file{SWI-Stream.h}.
\termitem{buffer}{Buffering}
SWI-Prolog extension to query the buffering mode of this stream.
\arg{Buffering} is one of \const{full}, \const{line} or \const{false}.
See also open/4.
\end{description}
\predicate{current_stream}{3}{?Object, ?Mode, ?Stream}
The predicate current_stream/3 is used to access the status of a
stream as well as to generate all open streams. \arg{Object} is the
name of the file opened if the stream refers to an open file, an
integer file-descriptor if the stream encapsulates an operating-system
stream or the atom \const{[]} if the stream refers to some other object.
\arg{Mode} is one of \const{read} or \const{write}.
\predicate{set_stream_position}{2}{+Stream, +Pos}
Set the current position of \arg{Stream} to \arg{Pos}. \arg{Pos} is
a term as returned by stream_property/2 using the \term{position}{Pos}
property. See also seek/4.
\predicate{seek}{4}{+Stream, +Offset, +Method, -NewLocation}
Reposition the current point of the given \arg{Stream}. \arg{Method}
is one of \const{bof}, \arg{current} or \arg{eof}, indicating
positioning relative to the start, current point or end of the
underlying object. \arg{NewLocation} is unified with the new offset,
relative to the start of the stream.
If the seek modifies the current location, the line number and character
position in the line are set to 0.
If the stream cannot be repostioned, a \const{reposition} error is
raised. The predicate seek/4 is compatible to Quintus Prolog, though the
error conditions and signalling is ISO compliant. See also
stream_position/3.
\predicate{set_stream}{2}{+Stream, +Attribute}
Modify an attribute of an existing stream. \arg{Attribute} specifies
the stream property to set. See also stream_property/2 and open/4.
\begin{description}
\termitem{alias}{AliasName}
Set the alias of an already created stream. If \arg{AliasName} is the
name of one of the standard streams is used, this stream is rebound.
Thus, \exam{set_stream(S, current_input)} is the same as set_input/1 and
by setting the alias of a stream to \const{user_input}, etc.\ all user
terminal input is read from this stream. See also interactor/0.
\termitem{buffer}{Buffering}
Set the buffering mode of an already created stream. Buffering is one
of \const{full}, \const{line} or \const{false}.
\termitem{eof_action}{Action}
Set end-of-file handling to one of \const{eof_code}, \const{reset} or
\const{error}.
\termitem{close_on_abort}{Bool}
Determine whether or not the stream is closed by abort/0. By default
streams are closed.
\end{description}
\end{description}
\subsection{Switching Between Implicit and Explicit I/O}
The predicates below can be used for switching between the implicit-
and the explicit stream based I/O predicates.
\begin{description}
\predicate{set_input}{1}{+Stream}
Set the current input stream to become \arg{Stream}. Thus, open(file,
read, Stream), set_input(Stream) is equivalent to see(file).
\predicate{set_output}{1}{+Stream}
Set the current output stream to become \arg{Stream}.
\predicate{current_input}{1}{-Stream}
Get the current input stream. Useful to get access to the status
predicates associated with streams.
\predicate{current_output}{1}{-Stream}
Get the current output stream.
\end{description}
\section{Status of streams} \label{sec:streamstat}
\begin{description}
\predicate{wait_for_input}{3}{+ListOfStreams, -ReadyList, +TimeOut}
Wait for input on one of the streams in \arg{ListOfStreams} and return a
list of streams on which input is available in \arg{ReadyList}.
wait_for_input/3 waits for at most \arg{TimeOut} seconds. \arg{Timeout}
may be specified as a floating point number to specify fractions of a
second. If \arg{Timeout} equals 0, wait_for_input/3 waits indefinitely.
This predicate can be used to implement timeout while reading and to
handle input from multiple sources. The following example will wait for
input from the user and an explicitly opened second terminal. On return,
\arg{Inputs} may hold \const{user} or \arg{P4} or both.
\begin{code}
?- open('/dev/ttyp4', read, P4),
wait_for_input([user, P4], Inputs, 0).
\end{code}
This predicate relies on the select() call on most operating systems. On
Unix this call is implemented for any stream referring to a file-handle,
which implies all OS-based streams: sockets, terminals, pipes, etc. On
non-Unix systems select() is generally only implemented for socket-based
streams. See also \pllib{socket} from the \const{clib} package.
\predicate{character_count}{2}{+Stream, -Count}
Unify \arg{Count} with the current character index. For input streams
this is the number of characters read since the open, for output
streams this is the number of characters written. Counting starts at 0.
\predicate{line_count}{2}{+Stream, -Count}
Unify \arg{Count} with the number of lines read or written. Counting
starts at 1.
\predicate{line_position}{2}{+Stream, -Count}
Unify \arg{Count} with the position on the current line. Note that this
assumes the position is 0 after the open. Tabs are assumed to be
defined on each 8-th character and backspaces are assumed to reduce the
count by one, provided it is positive.
\predicate{fileerrors}{2}{-Old, +New}
Define error behaviour on errors when opening a file for reading or
writing. Valid values are the atoms \const{on} (default) and \const{off}.
First \arg{Old} is unified with the current value. Then the new value is
set to \arg{New}.%
\footnote{Note that Edinburgh Prolog defines fileerrors/0 and
nofileerrors/0. As this does not allow you to switch back
to the old mode I think this definition is better.}
\end{description}
\section{Primitive character I/O} \label{sec:chario}
See \secref{chars} for an overview of supported character
representations.
\begin{description}
\predicate{nl}{0}{}
Write a newline character to the current output stream. On Unix systems
nl/0 is equivalent to \exam{put(10)}.
\predicate{nl}{1}{+Stream}
Write a newline to \arg{Stream}.
\predicate{put}{1}{+Char}
Write \arg{Char} to the current output stream, \arg{Char} is either an
integer-expression evaluating to an ASCII value
($0 \leq \arg{Char} \leq 255$) or an atom of one character.
\predicate{put}{2}{+Stream, +Char}
Write \arg{Char} to \arg{Stream}.
\predicate{put_byte}{1}{+Byte}
Alias for put/1.
\predicate{put_byte}{2}{+Stream, +Byte}
Alias for put/2
\predicate{put_char}{1}{+Char}
Alias for put_char/1.
\predicate{put}{2}{+Stream, +Char}
Alias for put/2
\predicate{put_code}{1}{+Code}
Alias for put/1.
\predicate{put_code}{2}{+Stream, +Code}
Alias for put/2
\predicate{tab}{1}{+Amount}
Writes \arg{Amount} spaces on the current output stream. \arg{Amount}
should be an expression that evaluates to a positive integer (see
\secref{arith}).
\predicate{tab}{2}{+Stream, +Amount}
Writes \arg{Amount} spaces to \arg{Stream}.
\predicate{flush_output}{0}{}
Flush pending output on current output stream. flush_output/0 is
automatically generated by read/1 and derivatives if the current input
stream is \const{user} and the cursor is not at the left margin.
\predicate{flush_output}{1}{+Stream}
Flush output on the specified stream. The stream must be open for
writing.
\predicate{ttyflush}{0}{}
Flush pending output on stream \arg{user}. See also flush_output/[0,1].
\predicate{get_byte}{1}{-Byte}
Read the current input stream and unify the next byte with \arg{Byte}
(an integer between 0 and 255. \arg{Byte} is unified with -1 on end of
file.
\predicate{get_byte}{2}{+Stream, -Byte}
Read the next byte from \arg{Stream}.
\predicate{get_code}{1}{-Code}
Read the current input stream and unify \arg{Code} with the character
code of the next character. \arg{Char} is unified with -1 on end of file.
See also get_char/1.
\predicate{get_code}{2}{+Stream, -Code}
Read the next character-code from \arg{Stream}.
\predicate{get_char}{1}{-Char}
Read the current input stream and unify \arg{Char} with the next
character as a one-character-atom. See also atom_chars/2.
On end-of-file, \arg{Char} is unified to the atom \const{end_of_file}.
\predicate{get_char}{2}{+Stream, -Char}
Unify \arg{Char} with the next character from \arg{Stream} as a
one-character-atom. See also get_char/2, get_byte/2 and get_code/2.
\predicate{get0}{1}{-Char}
Edinburgh version of the ISO get_byte/1 predicate.
\predicate{get0}{2}{+Stream, -Char}
Edinburgh version of the ISO get_byte/2 predicate.
\predicate{get}{1}{-Char}
Read the current input stream and unify the next non-blank character
with \arg{Char}. \arg{Char} is unified with -1 on end of file.
\predicate{get}{2}{+Stream, -Char}
Read the next non-blank character from \arg{Stream}.
\predicate{peek_byte}{1}{-Byte}
Reads the next input byte like get_byte/1, but does not remove it
from the input stream.
\predicate{peek_byte}{2}{+Stream, -Byte} Reads the next input byte
like get_byte/2, but does not remove it from the stream.
\predicate{peek_code}{1}{-Code}
Reads the next input code like get_code/1, but does not remove it
from the input stream.
\predicate{peek_code}{2}{+Stream, -Code} Reads the next input code
like get_code/2, but does not remove it from the stream.
\predicate{peek_char}{1}{-Char}
Reads the next input character like get_char/1, but does not remove it
from the input stream.
\predicate{peek_char}{2}{+Stream, -Char} Reads the next input
character like get_char/2, but does not remove it from the stream.
\predicate{skip}{1}{+Char}
Read the input until \arg{Char} or the end of the file is encountered.
A subsequent call to get0/1 will read the first character after \arg{Char}.
\predicate{skip}{2}{+Stream, +Char}
Skip input (as skip/1) on \arg{Stream}.
\predicate{get_single_char}{1}{-Char}
Get a single character from input stream `user' (regardless of the
current input stream). Unlike get0/1 this predicate does not wait for a
return. The character is not echoed to the user's terminal. This
predicate is meant for keyboard menu selection etc. If SWI-Prolog was
started with the \cmdlineoption{-tty} option this predicate reads an entire
line of input and returns the first non-blank character on this line, or
the ASCII code of the newline (10) if the entire line consisted of blank
characters.
\predicate{at_end_of_stream}{0}{}
Succeeds after the last character of the current input stream has
been read. Also succeeds if there is no valid current input stream.
\predicate{at_end_of_stream}{1}{+Stream}
Succeeds after the last character of the named stream is read, or
\arg{Stream} is not a valid input stream. The end-of-stream test
is only available on buffered input stream (unbuffered input streams
are rarely used, see open/4).
\predicate{copy_stream_data}{3}{+StreamIn, +StreamOut, +Len}
Copy \arg{Len} bytes from stream \arg{StreamIn} to \arg{StreamOut}.
\predicate{copy_stream_data}{2}{+StreamIn, +StreamOut}
Copy data all (remaining) data from stream \arg{StreamIn} to
\arg{StreamOut}.
\end{description}
\section{Term reading and writing} \label{sec:termrw}
This section describes the basic term reading and writing predicates.
The predicates term_to_atom/2, atom_to_term/3 and sformat/3 provide
means for translating atoms and strings to terms. The predicates
format/[1,2] and writef/2 provide formatted output.
There are two ways to manipulate the output format. The predicate
print/[1,2] may be programmed using portray/1. The format of floating
point numbers may be manipulated using the prolog_flag (see
current_prolog_flag/2) \const{float_format}.
Reading is sensitive to the prolog_flag \const{character_escapes}, which
controls the interpretation of the \chr{\} character in quoted
atoms and strings.
\begin{description}
\predicate{write_term}{2}{+Term, +Options}
The predicate write_term/2 is the generic form of all Prolog term-write
predicates. Valid options are:
\begin{description}
\termitem{quoted}{\const{true} or \const{false}}
If \const{true}, atoms and functors that needs quotes will be quoted.
The default is \const{false}.
\termitem{character_escapes}{\const{true} or \const{false}}
If \const{true}, and \term{quoted}{true} is active, special characters
in quoted atoms and strings are emitted as ISO escape-sequences.
Default is taken from the reference module (see below).
\termitem{ignore_ops}{\const{true} or \const{false}}
If \const{true}, the generic term-representation (<functor>(<args>
\ldots)) will be used for all terms, Otherwise (default), operators,
list-notation and \verb${}$/1 will be written using their special
syntax.
\termitem{module}{Module}
Define the reference module (default \const{user}). This defines
the default value for the \const{character_escapes} option as well
as the operator definitions to use. See also op/3.
\termitem{numbervars}{\const{true} or \const{false}}
If \const{true}, terms of the format \verb|$VAR(N)|, where <N> is a
positive integer, will be written as a variable name. The default is
\const{false}.
\termitem{portray}{\const{true} or \const{false}}
If \const{true}, the hook portray/1 is called before printing a term
that is not a variable. If portray/1 succeeds, the term is considered
printed. See also print/1. The default is \const{false}. This option
is an extension to the ISO write_term options.
\termitem{max_depth}{Integer}
If the term is nested deeper than \arg{Integer}, print the remainder
as eclipse (\ldots). A 0 (zero) value (default) imposes no depth limit.
This option also delimits the number of printed for a list. Example:
\begin{code}
?- write_term(a(s(s(s(s(0)))), [a,b,c,d,e,f]), [max_depth(3)]).
a(s(s(...)), [a, b|...])
Yes
\end{code}
Used by the toplevel and debugger to limit screen output. See also
the prolog-flags \const{toplevel_print_options} and
\const{debugger_print_options}.
\end{description}
\predicate{write_term}{3}{+Stream, +Term, +Options}
As write_term/2, but output is sent to \arg{Stream} rather than the
current output.
\predicate{write_canonical}{1}{+Term}
Write \arg{Term} on the current output stream using standard
parenthesised prefix notation (i.e., ignoring operator declarations).
Atoms that need quotes are quoted. Terms written with this predicate
can always be read back, regardless of current operator declarations.
Equivalent to write_term/2 using the options \const{ignore_ops} and
\const{quoted}.
\predicate{write_canonical}{2}{+Stream, +Term}
Write \arg{Term} in canonical form on \arg{Stream}.
\predicate{write}{1}{+Term}
Write \arg{Term} to the current output, using brackets and operators where
appropriate. See current_prolog_flag/2 for controlling floating point output format.
\predicate{write}{2}{+Stream, +Term}
Write \arg{Term} to \arg{Stream}.
\predicate{writeq}{1}{+Term}
Write \arg{Term} to the current output, using brackets and operators where
appropriate. Atoms that need quotes are quoted. Terms written with this
predicate can be read back with read/1 provided the currently active
operator declarations are identical.
\predicate{writeq}{2}{+Stream, +Term}
Write \arg{Term} to \arg{Stream}, inserting quotes.
\predicate{print}{1}{+Term}
Prints \arg{Term} on the current output stream similar to write/1,
but for each (sub)term of \arg{Term} first the dynamic predicate
portray/1 is called. If this predicate succeeds \arg{print} assumes the
(sub)term has been written. This allows for user defined term writing.
\predicate{print}{2}{+Stream, +Term}
Print \arg{Term} to \arg{Stream}.
\predicate{portray}{1}{+Term}
A dynamic predicate, which can be defined by the user to change the
behaviour of print/1 on (sub)terms. For each subterm encountered that
is not a variable print/1 first calls portray/1 using the term as
argument. For lists only the list as a whole is given to portray/1. If
portray succeeds print/1 assumes the term has been written.
\predicate{read}{1}{-Term}
Read the next Prolog term from the current input stream and unify it
with \arg{Term}. On a syntax error read/1 displays an error message,
attempts to skip the erroneous term and fails. On reaching end-of-file
\arg{Term} is unified with the atom \const{end_of_file}.
\predicate{read}{2}{+Stream, -Term}
Read \arg{Term} from \arg{Stream}.
\predicate{read_clause}{1}{-Term}
Equivalent to read/1, but warns the user for variables only occurring
once in a term (singleton variables) which do not start with an
underscore if \exam{style_check(singleton)} is active (default).
Used to read Prolog source files (see consult/1). New code should
use read_term/2 with the option \exam{singletons(warning)}.
\predicate{read_clause}{2}{+Stream, -Term}
Read a clause from \arg{Stream}. See read_clause/1.
\predicate{read_term}{2}{-Term, +Options}
Read a term from the current input stream and unify the term with
\arg{Term}. The reading is controlled by options from the list of
\arg{Options}. If this list is empty, the behaviour is the same as for
read/1. The options are upward compatible to Quintus Prolog. The
argument order is according to the ISO standard. Syntax-errors are
always reported using exception-handling (see catch/3). Options:
\begin{description}
\termitem{variables}{Vars}
Unify \arg{Vars} with a list of variables in the term. The variables
appear in the order they have been read. See also free_variables/2.
(ISO).
\termitem{variable_names}{Vars}
Unify \arg{Vars} with a list of `\arg{Name} = \arg{Var}', where \arg{Name} is an atom describing the variable name and \arg{Var} is a
variable that shares with the corresponding variable in \arg{Term}.
(ISO).
\termitem{singletons}{Vars}
As \const{variable_names}, but only reports the variables occurring only
once in the \arg{Term} read. Variables starting with an underscore
(`\chr{_}') are not included in this list. (ISO).
\termitem{syntex_errors}{Atom}
If \const{error} (default), throw and exception on a syntax error. Other
values are \const{fail}, which causes a message to be printed using
print_message/2, after which the predicate fails, \const{quiet} which
causes the predicate to fail silently and \const{dec10} which causes
syntax errors to be printed, after which read_term/[2,3] continues
reading the next term. Using \const{dec10}, read_term/[2,3] never fails.
(Quintus, SICStus).
\termitem{module}{Module}
Specify \arg{Module} for operators, \const{character_escapes} flag
and \const{double_quotes} flag. The value of the latter two is overruled
if the corresponding read_term/3 option is provided. If no module is
specified, the current `source-module' is used. (SWI-Prolog).
\termitem{character_escapes}{Bool}
Defines how to read \verb$\$ escape-sequences in quoted atoms.
See the prolog-flags \const{character_escapes}, current_prolog_flag/2.
(SWI-Prolog).
\termitem{double_quotes}{Bool}
Defines how to read "\ldots" strings. See the prolog-flags
\const{double_quotes}, current_prolog_flag/2. (SWI-Prolog).
\termitem{term_position}{Pos}
Unifies \arg{Pos} with the starting position of the term read. \arg{Pos}
if of the same format as use by stream_position/3.
\termitem{subterm_positions}{TermPos}
Describes the detailed layout of the term. The formats for the various
types of terms if given below. All positions are character positions. If
the input is related to a normal stream, these positions are relative to
the start of the input, when reading from the terminal, they are
relative to the start of the term.
\begin{description}
\definition{\arg{From}-\arg{To}}
Used for primitive types (atoms, numbers, variables).
\termitem{string_position}{\arg{From}, \arg{To}}
Used to indicate the position of a string enclosed in double
quotes (\chr{"}).
\termitem{brace_term_position}{\arg{From}, \arg{To}, \arg{Arg}}
Term of the form \exam{\{\ldots \}}, as used in DCG rules. \arg{Arg}
describes the argument.
\termitem{list_position}{\arg{From}, \arg{To},
\arg{Elms}, \arg{Tail}}
A list. \arg{Elms} describes the positions of the elements. If the list
specifies the tail as \mbox{\chr{|}<TailTerm>}, \arg{Tail} is unified
with the term-position of the tail, otherwise with the atom \const{none}.
\termitem{term_position}{\arg{From}, \arg{To},
\arg{FFrom}, \arg{FTo}, \arg{SubPos}}
Used for a compound term not matching one of the above. \arg{FFrom}
and \arg{FTo} describe the position of the functor. \arg{SubPos}
is a list, each element of which describes the term-position of the
corresponding subterm.
\end{description}
\end{description}
\predicate{read_term}{3}{+Stream, -Term, +Options}
Read term with options from \arg{Stream}. See read_term/2.
\predicate{read_history}{6}{+Show, +Help, +Special, +Prompt, -Term, -Bindings}
Similar to read_term/2 using the option \const{variable_names}, but
allows for history substitutions. read_history/6 is used by the top
level to read the user's actions. \arg{Show} is the command the user
should type to show the saved events. \arg{Help} is the command to get
an overview of the capabilities. \arg{Special} is a list of commands
that are not saved in the history. \arg{Prompt} is the first prompt
given. Continuation prompts for more lines are determined by prompt/2. A
\const{\%w} in the prompt is substituted by the event number. See
\secref{history} for available substitutions.
SWI-Prolog calls read_history/6 as follows:
\begin{code}
read_history(h, '!h', [trace], '%w ?- ', Goal, Bindings)
\end{code}
\predicate{prompt}{2}{-Old, +New}
Set prompt associated with read/1 and its derivatives. \arg{Old}
is first unified with the current prompt. On success the prompt will be
set to \arg{New} if this is an atom. Otherwise an error message is
displayed. A prompt is printed if one of the read predicates is
called and the cursor is at the left margin. It is also printed
whenever a newline is given and the term has not been terminated.
Prompts are only printed when the current input stream is \arg{user}.
\predicate{prompt1}{1}{+Prompt}
Sets the prompt for the next line to be read. Continuation lines will
be read using the prompt defined by prompt/2.
\end{description}
\section{Analysing and Constructing Terms} \label{sec:manipterm}
\begin{description}
\predicate{functor}{3}{?Term, ?Functor, ?Arity}
Succeeds if \arg{Term} is a term with functor \arg{Functor} and arity
\arg{Arity}. If \arg{Term} is a variable it is unified with a new term
holding only variables. functor/3 silently fails on instantiation
faults%
\footnote{In version 1.2 instantiation faults led to error messages.
The new version can be used to do type testing without the
need to catch illegal instantiations first.}
If \arg{Term} is an atom or number, \arg{Functor} will be unified with
\arg{Term} and arity will be unified with the integer 0 (zero).
\predicate{arg}{3}{?Arg, ?Term, ?Value}
\arg{Term} should be instantiated to a term, \arg{Arg} to an integer
between 1 and the arity of \arg{Term}. \arg{Value} is unified with the
\arg{Arg}-th argument of \arg{Term}. \arg{Arg} may also be unbound.
In this case \arg{Value} will be unified with the successive arguments
of the term. On successful unification, \arg{Arg} is unified with the
argument number. Backtracking yields alternative solutions.%
\footnote{The instantiation pattern (-, +, ?) is an extension to
`standard' Prolog.}
The predicate arg/3 fails silently if $\arg{Arg} = 0$ or
$\arg{Arg} > \mbox{\em arity}$ and raises the exception
\errorterm{domain_error}{not_less_then_zero, \arg{Arg}} if $\arg{Arg} <
0$.
\predicate{setarg}{3}{+Arg, +Term, +Value}
Extra-logical predicate. Assigns the \arg{Arg}-th argument of the
compound term \arg{Term} with the given \arg{Value}. The assignment
is undone if backtracking brings the state back into a position before
the setarg/3 call.
This predicate may be used for destructive assignment to terms, using
them as and extra-logical storage bin.
\infixop{=..}{?Term}{?List}
\arg{List} is a list which head is the functor of \arg{Term} and the
remaining arguments are the arguments of the term. Each of the
arguments may be a variable, but not both. This predicate is called
`Univ'. Examples:
\begin{code}
?- foo(hello, X) =.. List.
List = [foo, hello, X]
?- Term =.. [baz, foo(1)]
Term = baz(foo(1))
\end{code}
\predicate{numbervars}{4}{+Term, +Functor, +Start, -End}
Unify the free variables of \arg{Term} with a term constructed from the
atom \arg{Functor} with one argument. The argument is the number of the
variable. Counting starts at \arg{Start}. \arg{End} is unified with
the number that should be given to the next variable. Example:
\begin{code}
?- numbervars(foo(A, B, A), this_is_a_variable, 0, End).
A = this_is_a_variable(0)
B = this_is_a_variable(1)
End = 2
\end{code}
In Edinburgh Prolog the second argument is missing. It is fixed to be
\const{\$VAR}.
\predicate{free_variables}{2}{+Term, -List}
Unify \arg{List} with a list of variables, each sharing with a unique variable
of \arg{Term}. For example:
\begin{code}
?- free_variables(a(X, b(Y, X), Z), L).
L = [G367, G366, G371]
X = G367
Y = G366
Z = G371
\end{code}
\predicate{copy_term}{2}{+In, -Out}
Make a copy of term \arg{In} and unify the result with \arg{Out}.
Ground parts of \arg{In} are shared by \arg{Out}. Provided \arg{In} and
\arg{Out} have no sharing variables before this call they will have no
sharing variables afterwards. copy_term/2 is semantically equivalent
to:
\begin{code}
copy_term(In, Out) :-
recorda(copy_key, In, Ref),
recorded(copy_key, Out, Ref),
erase(Ref).
\end{code}
\end{description}
\section{Analysing and Constructing Atoms} \label{sec:manipatom}
These predicates convert between Prolog constants and lists of ASCII
values. The predicates atom_codes/2, number_codes/2 and name/2 behave
the same when converting from a constant to a list of ASCII values. When
converting the other way around, atom_codes/2 will generate an atom,
number_codes/2 will generate a number or exception and name/2 will
return a number if possible and an atom otherwise.
The ISO standard defines atom_chars/2 to describe the `broken-up'
atom as a list of one-character atoms instead of a list of codes. Upto
version 3.2.x, SWI-Prolog's atom_chars/2 behaved, compatible to
Quintus and SICStus Prolog, like atom_codes. As of 3.3.x SWI-Prolog
atom_codes/2 and atom_chars/2 are compliant to the ISO standard.
To ease the pain of all variations in the Prolog community, all
SWI-Prolog predicates behave as flexible as possible. This implies
the `list-side' accepts either a code-list or a char-list and the
`atom-side' accept all atomic types (atom, number and string).
\begin{description}
\predicate{atom_codes}{2}{?Atom, ?String}
Convert between an atom and a list of ASCII values. If \arg{Atom} is
instantiated, if will be translated into a list of ASCII values and the
result is unified with \arg{String}. If \arg{Atom} is unbound and \arg{String} is a list of ASCII values, it will \arg{Atom} will be unified
with an atom constructed from this list.
\predicate{atom_chars}{2}{?Atom, ?CharList}
As atom_codes/2, but \arg{CharList} is a list of one-character atoms
rather than a list of ASCII values%
\footnote{Upto version 3.2.x, atom_chars/2 behaved as the
current atom_codes/2. The current definition is
compliant with the ISO standard}.
\begin{code}
?- atom_chars(hello, X).
X = [h, e, l, l, o]
\end{code}
\predicate{char_code}{2}{?Atom, ?ASCII}
Convert between character and ASCII value for a single character.%
\footnote{This is also called atom_char/2 in older versions of
SWI-Prolog as well as some other Prolog
implementations. atom_char/2 is available from
the library \file{backcomp.pl}}
\predicate{number_chars}{2}{?Number, ?CharList}
Similar to atom_chars/2, but converts between a number and its
representation as a list of one-character atoms. Fails with a
\except{representation_error} if \arg{Number} is unbound and
\arg{CharList} does not describe a number.
\predicate{number_codes}{2}{?Number, ?CodeList}
As number_chars/2, but converts to a list of character codes (normally
ASCII values) rather than one-character atoms. In the mode -, +, both
predicates behave identically to improve handling of non-ISO source.
\predicate{name}{2}{?AtomOrInt, ?String}
\arg{String} is a list of ASCII values describing \arg{Atom}. Each of the
arguments may be a variable, but not both. When \arg{String} is bound to an
ASCII value list describing an integer and \arg{Atom} is a variable \arg{Atom}
will be unified with the integer value described by \arg{String} (e.g.
`\exam{name(N, "300"), 400 is N + 100}' succeeds).
\predicate{int_to_atom}{3}{+Int, +Base, -Atom}
Convert \arg{Int} to an {\sc ascii} representation using base \arg{Base}
and unify the result with \arg{Atom}. If $\arg{Base} \not= 10$ the base
will be prepended to \arg{Atom}. $\arg{Base} = 0$ will try to interpret
\arg{Int} as an ASCII value and return \const{0'}<c>. Otherwise $2 \leq
\arg{Base} \leq 36$. Some examples are given below.
\begin{center}\begin{tabular}{lcl}
int_to_atom(45, 2, A) & $\longrightarrow$ & $A = 2'101101$ \\
int_to_atom(97, 0, A) & $\longrightarrow$ & $A = 0'a$ \\
int_to_atom(56, 10, A) & $\longrightarrow$ & $A = 56$ \\
\end{tabular}\end{center}
\predicate{int_to_atom}{2}{+Int, -Atom}
Equivalent to \exam{int_to_atom(Int, 10, Atom)}.
\predicate{term_to_atom}{2}{?Term, ?Atom}
Succeeds if \arg{Atom} describes a term that unifies with \arg{Term}. When
\arg{Atom} is instantiated \arg{Atom} is converted and then unified with
\arg{Term}. If \arg{Atom} has no valid syntax, a \except{syntax_error}
exception is raised. Otherwise \arg{Term} is ``written'' on \arg{Atom}
using write/1.
\predicate{atom_to_term}{3}{+Atom, -Term, -Bindings}
Use \arg{Atom} as input to read_term/2 using the option
\const{variable_names} and return the read term in \arg{Term} and the
variable bindings in \arg{Bindings}. \arg{Bindings} is a list of
$\arg{Name} = \arg{Var}$ couples, thus providing access to the actual
variable names. See also read_term/2. If \arg{Atom} has no valid syntax,
a \except{syntax_error} exception is raised.
\predicate{atom_concat}{3}{?Atom1, ?Atom2, ?Atom3}
\arg{Atom3} forms the concatenation of \arg{Atom1} and \arg{Atom2}. At
least two of the arguments must be instantiated to atoms, integers or
floating point numbers. For ISO compliance, the instantiation-pattern
\mbox{-, -, +} is allowed too, non-deterministically splitting the 3-th
argument into two parts (as append/3 does for lists). See also
string_concat/3.
\predicate{concat_atom}{2}{+List, -Atom}
\arg{List} is a list of atoms, integers or floating point numbers. Succeeds
if \arg{Atom} can be unified with the concatenated elements of \arg{List}. If
\arg{List} has exactly 2 elements it is equivalent to atom_concat/3,
allowing for variables in the list.
\predicate{concat_atom}{3}{?List, +Separator, ?Atom}
Creates an atom just like concat_atom/2, but inserts \arg{Separator}
between each pair of atoms. For example:
\begin{code}
?- concat_atom([gnu, gnat], ', ', A).
A = 'gnu, gnat'
\end{code}
This predicate can also be used to split atoms by instantiating
\arg{Separator} and \arg{Atom}:
\begin{code}
?- concat_atom(L, -, 'gnu-gnat').
L = [gnu, gnat]
\end{code}
\predicate{atom_length}{2}{+Atom, -Length}
Succeeds if \arg{Atom} is an atom of \arg{Length} characters long. This
predicate also works for strings (see \secref{string}). If the prolog
flag \const{iso} is \emph{not} set, it also accepts integers and floats,
expressing the number of characters output when given to write/1 as well
as code-lists and character-lists, expressing the length of the list.%
\bug{Note that \const{[]} is both an atom an empty code/character
list. The predicate atom_length/2 returns 2 for this atom.}
\predicate{atom_prefix}{2}{+Atom, +Prefix}
Succeeds if \arg{Atom} starts with the characters from \arg{Prefix}.
Its behaviour is equivalent to \exam{?- concat(\arg{Prefix}, _, \arg{Atom})}, but avoids the construction of an atom for the `remainder'.
\predicate{sub_atom}{5}{+Atom, ?Before, ?Len, ?After, ?Sub}
ISO predicate for breaking atoms. It maintains the following relation:
\arg{Sub} is a sub-atom of \arg{Atom} that starts at \arg{Before}, has
\arg{Len} characters and \arg{Atom} contains \arg{After} characters
after the match.
\begin{code}
?- sub_atom(abc, 1, 1, A, S).
A = 1, S = b
\end{code}
The implementation minimalises non-determinism and creation of atoms.
This is a very flexible predicate that can do search, prefix- and
suffix-matching, etc.
\end{description}
\section{Classifying characters} \label{sec:chartype}
SWI-Prolog offers two comprehensive predicates for classifying
characters and character-codes. These predicates are defined as built-in
predicates to exploit the C-character classification's handling of
\jargon{locale} (handling of local character-sets). These predicates
are fast, logical and deterministic if applicable.
In addition, there is the library \pllib{ctype} providing compatibility
to some other Prolog systems. The predicates of this library are defined
in terms of code_type/2.
\begin{description}
\predicate{char_type}{2}{?Char, ?Type}
Tests or generates alternative \arg{Type}s or \arg{Char}s. The
character-types are inspired by the standard C \file{<ctype.h>}
primitives.
\begin{description}
\termitem{alnum}{}
\arg{Char} is a letter (upper- or lowercase) or digit.
\termitem{alpha}{}
\arg{Char} is a letter (upper- or lowercase).
\termitem{csym}{}
\arg{Char} is a letter (upper- or lowercase), digit or the underscore
(\verb$_$). These are valid C- and Prolog symbol characters.
\termitem{csymf}{}
\arg{Char} is a letter (upper- or lowercase) or the underscore
(\verb$_$). These are valid first characters for C- and Prolog symbols
\termitem{ascii}{}
\arg{Char} is a 7-bits ASCII character (0..127).
\termitem{white}{}
\arg{Char} is a space or tab. E.i.\ white space inside a line.
\termitem{cntrl}{}
\arg{Char} is an ASCII control-character (0..31).
\termitem{digit}{}
\arg{Char} is a digit.
\termitem{digit}{Weigth}
\arg{Char} is a digit with value \arg{Weigth}. I.e.\ \exam{char_type(X,
digit(6)} yields \arg{X} = \exam{'6'}. Useful for parsing numbers.
\termitem{xdigit}{Weigth}
\arg{Char} is a haxe-decimal digit with value \arg{Weigth}. I.e.\
\exam{char_type(a, xdigit(X)} yields \arg{X} = \exam{'10'}. Useful for
parsing numbers.
\termitem{graph}{}
\arg{Char} produces a visible mark on a page when printed. Note that
the space is not included!
\termitem{lower}{}
\arg{Char} is a lower-case letter.
\termitem{lower}{Upper}
\arg{Char} is a lower-case version of \arg{Upper}. Only true if
\arg{Char} is lowercase and \arg{Upper} uppercase.
\termitem{to_lower}{Upper}
\arg{Char} is a lower-case version of \arg{Upper}. For non-letters,
or letter without case, \arg{Char} and \arg{Lower} are the same.
\termitem{upper}{}
\arg{Char} is an upper-case letter.
\termitem{upper}{Lower}
\arg{Char} is an upper-case version of \arg{Lower}. Only true if
\arg{Char} is uppercase and \arg{Lower} lowercase.
\termitem{to_upper}{Lower}
\arg{Char} is an upper-case version of \arg{Lower}. For non-letters,
or letter without case, \arg{Char} and \arg{Lower} are the same.
\termitem{punct}{}
\arg{Char} is a punctuation character. This is a \const{graph} character
that is not a letter or digit.
\termitem{space}{}
\arg{Char} is some form of layout character (tab, vertical-tab, newline,
etc.).
\termitem{end_of_file}{}
\arg{Char} is -1.
\termitem{end_of_line}{}
\arg{Char} ends a line (ASCII: 10..13).
\termitem{newline}{}
\arg{Char} is a the newline character (10).
\termitem{period}{}
\arg{Char} counts as the end of a sentence (.,!,?).
\termitem{quote}{}
\arg{Char} is a quote-character (\verb$"$, \verb$'$, \verb$`$).
\termitem{paren}{Close}
\arg{Char} is an open-parenthesis and \arg{Close} is the corresponding
close-parenthesis.
\end{description}
\predicate{code_type}{2}{?Code, ?Type}
As char_type/2, but uses character-codes rather than one-character
atoms. Please note that both predicates are as flexible as possible.
They handle either representation if the argument is instantiated
and only will instantiate with an integer code or one-character atom
depending of the version used. See also the prolog-flag
\const{double_quotes}, atom_chars/2 and atom_codes/2.
\end{description}
\section{Representing text in strings} \label{sec:strings}
SWI-Prolog supports the data type \arg{string}. Strings are a time and
space efficient mechanism to handle text text in Prolog. Strings are
stores as a byte array on the global (term) stack and thus destroyed on
backtracking and reclaimed by the garbage collector.
Strings were added to SWI-Prolog based on an early draft of the ISO
standard, offerring a mechanism to represent temporary character data
efficiently. As SWI-Prolog strings can handle 0-bytes, they
are frequently used through the foreign language interface
(\secref{foreign}) for storing arbitrary byte-sequences.
Starting with version 3.3, SWI-Prolog offers garbage collection on the
atom-space as well as representing 0-bytes in atoms. Although strings
and atoms still have different features, new code should consider using
atoms to avoid too many representations for text as well as for
compatibility to other Prolog systems. Below are some of the
differences:
\begin{itemlist}
\item [creation]
Creating strings is fast, as the data is simply copied to the global
stack. Atoms are unique and therefore more expensive in terms of
memory and time to create. On the other hand, if the same text has
to be represented multiple times, atoms are more efficient.
\item [destruction]
Backtracking destroys strings at no cost. They are cheap to handle by
the garbage collector, but it should be noted that extensive use of
strings will cause many garbage collections. Atom garbage collection is
generally faster.
\end{itemlist}
See also the prolog-flag \const{double_quotes}.
\begin{description}
\predicate{string_to_atom}{2}{?String, ?Atom}
Logical conversion between a string and an atom. At least one of the
two arguments must be instantiated. \arg{Atom} can also be an integer
or floating point number.
\predicate{string_to_list}{2}{?String, ?List}
Logical conversion between a string and a list of ASCII characters. At
least one of the two arguments must be instantiated.
\predicate{string_length}{2}{+String, -Length}
Unify \arg{Length} with the number of characters in \arg{String}. This
predicate is functionally equivalent to atom_length/2 and also accepts
atoms, integers and floats as its first argument.
\predicate{string_concat}{3}{?String1, ?String2, ?String3}
Similar to atom_concat/3, but the unbound argument will be unified with
a string object rather than an atom. Also, if both \arg{String1} and
\arg{String2} are unbound and \arg{String3} is bound to text, it breaks
\arg{String3}, unifying the start with \arg{String1} and the end with
\arg{String2} as append does with lists. Note that this is not
particularly fast on long strings as for each redo the system has to
create two entirely new strings, while the list equivalent only creates
a single new list-cell and moves some pointers around.
\predicate{sub_string}{5}{+String, ?Start, ?Length, ?After, ?Sub}
\arg{Sub} is a substring of \arg{String} starting at \arg{Start}, with
length \arg{Length} and \arg{String} has \arg{After} characters left
after the match. See also sub_atom/5.
\end{description}
\section{Operators} \label{sec:operators}
Operators are defined to improve the readibility of source-code.
For example, without operators, to write \exam{2*3+4*5} one would have
to write \exam{+(*(2,3),*(4,5))}. In Prolog, a number of operators have
been predefined. All operators, except for the comma (,) can be
redefined by the user.
\index{operator,and modules}
Some care has to be taken before defining new operators. Defining too
many operators might make your source `natural' looking, but at the same
time lead to hard to understand the limits of your syntax. To ease the
pain, as of SWI-Prolog 3.3.0, operators are local to the module in which
they are defined. The module-table of the module \const{user} acts as
default table for all modules. This global table can be modified
explictly from inside a module:
\begin{code}
:- module(prove,
[ prove/1
]).
:- op(900, xfx, user:(=>)).
\end{code}
Unlike what many users think, operators and quoted atoms have no
relation: defining a atom as an operator does {\bf not} influence
parsing characters into atoms and quoting an atom does {\bf not} stop
it from acting as an operator. To stop an atom acting as an operator,
enclose it in braces like this: (myop).
\begin{description}
\predicate{op}{3}{+Precedence, +Type, :Name}
Declare \arg{Name} to be an operator of type \arg{Type} with precedence
\arg{Precedence}. \arg{Name} can also be a list of names, in which case
all elements of the list are declared to be identical operators.
\arg{Precedence} is an integer between 0 and 1200. Precedence 0 removes
the declaration. \arg{Type} is one of: \const{xf}, \const{yf},
\const{xfx}, \const{xfy}, \const{yfx}, \const{yfy}, \const{fy} or
\const{fx}. The `\chr{f}' indicates the position of the functor, while
\chr{x} and \chr{y} indicate the position of the arguments. `\chr{y}'
should be interpreted as ``on this position a term with precedence lower
or equal to the precedence of the functor should occur''. For `\chr{x}'
the precedence of the argument must be strictly lower. The precedence of
a term is 0, unless its principal functor is an operator, in which case
the precedence is the precedence of this operator. A term enclosed in
brackets \exam{(\ldots)} has precedence 0.
The predefined operators are shown in \tabref{operators}. Note that
all operators can be redefined by the user.
\begin{table}
\begin{center}
\begin{tabular}{|r|D{f}{f}{-1}|p{4in}|}
\hline
1200 & xfx & \op{-->}, \op{:-} \\
1200 & fx & \op{:-}, \op{?-} \\
1150 & fx & \op{dynamic}, \op{multifile}, \op{module_transparent},
\op{discontiguous}, \op{volatile}, \op{initialization}\\
1100 & xfy & \op{;}, \op{|} \\
1050 & xfy & \op{->} \\
1000 & xfy & \op{,} \\
954 & xfy & \op{\} \\
900 & fy & \op{\+} \\
900 & fx & \op{~} \\
700 & xfx & \op{<}, \op{=}, \op{=..}, \op{=@=}, \op{=:=}, \op{=<}, \op{==},
\op{=\=}, \op{>}, \op{>=}, \op{@<}, \op{@=<}, \op{@>},
\op{@>=}, \op{\=}, \op{\==}, \op{is} \\
600 & xfy & \op{:} \\
500 & yfx & \op{+}, \op{-}, \op{/\}, \op{\/}, \op{xor} \\
500 & fx & \op{+}, \op{-}, \op{?}, \op{\} \\
400 & yfx & \op{*}, \op{/}, \op{//}, \op{<<}, \op{>>}, \op{mod},
\op{rem} \\
200 & xfx & \op{**} \\
200 & xfy & \op{^} \\
\hline
\end{tabular}
\end{center}
\caption{System operators}
\label{tab:operators}
\end{table}
\predicate{current_op}{3}{?Precedence, ?Type, ?:Name}
Succeeds when \arg{Name} is currently defined as an operator of type \arg{Type}
with precedence \arg{Precedence}. See also op/3.
\end{description}
\section{Character Conversion} \label{sec:charconv}
Although I wouldn't really know for what you would like to use these
features, they are provided for ISO complicancy.
\begin{description}
\predicate{char_conversion}{2}{+CharIn, +CharOut}
Define that term-input (see read_term/3) maps each character read as
\arg{CharIn} to the character \arg{CharOut}. Character conversion is
only executed if the prolog-flag \const{char_conversion} is set to
\const{true} and not inside quoted atoms or strings. The initial table
maps each character onto itself. See also current_char_conversion/2.
\predicate{current_char_conversion}{2}{?CharIn, ?CharOut}
Queries the current character conversion-table. See char_conversion/2
for details.
\end{description}
\section{Arithmetic} \label{sec:arith}
Arithmetic can be divided into some special purpose integer predicates
and a series of general predicates for floating point and integer
arithmetic as appropriate. The integer predicates are as ``logical'' as
possible. Their usage is recommended whenever applicable, resulting in
faster and more ``logical'' programs.
The general arithmetic predicates are optionally compiled now (see
set_prolog_flag/2 and the \cmdlineoption{-O} command line option).
Compiled arithmetic reduces global stack requirements and improves
performance. Unfortunately compiled arithmetic cannot be traced, which
is why it is optional.
The general arithmetic predicates all handle \arg{expressions}. An
expression is either a simple number or a \arg{function}. The arguments
of a function are expressions. The functions are described in
\secref{functions}.
\begin{description}
\predicate{between}{3}{+Low, +High, ?Value}
\arg{Low} and \arg{High} are integers, $\arg{High} \geq \arg{Low}$. If
\arg{Value} is an integer, $\arg{Low} \leq \arg{Value} \leq \arg{High}$.
When \arg{Value} is a variable it is successively bound to all integers
between \arg{Low} and \arg{High}.
\predicate{succ}{2}{?Int1, ?Int2}
Succeeds if $\arg{Int2} = \arg{Int1} + 1$. At least one of the arguments
must be instantiated to an integer.
\predicate{plus}{3}{?Int1, ?Int2, ?Int3}
Succeeds if $\arg{Int3} = \arg{Int1} + \arg{Int2}$. At least two of the
three arguments must be instantiated to integers.
\infixop{>}{+Expr1}{+Expr2}
Succeeds when expression \arg{Expr1} evaluates to a larger number than \arg{Expr2}.
\infixop{<}{+Expr1}{+Expr2}
Succeeds when expression \arg{Expr1} evaluates to a smaller number than \arg{Expr2}.
\infixop{=<}{+Expr1}{+Expr2}
Succeeds when expression \arg{Expr1} evaluates to a smaller or equal number
to \arg{Expr2}.
\infixop{>=}{+Expr1}{+Expr2}
Succeeds when expression \arg{Expr1} evaluates to a larger or equal number
to \arg{Expr2}.
\infixop{=\=}{+Expr1}{+Expr2}
Succeeds when expression \arg{Expr1} evaluates to a number non-equal to
\arg{Expr2}.
\infixop{=:=}{+Expr1}{+Expr2}
Succeeds when expression \arg{Expr1} evaluates to a number equal to \arg{
Expr2}.
\infixop{is}{-Number}{+Expr}
Succeeds when \arg{Number} has successfully been unified with the number
\arg{Expr} evaluates to. If \arg{Expr} evaluates to a float that can be
represented using an integer (i.e, the value is integer and within the
range that can be described by Prolog's integer representation), \arg{
Expr} is unified with the integer value.
Note that normally, is/2 will be used with unbound left operand. If
equality is to be tested, =:=/2 should be used. For example:
\begin{center}\begin{tabular}{lp{2.5in}}
\exam{?- 1.0 is sin({pi}/2).} & Fails!. sin({pi}/2) evaluates to 1.0,
but is/2 will represent this as the
integer 1, after which unify will
fail. \\
\exam{?- 1.0 is float(sin({pi}/2)).} & Succeeds, as the float/1 function
forces the result to be float. \\
\exam{?- 1.0 =:= sin({pi}/2).} & Succeeds as expected.
\end{tabular}\end{center}
\end{description}
\section{Arithmetic Functions} \label{sec:functions}
Arithmetic functions are terms which are evaluated by the arithmetic
predicates described above. SWI-Prolog tries to hide the difference
between integer arithmetic and floating point arithmetic from the Prolog
user. Arithmetic is done as integer arithmetic as long as possible and
converted to floating point arithmetic whenever one of the arguments or
the combination of them requires it. If a function returns a floating
point value which is whole it is automatically transformed into an
integer. There are three types of arguments to functions:
\begin{center}\begin{tabular}{lp{4in}}
\arg{Expr} & Arbitrary expression, returning either a floating
point value or an integer. \\
\arg{IntExpr} & Arbitrary expression that should evaluate into
an integer. \\
\arg{Int} & An integer.
\end{tabular}\end{center}
In case integer addition, subtraction and multiplication would lead to
an integer overflow the operands are automatically converted to
floating point numbers. The floating point functions (sin/1, exp/1,
etc.) form a direct interface to the corresponding C library
functions used to compile SWI-Prolog. Please refer to the C library
documentation for details on precision, error handling, etc.
\begin{description}
\prefixop{-}{+Expr}
$\arg{Result} = -\arg{Expr}$
\infixop{+}{+Expr1}{+Expr2}
$\arg{Result} = \arg{Expr1} + \arg{Expr2}$
\infixop{-}{+Expr1}{+Expr2}
$\arg{Result} = \arg{Expr1} - \arg{Expr2}$
\infixop{*}{+Expr1}{+Expr2}
$\arg{Result} = \arg{Expr1} \times \arg{Expr2}$
\infixop{/}{+Expr1}{+Expr2}
$\arg{Result} = \frac{\arg{Expr1}}{\arg{Expr2}}$
\infixop{mod}{+IntExpr1}{+IntExpr2}
Modulo:
\mbox{\arg{Result} = \arg{IntExpr1} - (\arg{IntExpr1} // \arg{IntExpr2})
$\times$ \arg{IntExpr2}}
The function mod/2 is implemented using the C \verb$%$ operator. It's
behaviour with negtive values is illustrated in the table below.
\begin{center}
\begin{tabular}{rcrcr}
2 &=& 17 &mod& 5 \\
2 &=& 17 &mod& -5 \\
-2 &=& -17 &mod& 5 \\
-2 &=& -17 &mod& 5 \\
\end{tabular}
\end{center}
\infixop{rem}{+IntExpr1}{+IntExpr2}
Remainder of division:
\mbox{\arg{Result} = float_fractional_part(\arg{IntExpr1}/\arg{IntExpr2})}
\infixop{//}{+IntExpr1}{+IntExpr2}
Integer division:
\mbox{\arg{Result} = truncate(\arg{Expr1}/\arg{Expr2})}
\predicate{abs}{1}{+Expr}
Evaluate \arg{Expr} and return the absolute value of it.
\predicate{sign}{1}{+Expr}
Evaluate to -1 if $\arg{Expr} < 0$, 1 if $\arg{Expr} > 0$ and 0 if
$\arg{Expr} = 0$.
\predicate{max}{2}{+Expr1, +Expr2}
Evaluates to the largest of both \arg{Expr1} and \arg{Expr2}.
\predicate{min}{2}{+Expr1, +Expr2}
Evaluates to the smallest of both \arg{Expr1} and \arg{Expr2}.
\predicate{.}{2}{+Int, []}
A list of one element evaluates to the element. This implies \exam{"a"}
evaluates to the ASCII value of the letter `a' (97). This option is
available for compatibility only. It will not work if
`\exam{style_check(+string)}' is active as \exam{"a"} will then be transformed
into a string object. The recommended way to specify the ASCII value of
the letter `a' is \exam{0'a}.
\predicate{random}{1}{+Int}
Evaluates to a random integer \arg{i} for which $0 \leq i < \arg{Int}$.
The seed of this random generator is determined by the system clock when
SWI-Prolog was started.
\predicate{round}{1}{+Expr}
Evaluates \arg{Expr} and rounds the result to the nearest integer.
\predicate{integer}{1}{+Expr}
Same as round/1 (backward compatibility).
\predicate{float}{1}{+Expr}
Translate the result to a floating point number. Normally, Prolog will
use integers whenever possible. When used around the 2nd argument of
is/2, the result will be returned as a floating point number. In other
contexts, the operation has no effect.
\predicate{float_fractional_part}{1}{+Expr}
Fractional part of a floating-point number. Negative if \arg{Expr} is
negative, 0 if \arg{Expr} is integer.
\predicate{float_integer_part}{1}{+Expr}
Integer part of floating-point number. Negative if \arg{Expr} is
negative, \arg{Expr} if \arg{Expr} is integer.
\predicate{truncate}{1}{+Expr}
Truncate \arg{Expr} to an integer. Same as float_integer_part/1.
\predicate{floor}{1}{+Expr}
Evaluates \arg{Expr} and returns the largest integer smaller or equal
to the result of the evaluation.
\predicate{ceiling}{1}{+Expr}
Evaluates \arg{Expr} and returns the smallest integer larger or equal
to the result of the evaluation.
\predicate{ceil}{1}{+Expr}
Same as ceiling/1 (backward compatibility).
\infixop{>>}{+IntExpr}{+IntExpr}
Bitwise shift \arg{IntExpr1} by \arg{IntExpr2} bits to the right.
\infixop{<<}{+IntExpr}{+IntExpr}
Bitwise shift \arg{IntExpr1} by \arg{IntExpr2} bits to the left.
\infixop{\/}{+IntExpr}{+IntExpr}
Bitwise `or' \arg{IntExpr1} and \arg{IntExpr2}.
\infixop{/\}{+IntExpr}{+IntExpr}
Bitwise `and' \arg{IntExpr1} and \arg{IntExpr2}.
\infixop{xor}{+IntExpr}{+IntExpr}
Bitwise `exclusive or' \arg{IntExpr1} and \arg{IntExpr2}.
\prefixop{\}{+IntExpr}
Bitwise negation.
\predicate{sqrt}{1}{+Expr}
$\arg{Result} = \sqrt{\arg{Expr}}$
\predicate{sin}{1}{+Expr}
$\arg{Result} = \sin{\arg{Expr}}$. \arg{Expr} is the angle in radians.
\predicate{cos}{1}{+Expr}
$\arg{Result} = \cos{\arg{Expr}}$. \arg{Expr} is the angle in radians.
\predicate{tan}{1}{+Expr}
$\arg{Result} = \tan{\arg{Expr}}$. \arg{Expr} is the angle in radians.
\predicate{asin}{1}{+Expr}
$\arg{Result} = \arcsin{\arg{Expr}}$. \arg{Result} is the angle in radians.
\predicate{acos}{1}{+Expr}
$\arg{Result} = \arccos{\arg{Expr}}$. \arg{Result} is the angle in radians.
\predicate{atan}{1}{+Expr}
$\arg{Result} = \arctan{\arg{Expr}}$. \arg{Result} is the angle in radians.
\predicate{atan}{2}{+YExpr, +XExpr}
$\arg{Result} = \arctan{\frac{\arg{YExpr}}{\arg{XExpr}}}$. \arg{Result} is the
angle in radians. The return value is in the range $[-\pi\ldots\pi]$.
Used to convert between rectangular and polar coordinate system.
\predicate{log}{1}{+Expr}
$\arg{Result} = \ln{\arg{Expr}}$
\predicate{log10}{1}{+Expr}
$\arg{Result} = \lg{\arg{Expr}}$
\predicate{exp}{1}{+Expr}
$\arg{Result} = \pow{e}{\arg{Expr}}$
\infixop{**}{+Expr1}{+Expr2}
$\arg{Result} = \pow{\arg{Expr1}}{\arg{Expr2}}$
\infixop{^}{+Expr1}{+Expr2}
Same as **/2. (backward compatibility).
\predicate{pi}{0}{}
Evaluates to the mathematical constant $\pi$ (3.141593).
\predicate{e}{0}{}
Evaluates to the mathematical constant $e$ (2.718282).
\predicate{cputime}{0}{}
Evaluates to a floating point number expressing the {\sc cpu} time (in seconds)
used by Prolog up till now. See also statistics/2 and time/1.
\end{description}
\section{Adding Arithmetic Functions} \label{sec:extendarith}
Prolog predicates can be given the role of arithmetic function. The
last argument is used to return the result, the arguments before the
last are the inputs. Arithmetic functions are added using the
predicate arithmetic_function/1, which takes the head as its argument.
Arithmetic functions are module sensitive, that is they are only
visible from the module in which the function is defined and declared.
Global arithmetic functions should be defined and registered from
module \const{user}. Global definitions can be overruled locally in
modules. The builtin functions described above can be redefined as
well.
\begin{description}
\predicate{arithmetic_function}{1}{+Head}
Register a Prolog predicate as an arithmetic function (see is/2,
\predref{>}{2}, etc.). The Prolog predicate should have one more
argument than specified by \arg{Head}, which it either a term \arg{Name/Arity}, an atom or a complex term. This last argument is an unbound
variable at call time and should be instantiated to an integer or
floating point number. The other arguments are the parameters. This
predicate is module sensitive and will declare the arithmetic function
only for the context module, unless declared from module \const{user}.
Example:
\begin{code}
1 ?- [user].
:- arithmetic_function(mean/2).
mean(A, B, C) :-
C is (A+B)/2.
user compiled, 0.07 sec, 440 bytes.
Yes
2 ?- A is mean(4, 5).
A = 4.500000
\end{code}
\predicate{current_arithmetic_function}{1}{?Head}
Successively unifies all arithmetic functions that are visible from
the context module with \arg{Head}.
\end{description}
\section{List Manipulation} \label{sec:maniplist}
\begin{description}
\predicate{is_list}{1}{+Term}
Succeeds if \arg{Term} is bound to the empty list (\exam{[]}) or a term with
functor `\const{.}' and arity~2.
\predicate{proper_list}{1}{+Term}
Equivalent to is_list/1, but also requires the tail of the list to be
a list (recursively). Examples:
\begin{code}
is_list([x|A]) % true
proper_list([x|A]) % false
\end{code}
\predicate{append}{3}{?List1, ?List2, ?List3}
Succeeds when \arg{List3} unifies with the concatenation of \arg{List1}
and \arg{List2}. The predicate can be used with any instantiation
pattern (even three variables).
\predicate{member}{2}{?Elem, ?List}
Succeeds when \arg{Elem} can be unified with one of the members of \arg{List}. The predicate can be used with any instantiation
pattern.
\predicate{memberchk}{2}{?Elem, +List}
Equivalent to member/2, but leaves no choice point.
\predicate{delete}{3}{+List1, ?Elem, ?List2}
Delete all members of \arg{List1} that simultaneously unify with \arg{Elem} and unify the result with \arg{List2}.
\predicate{select}{3}{?Elem, ?List, ?Rest}
Select \arg{Elem} from \arg{List} leaving \arg{Rest}. It behaves as
member/2, returning the remaining elements in \arg{Rest}. Note that
besides selecting elements from a list, it can also be used to insert
elements.%
\bug{Upto SWI-Prolog 3.3.10, the definition of this predicate was
not according to the de-facto standard. The first two arguments
were in the wrong order.}
\predicate{nth0}{3}{?Index, ?List, ?Elem}
Succeeds when the \arg{Index}-th element of \arg{List} unifies with
\arg{Elem}. Counting starts at 0.
\predicate{nth1}{3}{?Index, ?List, ?Elem}
Succeeds when the \arg{Index}-th element of \arg{List} unifies with
\arg{Elem}. Counting starts at 1.
\predicate{last}{2}{?Elem, ?List}
Succeeds if \arg{Elem} unifies with the last element of \arg{List}. If
\arg{List} is a proper list last/2 is deterministic. If \arg{List} has
an unbound tail, backtracking will cause \arg{List} to grow.
\predicate{reverse}{2}{+List1, -List2}
Reverse the order of the elements in \arg{List1} and unify the result
with the elements of \arg{List2}.
\predicate{flatten}{2}{+List1, -List2}
Transform \arg{List1}, possibly holding lists as elements into a `flat'
list by replacing each list with its elements (recursively). Unify the
resulting flat list with \arg{List2}. Example:
\begin{code}
?- flatten([a, [b, [c, d], e]], X).
X = [a, b, c, d, e]
\end{code}
\predicate{length}{2}{?List, ?Int}
Succeeds if \arg{Int} represents the number of elements of list \arg{List}. Can be used to create a list holding only variables.
\predicate{merge}{3}{+List1, +List2, -List3}
\arg{List1} and \arg{List2} are lists, sorted to the standard order of
terms (see \secref{compare}). \arg{List3} will be unified with an
ordered list holding both the elements of \arg{List1} and \arg{List2}.
Duplicates are {\bf not} removed.
\end{description}
\section{Set Manipulation} \label{sec:manipset}
\begin{description}
\predicate{is_set}{1}{+Set}
Succeeds if \arg{Set} is a proper list (see proper_list/1) without duplicates.
\predicate{list_to_set}{2}{+List, -Set}
Unifies \arg{Set} with a list holding the same elements as \arg{List} in
the same order. If \arg{list} contains duplicates, only the first is
retained. See also sort/2. Example:
\begin{code}
?- list_to_set([a,b,a], X)
X = [a,b]
\end{code}
\predicate{intersection}{3}{+Set1, +Set2, -Set3}
Succeeds if \arg{Set3} unifies with the intersection of \arg{Set1} and
\arg{Set2}. \arg{Set1} and \arg{Set2} are lists without duplicates.
They need not be ordered.
\predicate{subtract}{3}{+Set, +Delete, -Result}
Delete all elements of set `Delete' from `Set' and unify the resulting
set with `Result'.
\predicate{union}{3}{+Set1, +Set2, -Set3}
Succeeds if \arg{Set3} unifies with the union of \arg{Set1} and
\arg{Set2}. \arg{Set1} and \arg{Set2} are lists without duplicates.
They need not be ordered.
\predicate{subset}{2}{+Subset, +Set}
Succeeds if all elements of \arg{Subset} are elements of \arg{Set} as well.
\predicate{merge_set}{3}{+Set1, +Set2, -Set3}
\arg{Set1} and \arg{Set2} are lists without duplicates, sorted to the
standard order of terms. \arg{Set3} is unified with an ordered
list without duplicates holding the union of the elements of \arg{Set1}
and \arg{Set2}.
\end{description}
\section{Sorting Lists} \label{sec:sort}
\begin{description}
\predicate{sort}{2}{+List, -Sorted}
Succeeds if \arg{Sorted} can be unified with a list holding the
elements of \arg{List}, sorted to the standard order of terms (see
\secref{compare}). Duplicates are removed. Implemented by translating
the input list into a temporary array, calling the C-library function
\manref{qsort}{3} using \funcref{PL_compare}{} for comparing the elements,
after which the result is translated into the result list.
\predicate{msort}{2}{+List, -Sorted}
Equivalent to sort/2, but does not remove duplicates.
\predicate{keysort}{2}{+List, -Sorted}
List is a proper list whose elements are \exam{\arg{Key}-\arg{Value}},
that is, terms whose principal functor is (-)/2, whose first argument is
the sorting key, and whose second argument is the satellite data to be
carried along with the key. keysort/2 sorts \arg{List} like msort/2, but
only compares the keys. Can be used to sort terms not on standard order,
but on any criterion that can be expressed on a multi-dimensional scale.
Sorting on more than one criterion can be done using terms as keys,
putting the first criterion as argument 1, the second as argument 2,
etc. The order of multiple elements that have the same \arg{Key} is not
changed.
\predicate{predsort}{3}{+Pred, +List, -Sorted}
Sorts similar to sort/2, but determines the order of two terms by
calling \mbox{\arg{Pred}(-\arg{Delta}, +\arg{E1}, +\arg{E2})}. This
call must unify \arg{Delta} with one of \const{<}, const{>} or
\const{=}. If built-in predicate compare/3 is used, the result is
the same as sort/2. See also keysort/2.%
\footnote{Please note that the semantics have changed between
3.1.1 and 3.1.2}
\end{description}
\section{Finding all Solutions to a Goal} \label{sec:allsolutions}
\begin{description}
\predicate{findall}{3}{+Var, +Goal, -Bag}
Creates a list of the instantiations \arg{Var} gets successively on
backtracking over \arg{Goal} and unifies the result with \arg{Bag}.
Succeeds with an empty list if \arg{Goal} has no solutions. findall/3 is
equivalent to bagof/3 with all free variables bound with the existence
operator (\op{^}), except that bagof/3 fails when goal has no
solutions.
\predicate{bagof}{3}{+Var, +Goal, -Bag}
Unify \arg{Bag} with the alternatives of \arg{Var}, if \arg{Goal} has
free variables besides the one sharing with \arg{Var} bagof will
backtrack over the alternatives of these free variables, unifying \arg{Bag} with the corresponding alternatives of \arg{Var}. The construct
\exam{+\arg{Var}{^}\arg{Goal}} tells bagof not to bind \arg{Var} in
\arg{Goal}. bagof/3 fails if \arg{Goal} has no solutions.
The example below illustrates bagof/3 and the \op{^} operator. The
variable bindings are printed together on one line to save paper.
\begin{code}
2 ?- listing(foo).
foo(a, b, c).
foo(a, b, d).
foo(b, c, e).
foo(b, c, f).
foo(c, c, g).
Yes
3 ?- bagof(C, foo(A, B, C), Cs).
A = a, B = b, C = G308, Cs = [c, d] ;
A = b, B = c, C = G308, Cs = [e, f] ;
A = c, B = c, C = G308, Cs = [g] ;
No
4 ?- bagof(C, A^foo(A, B, C), Cs).
A = G324, B = b, C = G326, Cs = [c, d] ;
A = G324, B = c, C = G326, Cs = [e, f, g] ;
No
5 ?-
\end{code}
\predicate{setof}{3}{+Var, +Goal, -Set}
Equivalent to bagof/3, but sorts the result using sort/2 to get a sorted
list of alternatives without duplicates.
\end{description}
\section{Invoking Predicates on all Members of a List} \label{sec:applylist}
All the predicates in this section call a predicate on all members of a
list or until the predicate called fails. The predicate is called via
call/[2..], which implies common arguments can be put in
front of the arguments obtained from the list(s). For example:
\begin{code}
?- maplist(plus(1), [0, 1, 2], X).
X = [1, 2, 3]
\end{code}
we will phrase this as ``\arg{Predicate} is applied on \ldots''
\begin{description}
\predicate{checklist}{2}{+Pred, +List}
\arg{Pred} is applied successively on each element of \arg{List} until
the end of the list or \arg{Pred} fails. In the latter case the
checklist/2 fails.
\predicate{maplist}{3}{+Pred, ?List1, ?List2}
Apply \arg{Pred} on all successive pairs of elements from \arg{List1}
and \arg{List2}. Fails if \arg{Pred} can not be applied to a pair. See
the example above.
\predicate{sublist}{3}{+Pred, +List1, ?List2}
Unify \arg{List2} with a list of all elements of \arg{List1} to which
\arg{Pred} applies.
\end{description}
\section{Forall} \label{sec:forall2}
\begin{description}
\predicate{forall}{2}{+Cond, +Action}
For all alternative bindings of \arg{Cond} \arg{Action} can be proven.
The example verifies that all arithmetic statements in the list \arg{L}
are correct. It does not say which is wrong if one proves wrong.
\begin{code}
?- forall(member(Result = Formula, [2 = 1 + 1, 4 = 2 * 2]),
Result =:= Formula).
\end{code}
\end{description}
\section{Formatted Write} \label{sec:format}
The current version of SWI-Prolog provides two formatted
write predicates. The first is writef/[1,2], which is compatible with
Edinburgh C-Prolog. The second is format/[1,2], which is compatible
with Quintus Prolog. We hope the Prolog community will once define a
standard formatted write predicate. If you want performance use
format/[1,2] as this predicate is defined in C. Otherwise
compatibility reasons might tell you which predicate to use.
\subsection{Writef}
\begin{description}
\predicate{writeln}{1}{+Term}
Equivalent to \exam{write(Term), nl.}
\predicate{writef}{1}{+Atom}
Equivalent to \exam{writef(Atom, []).}
\predicate{writef}{2}{+Format, +Arguments}
Formatted write. \arg{Format} is an atom whose characters will be printed.
\arg{Format} may contain certain special character sequences which specify
certain formatting and substitution actions. \arg{Arguments} then provides
all the terms required to be output.
Escape sequences to generate a single special character:
\begin{center}
\begin{tabular}{|l|p{3.5in}|}
\hline
\fmtseq{\n} & Output a nemline character (see also nl/[0,1]) \\
\fmtseq{\l} & Output a line separator (same as \fmtseq{\n}) \\
\fmtseq{\r} & Output a carriage-return character (ASCII 13) \\
\fmtseq{\t} & Output the ASCII character TAB (9) \\
\fmtseq{\\} & The character \chr{\} is output \\
\fmtseq{\%} & The character \chr{%} is output \\
\fmtseq{\nnn} & where <nnn> is an integer (1-3 digits) the
character with ASCII code <nnn> is output
(NB : <nnn> is read as \strong{decimal}) \\
\hline
\end{tabular}
\end{center}
Note that \fmtseq{\l}, \fmtseq{\nnn} and \fmtseq{\\}
are interpreted differently when character-escapes are in effect. See
\secref{charescapes}.
Escape sequences to include arguments from \arg{Arguments}. Each time a
\% escape sequence is found in \arg{Format} the next argument from \arg{Arguments} is formatted according to the specification.
\begin{center}
\begin{tabular}{|l|p{3.5in}|}
\hline
\fmtseq{%t} & print/1 the next item (mnemonic: term) \\
\fmtseq{%w} & write/1 the next item \\
\fmtseq{%q} & writeq/1 the next item \\
\fmtseq{%d} & Write the term, ignoring operators. See also
write_term/2. Mnemonic: old Edinburgh display/1. \\
\fmtseq{%p} & print/1 the next item (identical to \fmtseq{%t}) \\
\fmtseq{%n} & Put the next item as a character (i.e., it is
an ASCII value) \\
\fmtseq{%r} & Write the next item N times where N is the
second item (an integer) \\
\fmtseq{%s} & Write the next item as a String (so it must
be a list of characters) \\
\fmtseq{%f} & Perform a ttyflush/0 (no items used) \\
\fmtseq{%Nc} & Write the next item Centered in $N$ columns. \\
\fmtseq{%Nl} & Write the next item Left justified in $N$ columns. \\
\fmtseq{%Nr} & Write the next item Right justified in $N$ columns.
$N$ is a decimal number with at least one digit.
The item must be an atom, integer, float or string. \\
\hline
\end{tabular}
\end{center}
\predicate{swritef}{3}{-String, +Format, +Arguments}
Equivalent to writef/2, but ``writes'' the result on \arg{String} instead
of the current output stream. Example:
\begin{code}
?- swritef(S, '%15L%w', ['Hello', 'World']).
S = "Hello World"
\end{code}
\predicate{swritef}{2}{-String, +Format}
Equivalent to \exam{swritef(String, Format, []).}
\end{description}
\subsection{Format}
\begin{description}
\predicate{format}{1}{+Format}
Defined as `\exam{format(Format) :- format(Format, []).}'
\predicate{format}{2}{+Format, +Arguments}
\arg{Format} is an atom, list of ASCII values, or a Prolog string.
\arg{Arguments} provides the arguments required by the format
specification. If only one argument is required and this is not a list
of ASCII values the argument need not be put in a list. Otherwise the
arguments are put in a list.
Special sequences start with the tilde (\chr{~}), followed by an
optional numeric argument, followed by a character describing the action
to be undertaken. A numeric argument is either a sequence of digits,
representing a positive decimal number, a sequence \exam{`<character>},
representing the ASCII value of the character (only useful for
\fmtseq{~t}) or a asterisk (\chr{*}), in when the numeric
argument is taken from the next argument of the argument list, which
should be a positive integer. Actions are:
\begin{itemize}
\fmtchar{~}
Output the tilde itself.
\fmtchar{a}
Output the next argument, which should be an atom. This option is
equivalent to {\bf w}. Compatibility reasons only.
\fmtchar{c}
Output the next argument as an ASCII value. This argument should be an
integer in the range [0, \ldots, 255] (including 0 and 255).
\fmtchar{d}
Output next argument as a decimal number. It should be an integer. If
a numeric argument is specified a dot is inserted \arg{argument}
positions from the right (useful for doing fixed point arithmetic with
integers, such as handling amounts of money).
\fmtchar{D}
Same as {\bf d}, but makes large values easier to read by inserting a
comma every three digits left to the dot or right.
\fmtchar{e}
Output next argument as a floating point number in exponential
notation. The numeric argument specifies the precision. Default is 6
digits. Exact representation depends on the C library function
printf(). This function is invoked with the format
\mbox{\tt\%.<precision>e}.
\fmtchar{E}
Equivalent to {\bf e}, but outputs a capital E to indicate the exponent.
\fmtchar{f}
Floating point in non-exponential notation. See C library function
printf().
\fmtchar{g}
Floating point in {\bf e} or {\bf f} notation, whichever is shorter.
\fmtchar{G}
Floating point in {\bf E} or {\bf f} notation, whichever is shorter.
\fmtchar{i}
Ignore next argument of the argument list. Produces no output.
\fmtchar{k}
Give the next argument to displayq/1 (canonical write).
\fmtchar{n}
Output a newline character.
\fmtchar{N}
Only output a newline if the last character output on this stream was
not a newline. Not properly implemented yet.
\fmtchar{p}
Give the next argument to print/1.
\fmtchar{q}
Give the next argument to writeq/1.
\fmtchar{r}
Print integer in radix the numeric argument notation. Thus
\fmtseq{~16r} prints its argument hexadecimal. The argument should
be in the range $[2, \ldots, 36]$. Lower case letters are used for
digits above 9.
\fmtchar{R}
Same as {\bf r}, but uses upper case letters for digits above 9.
\fmtchar{s}
Output a string of ASCII characters or a string (see string/1 and
\secref{strings}) from the next argument.
\fmtchar{t}
All remaining space between 2 tabs tops is distributed equally over
\fmtseq{~t} statements between the tabs tops. This space is padded
with spaces by default. If an argument is supplied this is taken to be
the ASCII value of the character used for padding. This can be used to
do left or right alignment, centering, distributing, etc. See also
\fmtseq{~|} and \fmtseq{~+} to set tab stops. A tabs top is
assumed at the start of each line.
\fmtchar{|}
Set a tabs top on the current position. If an argument is supplied set a
tabs top on the position of that argument. This will cause all
\fmtseq{~t}'s to be distributed between the previous and this tabs
top.
\fmtchar{+}
Set a tabs top relative to the current position. Further the same as
\fmtseq{~|}.
\fmtchar{w}
Give the next argument to write/1.
\fmtchar{W}
Give the next two argument to write_term/2. This option is SWI-Prolog
specific.
\end{itemize}
Example:
\begin{code}
simple_statistics :-
<obtain statistics> % left to the user
format('~tStatistics~t~72|~n~n'),
format('Runtime: ~`.t ~2f~34| Inferences: ~`.t ~D~72|~n',
[RunT, Inf]),
....
\end{code}
Will output
\begin{code}
Statistics
Runtime: .................. 3.45 Inferences: .......... 60,345
\end{code}
\predicate{format}{3}{+Stream, +Format, +Arguments}
As format/2, but write the output on the given \arg{Stream}.
\predicate{sformat}{3}{-String, +Format, +Arguments}
Equivalent to format/2, but ``writes'' the result on \arg{String}
instead of the current output stream. Example:
\begin{code}
?- sformat(S, '~w~t~15|~w', ['Hello', 'World']).
S = "Hello World"
\end{code}
\predicate{sformat}{2}{-String, +Format}
Equivalent to `\exam{sformat(String, Format, []).}'
\end{description}
\subsection{Programming Format}
\begin{description}
\predicate{format_predicate}{2}{+Char, +Head}
If a sequence \fmtseq{~c} (tilde, followed by some character) is
found, the format derivatives will first check whether the user has
defined a predicate to handle the format. If not, the built in
formatting rules described above are used. \arg{Char} is either an {\sc
ascii} value, or a one character atom, specifying the letter to be
(re)defined. \arg{Head} is a term, whose name and arity are used to
determine the predicate to call for the redefined formatting character.
The first argument to the predicate is the numeric argument of the
format command, or the atom \const{default} if no argument is specified.
The remaining arguments are filled from the argument list. The example
below redefines \fmtseq{~n} to produce \arg{Arg} times return
followed by linefeed (so a (Grr.) DOS machine is happy with the output).
\begin{code}
:- format_predicate(n, dos_newline(_Arg)).
dos_newline(Arg) :-
between(1, Ar, _), put(13), put(10), fail ; true.
\end{code}
\predicate{current_format_predicate}{2}{?Code, ?:Head}
Enumerates all user-defined format predicates. \arg{Code} is the
character code of the format character. \arg{Head} is unified with
a term with the same name and arity as the predicate. If the
predicate does not reside in module \const{user}, \arg{Head} is
qualified with the definition module of the predicate.
\end{description}
\section{Terminal Control} \label{sec:tty}
The following predicates form a simple access mechanism to the Unix termcap
library to provide terminal independent I/O for screen terminals. These
predicates are only available on Unix machines. The SWI-Prolog Windows
consoles accepts the ANSI escape sequences.
\begin{description}
\predicate{tty_get_capability}{3}{+Name, +Type, -Result}
Get the capability named \arg{Name} from the termcap library. See
termcap(5) for the capability names. \arg{Type} specifies the type of
the expected result, and is one of \const{string}, \const{number} or
\const{bool}. String results are returned as an atom, number result as
an integer and bool results as the atom \const{on} or \const{off}. If
an option cannot be found this predicate fails silently. The
results are only computed once. Successive queries on the same
capability are fast.
\predicate{tty_goto}{2}{+X, +Y}
Goto position \mbox{(\arg{X}, \arg{Y})} on the screen. Note that the predicates
line_count/2 and line_position/2 will not have a well defined
behaviour while using this predicate.
\predicate{tty_put}{2}{+Atom, +Lines}
Put an atom via the termcap library function tputs(). This function
decodes padding information in the strings returned by tty_get_capability/3
and should be used to output these strings. \arg{Lines} is the
number of lines affected by the operation, or 1 if not applicable (as
in almost all cases).
\predicate{set_tty}{2}{-OldStream, +NewStream}
Set the output stream, used by tty_put/2 and tty_goto/2 to a
specific stream. Default is user_output.
\predicate{tty_size}{2}{-Rows, -Columns}
Determine the size of the terminal. If the system provides
\jargon{ioctl} calls for this these are used and tty_size/2 properly
reflects the actual size after a user resize of the window. As a
fallback, the system uses tty_get_capability/2 using \const{li} and
\const{co} capabilities. In this case the reported size reflects the
size at the first call and is not updated after a user-initiated
resize of the terminal.
\end{description}
\section{Operating System Interaction} \label{sec:system}
\begin{description}
\predicate{shell}{2}{+Command, -Status}
Execute \arg{Command} on the operating system. \arg{Command} is given to the
Bourne shell (/bin/sh). \arg{Status} is unified with the exit status of
the command.
On \arg{Win32} systems, shell/[1,2] executes the command using the
CreateProcess() API and waits for the command to terminate. If the
command ends with a \chr{\&} sign, the command is handed to the
WinExec() API, which does not wait for the new task to terminate. See
also win_exec/2 and win_shell/2. Please note that the CreateProcess()
API does {\bf not} imply the Windows command interpreter
(\program{command.exe} on Windows 95/98 and \program{cmd.exe} on
Windows-NT) and therefore commands built-in to the command-interpreter
can only be activated using the command interpreter. For example:
\exam{'command.exe /C copy file1.txt file2.txt'}
\predicate{shell}{1}{+Command}
Equivalent to `\exam{shell(Command, 0)}'.
\predicate{shell}{0}{}
Start an interactive Unix shell. Default is \file{/bin/sh}, the
environment variable \env{SHELL} overrides this default. Not available
for Win32 platforms.
\predicate{win_exec}{2}{+Command, +Show}
Win32 systems only. Spawns a Windows task without waiting for its
completion. \arg{Show} is either \const{iconic} or \const{normal} and
dictates the initial status of the window. The \const{iconic} option
is notably handy to start (DDE) servers.
\predicate{win_shell}{2}{+Operation, +File}
Win32 systems only. Opens the document \arg{File} using the windows
shell-rules for doing so. \arg{Operation} is one of \const{open},
\const{print} or \const{explore} or another operation registered with
the shell for the given document-type. On modern systems it is also
possible to pass a \index{URL}URL as \arg{File}, opening the URL in
Windows default browser. This call interfaces to the Win32 API
ShellExecute().
\predicate{win_registry_get_value}{3}{+Key, +Name, -Value}
Win32 systems only. Fetches the value of a Win32 registry key.
\arg{Key} is an atom formed as a path-name describing the desired
registry key. \arg{Name} is the desired attribute name of the key.
\arg{Value} is unified with the value. If the value is of type
\type{DWORD}, the value is returned as an integer. If the value is a
string it is returned as a Prolog atom. Other types are currently not
supported. The default `root' is \const{HKEY_CURRENT_USER}. Other roots
can be specified explicitely as \const{HKEY_CLASSES_ROOT},
\const{HKEY_CURRENT_USER}, \const{HKEY_LOCAL_MACHINE} or
\const{HKEY_USERS}. The example below fetches the extension to use
for Prolog files (see \file{README.TXT} on the Windows version):
\begin{code}
?- win_registry_get_value('HKEY_LOCAL_MACHINE/Software/SWI/Prolog',
fileExtension,
Ext).
Ext = pl
\end{code}
\predicate{getenv}{2}{+Name, -Value}
Get environment variable. Fails silently if the variable does not exist.
Please note that environment variable names are case-sensitive on Unix
systems and case-insensitive on Windows.
\predicate{setenv}{2}{+Name, +Value}
Set environment variable. \arg{Name} and \arg{Value} should be
instantiated to atoms or integers. The environment variable will be
passed to shell/[0-2] and can be requested using getenv/2. They also
influence expand_file_name/2.
\predicate{unsetenv}{1}{+Name}
Remove environment variable from the environment.
\predicate{unix}{1}{+Command}
This predicate comes from the Quintus compatibility library and provides
a partial implementation thereof. It provides access to some operating
system features and unlike the name suggests, is not operating system
specific. Currently it is the only way to fetch the Prolog command-line
arguments. Defined \arg{Command}'s are below.
\begin{description}
\termitem{system}{+Command}
Equivalent to calling shell/1. Use for compatibility only.
\termitem{shell}{+Command}
Equivalent to calling shell/1. Use for compatibility only.
\termitem{shell}{}
Equivalent to calling shell/0. Use for compatibility only.
\termitem{cd}{}
Equivalent to calling working_directory/2 to the expansion (see
expand_file_name/2) of \chr{~}. For compatibility only.
\termitem{cd}{+Directory}
Equivalent to calling working_directory/2. Use for compatibility
only.
\termitem{argv}{-Argv}
Unify \arg{Argv} with the list of commandline arguments provides to
this Prolog run. Please note that Prolog system-arguments and
application arguments are separated by \const{--}. Integer arguments
are passed as Prolog integers, float arguments and Prolog floating
point numbers and all other arguments as Prolog atoms. New applications
should use the prolog-flag \const{argv}.
A stand-alone program could use the following skeleton to handle
command-line arguments. See also \secref{cmdlinecomp}.
\begin{code}
main :-
unix(argv(Argv)),
append(_PrologArgs, [--|AppArgs], Argv), !,
main(AppArgs).
\end{code}
\end{description}
\end{description}
\subsection{Dealing with time and date} \label{sec:timedate}
There is no standard for time-representation in the Prolog community.
SWI-Prolog represents it as a floating-point number using the same
basic representation as the POSIX standard, seconds elapsed since the
January 1970, 0 hours. This format is also used for predicates
accessing time-information from files (see time_file/2).
\begin{description}
\predicate{get_time}{1}{-Time}
Return the number of seconds that elapsed since the epoch of the POSIX,
tim representation: January 1970, 0 hours. \arg{Time} is a floating
point number. The granularity is system dependent.
\predicate{convert_time}{8}{+Time, -Year, -Month, -Day,
-Hour, -Minute, -Second, -MilliSeconds}
Convert a time stamp, provided by get_time/1, time_file/2, etc. \arg{Year} is unified with the year, \arg{Month} with the month number
(January is 1), \arg{Day} with the day of the month (starting with 1),
\arg{Hour} with the hour of the day (0--23), \arg{Minute} with the
minute (0--59). \arg{Second} with the second (0--59) and \arg{MilliSecond} with the milliseconds (0--999). Note that the latter
might not be accurate or might always be 0, depending on the timing
capabilities of the system. See also convert_time/2.
\predicate{convert_time}{2}{+Time, -String}
Convert a time-stamp as obtained though get_time/1 into a textual
representation using the C-library function \funcref{ctime}{}. The
value is returned as a SWI-Prolog string object (see \secref{strings}).
See also convert_time/8.
\end{description}
\subsection{Handling the menu in program{PLWIN.EXE}}
The Windows executable \program{PLWIN.EXE} has a menu-bar displayed at
the top that can be programmed from Prolog. Being totally non-portable,
we do not advice using it for your own application, but use XPCE or
another portable GUI platform instead. We give the predicates for
reference here.
\begin{description}
\predicate{win_insert_menu}{2}{+Label, +Before}
Insert a new entry (pulldown) in the menu. If the menu already contains
this entry, nothing is done. The \arg{Label} is the label and using the
Windows conventions, a letter prefixed with \const{\&} is underlined and
defines the associated accelerator key. \arg{Before} is the label before
which this one must be inserted. Using \chr{-} adds the new entry at the
end (right). For example, the call below adds a {\sf Application}
entry just before the {\sf Help} menu.
\begin{code}
win_insert_menu('&Application', '&Help')
\end{code}
\predicate{win_insert_menu_item}{4}{+Pulldown, +Label, +Before, :Goal}
Add an item to the named \arg{Pulldown} menu. \arg{Label} and
\arg{Before} are handled as in win_insert_menu/2, but the label \chr{-}
inserts a \jargon{separator}. \arg{Goal} is called if the user selects
the item.
\end{description}
\section{File System Interaction} \label{sec:files}
\begin{description}
\predicate{access_file}{2}{+File, +Mode}
Succeeds if \arg{File} exists and can be accessed by this prolog
process under mode \arg{Mode}. \arg{Mode} is one of the atoms
\const{read}, \const{write}, \const{append}, \const{exist}, \const{none} or
\const{execute}. \arg{File} may also be the name of a directory. Fails
silently otherwise. \exam{access_file(File, none)} simply succeeds
without testing anything.
If `Mode' is \const{write} or \const{append}, this predicate also succeeds
if the file does not exist and the user has write-access to the
directory of the specified location.
\predicate{exists_file}{1}{+File}
Succeeds when \arg{File} exists. This does not imply the user has read
and/or write permission for the file.
\predicate{file_directory_name}{2}{+File, -Directory}
Extracts the directory-part of \arg{File}. The returned \arg{Directory}
name does not end in \const{/}. There are two special cases. The
directory-name of \const{/} is \const{/} itself and the directory-name
if \arg{File} does not contain any \const{/} characters is \const{.}.
\predicate{file_base_name}{2}{+File, -BaseName}
Extracts the filename part from a path specification. If \arg{File} does
not contain any directory separators, \arg{File} is returned.
\predicate{same_file}{2}{+File1, +File2}
Succeeds if both filenames refer to the same physical file. That is,
if \arg{File1} and \arg{File2} are the same string or both names exist
and point to the same file (due to hard or symbolic links and/or
relative vs. absolute paths).
\predicate{exists_directory}{1}{+Directory}
Succeeds if \arg{Directory} exists. This does not imply the user has read,
search and or write permission for the directory.
\predicate{delete_file}{1}{+File}
Remove \arg{File} from the file system.
\predicate{rename_file}{2}{+File1, +File2}
Rename \arg{File1} into \arg{File2}. Currently files cannot be moved
across devices.
\predicate{size_file}{2}{+File, -Size}
Unify \arg{Size} with the size of \arg{File} in characters.
\predicate{time_file}{2}{+File, -Time}
Unify the last modification time of \arg{File} with \arg{Time}.
\arg{Time} is a floating point number expressing the seconds elapsed
since Jan~1, 1970. See also convert_time/[2,8] and get_time/1.
\predicate{absolute_file_name}{2}{+File, -Absolute}
Expand a local file-name into an absolute path. The absolute path is
canonised: references to \file{.} and \file{..} are deleted. This
predicate ensures that expanding a file-name it returns the same
absolute path regardless of how the file is addressed. SWI-Prolog uses
absolute file names to register source files independent of the current
working directory. See also absolute_file_name/3. See also
absolute_file_name/3 and expand_file_name/2.
\predicate{absolute_file_name}{3}{+Spec, +Options, -Absolute}
Converts the given file specification into an absolute path.
\arg{Option} is a list of options to guide the conversion:
\begin{description}
\termitem{extensions}{ListOfExtensions}
List of file-extensions to try. Default is \const{''}. For each
extension, absolute_file_name/3 will first add the extension and then
verify the conditions imposed by the other options. If the condition
fails, the next extension of the list is tried. Extensions may be
specified both as \fileext{.ext} or plain \const{ext}.
\termitem{access}{Mode}
Imposes the condition access_file(\arg{File}, \arg{Mode}). \arg{Mode}
is on of \const{read}, \const{write}, \const{append}, \const{exist} or \const{none}. See also access_file/2.
\termitem{file_type}{Type}
Defines extensions. Current mapping: \const{txt} implies \const{['']},
\const{prolog} implies \const{['.pl', '']}, \const{executable} implies
\const{['.so', '']}, \const{qlf} implies \const{['.qlf', '']} and
\const{directory} implies \const{['']}.
\termitem{file_errors}{fail/error}
If \const{error} (default), throw and \const{existence_error} exception
if the file cannot be found. If \const{fail}, stay silent.%
\footnote{Silent operation was the default up to version 3.2.6.}
\termitem{solutions}{first/all}
If \const{first} (default), the predicates leaves no choice-point.
Otherwise a choice-point will be left and backtracking may yield
more solutions.
\end{description}
The prolog-flag \const{verbose_file_search} can be set to \const{true}
to help debugging Prolog's search for files.
\predicate{is_absolute_file_name}{1}{+File}
True if \arg{File} specifies and absolute path-name. On Unix systems,
this implies the path starts with a `/'. For Microsoft based systems
this implies the path starts with \file{<letter>:}. This predicate is
intended to provide platform-independent checking for absolute paths.
See also absolute_file_name/2 and prolog_to_os_filename/2.
\predicate{file_name_extension}{3}{?Base, ?Extension, ?Name}
This predicate is used to add, remove or test filename extensions. The
main reason for its introduction is to deal with different filename
properties in a portable manner. If the file system is case-insensitive,
testing for an extension will be done case-insensitive too. \arg{Extension} may be specified with or without a leading dot (\chr{.}).
If an \arg{Extension} is generated, it will not have a leading dot.
\predicate{expand_file_name}{2}{+WildCard, -List}
Unify \arg{List} with a sorted list of files or directories matching
\arg{WildCard}. The normal Unix wildcard constructs `\const{?}',
`\const{*}', `\const{[\ldots]}' and `\const{\{\ldots\}}' are recognised.
The interpretation of `\const{\{\ldots\}}' is interpreted slightly
different from the C shell (csh(1)). The comma separated argument can be
arbitrary patterns, including `\const{\{\ldots\}}' patterns. The empty
pattern is legal as well: `\file{\{.pl,\}}' matches either `\file{.pl}'
or the empty string.
If the pattern does contains wildcard characters, only existing files
and directories are returned. Expanding a `pattern' without wildcard
characters returns the argument, regardless on whether or not it exists.
Before expanding wildchards, the construct \file{\$\arg{var}} is expanded
to the value of the environment variable \var{var} and a possible
leading \verb$~$ character is expanded to the user's home directory.%
\footnote{On Windows, the home directory is determined as follows:
if the environment variable \env{HOME} exists, this is
used. If the variables \env{HOMEDRIVE} and \env{HOMEPATH}
exist (Windows-NT), these are used. At initialisation,
the system will set the environment variable \env{HOME}
to point to the SWI-Prolog home directory if neither
\env{HOME} nor \env{HOMEPATH} and \env{HOMEDRIVE} are
defined}.
\predicate{prolog_to_os_filename}{2}{?PrologPath, ?OsPath}
Converts between the internal Prolog pathname conventions and the
operating-system pathname conventions. The internal conventions are
Unix and this predicates is equivalent to =/2 (unify) on Unix systems.
On DOS systems it will change the directory-separator, limit the
filename length map dots, except for the last one, onto underscores.
\predicate{read_link}{3}{+File, -Link, -Target}
If \arg{File} points to a symbolic link, unify \arg{Link} with the
value of the link and \arg{Target} to the file the link is pointing to.
\arg{Target} points to a file, directory or non-existing entry in the
file system, but never to a link. Fails if \arg{File} is not a link.
Fails always on systems that do not support symbolic links.
\predicate{tmp_file}{2}{+Base, -TmpName}
Create a name for a temporary file. \arg{Base} is an identifier for
the category of file. The \arg{TmpName} is guaranteed to be unique.
If the system halts, it will automatically remove all created temporary
files.
\predicate{make_directory}{1}{+Directory}
Create a new directory (folder) on the filesystem. Raises an exception
on failure. On Unix systems, the directory is created with default
permissions (defined by the process \jargon{umask} setting).
\predicate{delete_directory}{1}{+Directory}
Delete directory (folder) from the filesystem. Raises an exception on
failure. Please note that in general it will not be possible to delete
a non-empty directory.
\predicate{working_directory}{2}{-Old, +New}
Unify \arg{Old} with an absolute path to the current working directory
and change working directory to \arg{New}. Use the pattern
\term{working_directory}{CWD, CWD} to get the current directory. See
also absolute_file_name/2 and chdir/1.%
\bug{Some of the file-I/O predicates use local filenames.
Changing directory while file-bound streams are open causes
wrong results on telling/1, seeing/1 and current_stream/3}
\predicate{chdir}{1}{+Path}
Compatibility predicate. New code should use working_directory/2.
\end{description}
\section{Multi-threading (alpha code)} \label{sec:threads}
{\bf The features described in this section are only enabled on Unix
systems providing POSIX threads and if the system is configured using
the \longoption{enable-mt}{} option. SWI-Prolog multi-theading support
is experimental and in some areas not safe.}
SWI-Prolog multithreading is based on standard C-language multithreading
support. It is not like {\em ParLog} or other paralel implementations of
the Prolog language. Prolog threads have their own stacks and only share
the Prolog {\em heap}: predicates, records, flags and other global
non-backtrackable data. SWI-Prolog thread support is designed with the
following goals in mind.
\begin{itemlist}
\item[Multi-threaded server applications]
Todays computing services often focus on (internet) server applications.
Such applications often have need for communication between services
and/or fast non-blocking service to multiple concurrent clients. The
shared heap provides fast communication and thread creation is
relatively cheap (A Pentium-II/450 can create and join approx. 10,000
threads per second on Linux 2.2).
\item[Interactive applications]
Interactive applications often need to perform extensive computation.
If such computations are executed in a new thread, the main thread can
process events and allow the user to cancel the ongoing computation.
User interfaces can also use multiple threads, each thread dealing with
input from a distinct group of windows.
\item[Natural integration with foreign code]
Each Prolog thread runs in a C-thread, automatically making them
cooperate with \jargon{MT-safe} foreign-code. In addition, any
foreign thread can create its own Prolog engine for dealing with
calling Prolog from C-code.
\end{itemlist}
\begin{description}
\predicate{thread_create}{3}{:Goal, -Id, +Options}
Create a new Prolog thread (and underlying C-thread) and start it
by executing \arg{Goal}. If the thread is created succesfully, the
thread-identifier of the created thread is unified to \arg{Id}.
\arg{Options} is a list of options. Currently defined options are:
\begin{description}
\termitem{local}{K-Bytes}
Set the limit to which the local stack of this thread may grow. If
omited, the limit of the calling thread is used. See also the
\cmdlineoption{-L} commandline option.
\termitem{global}{K-Bytes}
Set the limit to which the global stack of this thread may grow. If
omited, the limit of the calling thread is used. See also the
\cmdlineoption{-G} commandline option.
\termitem{trail}{K-Bytes}
Set the limit to which the trail stack of this thread may grow. If
omited, the limit of the calling thread is used. See also the
\cmdlineoption{-T} commandline option.
\termitem{argument}{K-Bytes}
Set the limit to which the argument stack of this thread may grow. If
omited, the limit of the calling thread is used. See also the
\cmdlineoption{-A} commandline option.
\termitem{alias}{AliasName}
Associate an `alias-name' with the thread. This named may be used to
refer to the thread and remains valid until the thread is joined
(see thread_join/2).
\termitem{detached}{Bool}
If \const{false} (default), the thread can be waited for using
thread_join/2. thread_join/2 must be called on this thread to reclaim
the all resources associated to the thread. If \const{true}, the system
will reclaim all associated resources automatically after the thread
finishes. Please not that thread identifiers are freed for reuse after a
detached thread finishes or a normal thread has been joined.
\end{description}
The \arg{Goal} argument is {\em copied} to the new Prolog engine. This
implies further instantiation of this term in either thread does not
have consequences for the other thread: Prolog threads do not share
data from their stacks.
\predicate{thread_self}{1}{-Id}
Get the Prolog thread identifier of the running thread. If the thread
has an alias, the alias-name is returned.
\predicate{current_thread}{2}{?Id, ?Status}
Enumerates identifiers and status of all currently known threads.
Calling current_thread/2 does not influence any thread. See also
thread_join/2. For threads that have an alias-name, this name is
returned in \arg{Id} instead of the numerical thread identifier.
\arg{Status} is one of:
\begin{description}
\termitem{running}{}
The thread is running. This is the initial status of a thread. Please
note that threats waiting for something are considered running too.
\termitem{false}{}
The \arg{Goal} of the thread has been completed and failed.
\termitem{true}{}
The \arg{Goal} of the thread has been completed and succeeded.
\termitem{exited}{Term}
The \arg{Goal} of the thread has been terminated using thread_exit/1
with \arg{Term} as argument.
\termitem{exception}{Term}
The \arg{Goal} of the thread has been terminated due to an uncaught
exception (see throw/1 and catch/3).
\end{description}
\predicate{thread_join}{2}{+Id, -Status}
Wait for the termination of thread with given \arg{Id}. Then unify
the result-status (see thread_exit/1) of the thread with \arg{Status}.
After this call, \arg{Id} becomes invalid and all resources associated
with the thread are reclaimed. See also current_thread/2.
A thread that has been completed without thread_join/2 being called on
it is partly reclaimed: the Prolog stacks are released and the C-thread
is destroyed. A small data-structure represening the exit-status of the
thread is retained until thread_join/2 is called on the thread.
\predicate{thread_exit}{1}{+Term}
Terminates the thread immediately, leaving \term{exited}{Term} as
result-state. The Prolog stacks and C-thread are reclaimed.
\predicate{thread_at_exit}{1}{:Goal}
Run \arg{Goal} after the execution of this thread has terminated. This
is to be compared to at_halt/1, but only for the current thread. These
hooks are ran regardless of why the execution of the thread has been
completed. As these hooks are run, the return-code is already available
through current_thread/2.
\end{description}
\subsection{Thread communication}
Prolog threads can exchange data using dynamic predicates, database
records, and other globally shared data. In addition, they can send
messages to each other. If a threads needs to wait for another thread
until that thread has produced some data, using only the database forces
the waiting thread to poll the database continuously. Waiting for a
message suspends the thread execution until the message has arrived
in its message queue.
\begin{description}
\predicate{thread_send_message}{2}{+ThreadId, +Term}
Place \arg{Term} in the message queue of the indicated thread (which can
even be the message queue of itself (see thread_self/1). Any term can
be placed in a message queue, but note that the term is copied to to
receiving thread and variable-bindings are thus lost. This call returns
immediately.
\predicate{thread_get_message}{1}{?Term}
Examines the thread message-queue and if necessary blocks execution
until a term that unifies to \arg{Term} arrives in the queue. After
a term from the queue has been unified unified to \arg{Term}, this
term is deleted from the queue and this predicate returns.
Please note that not-unifying messages remain in the queue. After
the following has been executed, thread 1 has the term \term{b}{gnu}
in its queue and continues execution using \arg{A} is \const{gnat}.
\begin{code}
<thread 1>
thread_get_message(a(A)),
<thread 2>
thread_send_message(b(gnu)),
thread_send_message(a(gnat)),
\end{code}
See also thread_peek_message/1.
\predicate{thread_peek_message}{1}{?Term}
Examines the thread message-queue and compares the queued terms
with \arg{Term} until one unifies or the end of the queue has been
reached. In the first case the call succeeds (possibly instantiating
\arg{Term}. If no term from the queue unifies this call fails.
\predicate{thread_signal}{2}{+ThreadId, :Goal}
Make thread \arg{ThreadId} execute \arg{Goal} at the first
opportunity. In the current implementation, this implies at the first
pass through the \jargon{Call-port}. The predicate thread_signal/2
itself places \arg{Goal} into the signalled-thread's signal queue
and returns immediately.
Signals (interrupts) do not cooperate well with the world of
multi-threading, mainly because the status of mutexes cannot be
guaranteed easily. At the call-port, the Prolog virtual machine
holds no locks and therefore the asynchronous execution is safe.
\arg{Goal} can be any valid Prolog goal, including throw/1 to make
the receiving thread generate an exception and trace/0 to start
tracing the receiving thread.
\end{description}
\subsection{Thread synchronisation}
All internal Prolog operations are thread-safe. This implies two Prolog
threads can operate on the same dynamic predicate without corrupting the
consistency of the predicate. This section deals with user-level
\jargon{mutexes} (called \jargon{monitors} in ADA or
\jargon{critical-sections} by Microsoft). A mutex is a
{\bf MUT}ual {\bf EX}clusive device, which implies at most one thread
can \jargon{hold} a mutex.
Mutexes are used to realise related updates to the Prolog database.
With `related', we refer to the situation where a `transaction' implies
two or more changes to the Prolog database. For example, we have a
predicate address/2, representing the address of a person and we want
to change the address by retracting the old and asserting the new
address. Between these two operations the database is invalid: this
person has either no address or two addresses (depending on the
assert/retract order).
Here is how to realise a correct update:
\begin{code}
:- initialization
mutex_create(addressbook).
change_address(Id, Address) :-
mutex_lock(addressbook),
retractall(address(Id, _)),
asserta(address(Id, Address)),
mutex_unlock(addressbook).
\end{code}
\begin{description}
\predicate{mutex_create}{1}{?MutexId}
Create a mutex. if \arg{MutexId} is an atom, a \jargon{named} mutex is
created. If it is a variable, an anonymous mutex reference is returned.
There is no limit to the number of mutexes that can be created.
\predicate{mutex_destroy}{1}{+MutexId}
Destroy a mutex. After this call, \arg{MutexId} becomes invalid and
further references yield an \except{existence_error} exception.
\predicate{mutex_lock}{1}{+MutexId}
Lock the mutex. Prolog mutexes are \jargon{recursive} mutexes: they
can be locked multiple times by the same thread. Only after unlocking
it as many times as it is locked, the mutex becomes available for
locking by other threads. If another thread has locked the mutex the
calling thread is suspended until to mutex is unlocked.
If \arg{MutexId} is an atom, and there is no current mutex with that
name, the mutex is created automatically using mutex_create/1. This
implies named mutexes need not be declared explicitly.
Please note that locking and unlocking mutexes should be paired
carefully. Especially make sure to unlock mutexes even if the protected
code fails or raises an exception. For most common cases use
with_mutex/2, wich provides a safer way for handling prolog-level
mutexes.
\predicate{mutex_trylock}{1}{+MutexId}
As mutex_lock/1, but if the mutex is held by another thread, this
predicates fails immediately.
\predicate{mutex_unlock}{1}{+MutexId}
Unlock the mutex. This can only be called if the mutex is held by the
calling thread. If this is not the case, a \except{permission_error}
exception is raised.
\predicate{mutex_unlock_all}{0}{}
Unlock all mutexes held by the current thread. This call is especially
useful to handle thread-termination using abort/0 or exceptions. See
also thread_signal/2.
\predicate{current_mutex}{3}{?MutexId, ?ThreadId, ?Count}
Enumerates all existing mutexes. If the mutex is held by some thread,
\arg{ThreadId} is unified with the identifier of te holding thread and
\arg{Count} with the recursive count of the mutex. Otherwise,
\arg{ThreadId} is \const{[]} and \arg{Count} is 0.
\predicate{with_mutex}{2}{+MutexId, :Goal}
Execute \arg{Goal} while holding \arg{MutexId}. If \arg{Goal} leaves
choicepointes, these are destroyed (as in once/1). The mutex is unlocked
regardless of whether \arg{Goal} succeeds, fails or raises an exception.
An exception thrown by \arg{Goal} is re-thrown after the mutex has been
successfully unlocked. See also mutex_create/2.
Although described in the thread-section, this predicate is also
available in the single-threaded version, where it behaves simply as
once/1.
\end{description}
\subsection{Thread-support library(threadutil)}
This library defines a couple of useful predicates for demonstrating and
debugging multi-threaded applications. This library is certainly not
complete.
\begin{description}
\predicate{threads}{0}{}
Lists all current threads and their status. In addition, all `zombie'
threads (finished threads that are not detached, nor waited for) are
joined to reclaim their resources.
\predicate{interactor}{0}{}
Create a new console and run the Prolog toplevel in this new console.
See also attach_console/0.
\predicate{attach_console}{0}{}
If the current thread has no console attached yet, attach one and
redirect the user streams (input, output, and error) to the new console
window. The console is an \program{xterm} application. For this to work,
you should be running X-windows and your xterm should know the
\cmdlineoption{-Sccn}.
This predicate has a couple of useful applications. One is to separate
(debugging) I/O of different threads. Another is to start debugging a
thread that is running in the background. If thread 10 is running, the
following sequence starts the tracer on this thread:
\begin{code}
?- thread_signal(10, (attach_console, trace)).
\end{code}
\end{description}
\subsection{Status of the thread implementation}
It is assumed that the basic Prolog execution is thread-safe. Various
problems are to be expected though, both dead-locks as well as
not-thread-safe code in builtin-predicates.
\section{User Toplevel Manipulation} \label{sec:toplevel}
\begin{description}
\predicate{break}{0}{}
Recursively start a new Prolog top level. This Prolog top level has its
own stacks, but shares the heap with all break environments and the top
level. Debugging is switched off on entering a break and restored on
leaving one. The break environment is terminated by typing the system's
\mbox{end-of-file} character (control-D). If the
\argoption{-t}{toplevel} command line option is given this goal is
started instead of entering the default interactive top level
(prolog/0).
\predicate{abort}{0}{}
Abort the Prolog execution and restart the top level. If the
\argoption{-t}{toplevel} command line options is given this goal is
started instead of entering the default interactive top level.
There are two implementations of abort/0. The default one uses the
exception mechanism (see throw/1), throwing the exception
\const{\$aborted}. The other one uses the C-construct longjmp()
to discard the entire environment and rebuild a new one. Using
exceptions allows for proper recovery of predicates exploiting
exceptions. Rebuilding the environment is safer if the Prolog stacks
are corrupt. Therefore the system will use the rebuild-strategy if
the abort was generated by an internal consistency check and the
exception mechanism otherwise. Prolog can be forced to use the
rebuild-strategy setting the prolog flag \const{abort_with_exception}
to \const{false}.
\predicate{halt}{0}{}
Terminate Prolog execution. Open files are closed and if the command
line option \cmdlineoption{-tty} is not active the terminal status (see Unix
stty(1)) is restored. Hooks may be registered both in Prolog and in
foreign code. Prolog hooks are registered using at_halt/1. halt/0
is equivalent to \exam{halt(0)}.
\predicate{halt}{1}{+Status}
Terminate Prolog execution with given status. Status is an integer.
See also halt/0.
\predicate{prolog}{0}{}
This goal starts the default interactive top level. Queries are read
from the stream \const{user_input}. See also the \const{history}
prolog_flag (current_prolog_flag/2). The prolog/0 predicate is
terminated (succeeds) by typing the end-of-file character (On most
systems control-D).
\end{description}
The following two hooks allow for expanding queries and handling the
result of a query. These hooks are used by the toplevel variable
expansion mechanism described in \secref{topvars}.
\begin{description}
\predicate{expand_query}{4}{+Query, -Expanded, +Bindings, -ExpandedBindings}
Hook in module \const{user}, normally not defined. \arg{Query} and
\arg{Bindings} represents the query read from the user and the names
of the free variables as obtained using read_term/3. If this predicate
succeeds, it should bind \arg{Expanded} and \arg{ExpandedBindings} to
the query and bindings to be executed by the toplevel. This predicate
is used by the toplevel (prolog/0). See also expand_answer/2 and
term_expansion/2.
\predicate{expand_answer}{2}{+Bindings, -ExpandedBindings} Hook in
module \const{user}, normally not defined. Expand the result of a
successfully executed toplevel query. \arg{Bindings} is the query
$<Name>=<Value>$ binding list from the query. \arg{ExpandedBindings}
must be unified with the bindings the toplevel should print.
\end{description}
\section{Creating a Protocol of the User Interaction} \label{sec:protocol}
SWI-Prolog offers the possibility to log the interaction with the user
on a file.%
\footnote{A similar facility was added to Edinburgh C-Prolog by
Wouter Jansweijer.}
All Prolog interaction, including warnings and tracer output, are written
on the protocol file.
\begin{description}
\predicate{protocol}{1}{+File}
Start protocolling on file \arg{File}. If there is already a protocol
file open then close it first. If \arg{File} exists it is truncated.
\predicate{protocola}{1}{+File}
Equivalent to protocol/1, but does not truncate the \arg{File} if it
exists.
\predicate{noprotocol}{0}{}
Stop making a protocol of the user interaction. Pending output is
flushed on the file.
\predicate{protocolling}{1}{-File}
Succeeds if a protocol was started with protocol/1 or protocola/1 and
unifies \arg{File} with the current protocol output file.
\end{description}
\section{Debugging and Tracing Programs} \label{sec:debugger}
This section is a reference to the debugger interaction predicates. A
more use-oriented overview of the debugger is in \secref{debugoverview}.
If you have installed XPCE, you can use the graphical frontend of the
tracer. This frontend is installed using the predicate guitracer/0.
\begin{description}
\predicate{trace}{0}{}
Start the tracer. trace/0 itself cannot be seen in the tracer. Note that
the Prolog toplevel treats trace/0 special; it means `trace the next goal'.
\predicate{tracing}{0}{}
Succeeds when the tracer is currently switched on. tracing/0 itself can
not be seen in the tracer.
\predicate{notrace}{0}{}
Stop the tracer. notrace/0 itself cannot be seen in the tracer.
\predicate{guitracer}{0}{}
Installs hooks (see prolog_trace_interception/4) into the system that
redirects tracing information to a GUI frontend providing structured
access to variable-bindings, graphical overview of the stack and
highlighting of relevant source-code.
\predicate{noguitracer}{0}{}
Reverts back to the textual tracer.
\predicate{trace}{1}{+Pred}
Equivalent to \exam{trace(\arg{Pred}, +all)}.
\predicate{trace}{2}{+Pred, +Ports}
Put a trace-point on all predicates satisfying the predicate specification
\arg{Pred}. \arg{Ports} is a list of portnames (\const{call},
\const{redo}, \const{exit}, \const{fail}). The atom \const{all} refers
to all ports. If the port is preceded by a \const{-} sign the
trace-point is cleared for the port. If it is preceded by a \const{+}
the trace-point is set.
The predicate trace/2 activates debug mode (see debug/0). Each time
a port (of the 4-port model) is passed that has a trace-point set the
goal is printed as with trace/0. Unlike trace/0 however, the execution
is continued without asking for further information. Examples:
\begin{center}
\begin{tabular}{lp{3in}}
\exam{?- trace(hello).} & Trace all ports of hello with any arity
in any module. \\
\exam{?- trace({foo}/2, +fail).} & Trace failures of {foo}/2 in any module. \\
\exam{?- trace({bar}/1, -all).} & Stop tracing {bar}/1.
\end{tabular}
\end{center}
The predicate debugging/0 shows all currently defined trace-points.
\predicate{notrace}{1}{+Goal}
Call \arg{Goal}, but suspend the debugger while \arg{Goal} is executing.
The current implementation cuts the choicepoints of \arg{Goal} after
successful completion. See once/1. Later implementations may have the
same semantics as call/1.
\predicate{debug}{0}{}
Start debugger. In debug mode, Prolog stops at spy- and trace-points,
disables tail-recursion optimisation and aggressive destruction of
choice-points to make debugging information accessible. Implemented
by the Prolog flag \plflag{debug}.
\predicate{nodebug}{0}{}
Stop debugger. Implementated by the prolog flag \plflag{debug}. See
also debug/0.
\predicate{debugging}{0}{}
Print debug status and spy points on current output stream. See also
the prolog flag \plflag{debug}.
\predicate{spy}{1}{+Pred}
Put a spy point on all predicates meeting the predicate specification
\arg{Pred}. See \secref{listing}.
\predicate{nospy}{1}{+Pred}
Remove spy point from all predicates meeting the predicate specification
\arg{Pred}.
\predicate{nospyall}{0}{}
Remove all spy points from the entire program.
\predicate{leash}{1}{?Ports}
Set/query leashing (ports which allow for user interaction). \arg{Ports} is
one of \arg{+Name}, \arg{-Name}, \arg{?Name} or a list of these.
\arg{+Name} enables leashing on that port, \arg{-Name} disables it and
\arg{?Name} succeeds or fails according to the current setting.
Recognised ports are: \const{call}, \const{redo}, \const{exit}, \const{fail} and
\const{unify}. The special shorthand \const{all} refers to all ports,
\const{full} refers to all ports except for the unify port (default).
\const{half} refers to the \const{call}, \const{redo} and \const{fail}
port.
\predicate{visible}{1}{+Ports}
Set the ports shown by the debugger. See leash/1 for a description of
the port specification. Default is \const{full}.
\predicate{unknown}{2}{-Old, +New}
Edinburgh-prolog compatibility predicate, interfacing to the ISO prolog
flag \plflag{unknown}. Values are \const{trace} (meaning \const{error})
and \const{fail}. If the \plflag{unknown} flag is set to
\const{warning}, unknown/2 reports the value as \const{trace}.
\predicate{style_check}{1}{+Spec}
Set style checking options. \arg{Spec} is either \mbox{\tt +<option>},
\mbox{\tt -<option>}, \mbox{\tt ?<option>} or a list of such options.
\mbox{\tt +<option>} sets a style checking option, \mbox{\tt -<option>} clears
it and \mbox{\tt ?<option>} succeeds or fails according to the current
setting. consult/1 and derivatives resets the style checking options to
their value before loading the file. If---for example---a file containing
long atoms should be loaded the user can start the file with:
\begin{code}
:- style_check(-atom).
\end{code}
Currently available options are:
\begin{center}
\begin{tabular}{|l|c|p{3.5in}|}
\hline
Name & Default & Description \\
\hline
\const{singleton} & on & read_clause/1 (used by consult/1) warns
on variables only appearing once in a term (clause)
which have a name not starting with an underscore. \\
\const{atom} & on & read/1 and derivatives will produce an
error message on quoted atoms or strings longer
than 5 lines. \\
\const{dollar} & off & Accept dollar as a lower case character, thus
avoiding the need for quoting atoms with dollar signs.
System maintenance use only. \\
\const{discontiguous} & on & Warn if the clauses for a predicate are not
together in the same source file. \\
\const{string} & off & Backward compatibility. See the prolog-flag
\const{double_quotes} (current_prolog_flag/2). \\
\hline
\end{tabular}
\end{center}
\end{description}
\section{Obtaining Runtime Statistics} \label{sec:statistics}
\begin{description}
\predicate{statistics}{2}{+Key, -Value}
Unify system statistics determined by \arg{Key} with \arg{Value}. The
possible keys are given in the \tabref{statistics}. The last part of
the table contains keys for compatibility to other Prolog implementations
(Quintus) for improved portability. Note that the ISO standard does not
define methods to collect system statistics.
\begin{table}
\begin{center}
\begin{tabular}{|l|p{4in}|}
\hline
agc & Number of atom garbage-collections performed \\
agc_gained & Number of atoms removed \\
agc_time & Time spent in atom garbage-collections \\
cputime & (User) {\sc cpu} time since Prolog was started in seconds \\
inferences & Total number of passes via the call and redo ports
since Prolog was started. \\
heap & Estimated total size of the heap (see \secref{heap}) \\
heapused & Bytes heap in use by Prolog. \\
heaplimit & Maximum size of the heap (see \secref{heap}) \\
local & Allocated size of the local stack in bytes. \\
localused & Number of bytes in use on the local stack. \\
locallimit & Size to which the local stack is allowed to grow \\
global & Allocated size of the global stack in bytes. \\
globalused & Number of bytes in use on the global stack. \\
globallimit & Size to which the global stack is allowed to grow \\
trail & Allocated size of the trail stack in bytes. \\
trailused & Number of bytes in use on the trail stack. \\
traillimit & Size to which the trail stack is allowed to grow \\
atoms & Total number of defined atoms. \\
functors & Total number of defined name/arity pairs. \\
predicates & Total number of predicate definitions. \\
modules & Total number of module definitions. \\
codes & Total amount of byte codes in all clauses. \\
threads & MT-version: number of active threads \\
threads_created & MT-version: number of created threads \\
threads_cputime & MT-version: seconds CPU time used by finished threads \\
\hline
\multicolumn{2}{|c|}{Compatibility keys} \\
\hline
runtime & [ CPU time, CPU time since last ]
(milliseconds) \\
system_time & [ System CPU time, System CPU time since last ]
(milliseconds)\\
real_time & [ Wall time, Wall time since last ] (seconds since 1970) \\
memory & [ Total unshared data, free memory ]
(Uses getrusage() if available, otherwise incomplete own
statistics. \\
stacks & [ global use, local use ] \\
program & [ heap, 0 ] \\
global_stack & [ global use, global free ] \\
local_stack & [ local use, local free ] \\
trail & [ trail use, 0 ] \\
garbage_collection & [ number of GC, bytes gained, time spent ] \\
stack_shifts & [ global shifts, local shifts, time spent ]
(fails if no shifter in this version) \\
atoms & [ number, memory use, 0 ] \\
atom_garbage_collection &
[ number of AGC, bytes gained, time spent ] \\
core & Same as memory \\
\hline
\end{tabular}
\end{center}
\caption{Keys for statistics/2}
\label{tab:statistics}
\end{table}
\predicate{statistics}{0}{}
Display a table of system statistics on the current output stream.
\predicate{time}{1}{+Goal}
Execute \arg{Goal} just like once/1 (i.e., leaving no choice points),
but print used time, number of logical inferences and the average
number of \arg{lips} (logical inferences per second). Note that
SWI-Prolog counts the actual executed number of inferences rather than
the number of passes through the call- and redo ports of the
theoretical 4-port model.
\end{description}
\section{Finding Performance Bottlenecks} \label{sec:profile}
SWI-Prolog offers a statistical program profiler similar to Unix prof(1)
for C and some other languages. A profiler is used as an aid to find
performance pigs in programs. It provides information on the time spent
in the various Prolog predicates.
The profiler is based on the assumption that if we monitor the functions
on the execution stack on time intervals not correlated to the program's
execution the number of times we find a procedure on the environment
stack is a measure of the time spent in this procedure. It is
implemented by calling a procedure each time slice Prolog is active.
This procedure scans the local stack and either just counts the
procedure on top of this stack (\const{plain} profiling) or all procedures
on the stack (\const{cumulative} profiling). To get accurate results
each procedure one is interested in should have a reasonable number of
counts. Typically a minute runtime will suffice to get a rough overview
of the most expensive procedures.
\begin{description}
\predicate{profile}{3}{+Goal, +Style, +Number}
Execute \arg{Goal} just like time/1. Collect profiling statistics
according to style (see profiler/2) and show the top \arg{Number}
procedures on the current output stream (see show_profile/1). The
results are kept in the database until reset_profiler/0 or profile/3
is called and can be displayed again with show_profile/1. profile/3
is the normal way to invoke the profiler. The predicates below
are low-level predicates that can be used for special cases.
\predicate{show_profile}{1}{+Number}
Show the collected results of the profiler. Stops the profiler first to
avoid interference from show_profile/1. It shows the top \arg{Number}
predicates according the percentage {\sc cpu}-time used.%
\footnote{show_profile/1 is defined in Prolog and takes a
considerable amount of memory.}
\predicate{profiler}{2}{-Old, +New}
Query or change the status of the profiler. The status is one of
\const{off}, \const{plain} or \const{cumulative}. \const{plain} implies the
time used by children of a predicate is not added to the time of the
predicate. For status \const{cumulative} the time of children is added
(except for recursive calls). Cumulative profiling implies the stack
is scanned up to the top on each time slice to find all active
predicates. This implies the overhead grows with the number of active
frames on the stack. Cumulative profiling starts debugging mode
to disable tail recursion optimisation, which would otherwise
remove the necessary parent environments. Switching status from
\const{plain} to \const{cumulative} resets the profiler. Switching to and
from status \const{off} does not reset the collected statistics, thus
allowing to suspend profiling for certain parts of the program.
\predicate{reset_profiler}{0}{}
Switches the profiler to \const{off} and clears all collected statistics.
\predicate{profile_count}{3}{+Head, -Calls, -Promilage}
Obtain profile statistics of the predicate specified by \arg{Head}.
\arg{Head} is an atom for predicates with arity 0 or a term with the
same name and arity as the predicate required (see
current_predicate/2). \arg{Calls} is unified with the number of `calls'
and `redos' while the profiler was active. \arg{Promilage} is unified
with the relative number of counts the predicate was active
(\const{cumulative}) or on top of the stack (\const{plain}). \arg{Promilage}
is an integer between 0 and 1000.
\end{description}
\section{Memory Management} \label{sec:memory}
Note: limit_stack/2 and trim_stacks/0 have no effect on machines that do
not offer dynamic stack expansion. On these machines these predicates
simply succeed to improve portability.
\begin{description}
\predicate{garbage_collect}{0}{}
Invoke the global- and trail stack garbage collector. Normally the
garbage collector is invoked automatically if necessary. Explicit
invocation might be useful to reduce the need for garbage collections in
time critical segments of the code. After the garbage collection
trim_stacks/0 is invoked to release the collected memory resources.
\predicate{garbage_collect_atoms}{0}{}
Reclaim unused atoms. Normally invoked after \const{agc_margin}
(a prolog flag) atoms have been created.
\predicate{limit_stack}{2}{+Key, +Kbytes}
Limit one of the stack areas to the specified value. \arg{Key} is one of
\const{local}, \const{global} or \const{trail}. The limit is an integer,
expressing the desired stack limit in K bytes. If the desired limit is
smaller than the currently used value, the limit is set to the nearest
legal value above the currently used value. If the desired value is
larger than the maximum, the maximum is taken. Finally, if the desired
value is either 0 or the atom \const{unlimited} the limit is set to its
maximum. The maximum and initial limit is determined by the command line
options \cmdlineoption{-L}, \cmdlineoption{-G} and \cmdlineoption{-T}.
\predicate{trim_stacks}{0}{}
Release stack memory resources that are not in use at this moment,
returning them to the operating system. Trim stack is a relatively
cheap call. It can be used to release memory resources in a
backtracking loop, where the iterations require typically seconds of
execution time and very different, potentially large, amounts of
stack space. Such a loop should be written as follows:
\begin{code}
loop :-
generator,
trim_stacks,
potentially_expensive_operation,
stop_condition, !.
\end{code}
The prolog top level loop is written this way, reclaiming memory
resources after every user query.
\predicate{stack_parameter}{4}{+Stack, +Key, -Old, +New}
Query/set a parameter for the runtime stacks. \arg{Stack} is one
of \const{local}, \const{global}, \const{trail} or \const{argument}.
The table below describes the \arg{Key}/\arg{Value} pairs. Old is first
unified with the current value.
\begin{center}
\begin{tabular}{|l|l|}
\hline
\const{limit} & Maximum size of the stack in bytes \\
\const{min_free} & Minimum free space at entry of foreign predicate \\
\hline
\end{tabular}
\end{center}
This predicate is currently only available on versions that use the
stack-shifter to enlarge the runtime stacks when necessary. It's
definition is subject to change.
\end{description}
\section{Windows DDE interface} \label{sec:DDE}
The predicates in this section deal with MS-Windows `Dynamic Data
Exchange' or DDE protocol.%
\footnote{This interface is contributed by Don Dwiggins.}
A Windows DDE conversation is a form of interprocess communication
based on sending reserved window-events between the communicating
processes.
See also \secref{DLL} for loading Windows DLL's into SWI-Prolog.
\subsection{DDE client interface}
The DDE client interface allows Prolog to talk to DDE server programs.
We will demonstrate the use of the DDE interface using the Windows
PROGMAN (Program Manager) application:
\begin{code}
1 ?- open_dde_conversation(progman, progman, C).
C = 0
2 ?- dde_request(0, groups, X)
--> Unifies X with description of groups
3 ?- dde_execute(0, '[CreateGroup("DDE Demo")]').
Yes
4 ?- close_dde_conversation(0).
Yes
\end{code}
For details on interacting with \program{progman}, use the SDK online
manual section on the Shell DDE interface. See also the Prolog
\file{library(progman)}, which may be used to write simple Windows setup
scripts in Prolog.
\begin{description}
\predicate{open_dde_conversation}{3}{+Service, +Topic, -Handle}
Open a conversation with a server supporting the given service name and
topic (atoms). If successful, \arg{Handle} may be used to send
transactions to the server. If no willing server is found this
predicate fails silently.
\predicate{close_dde_conversation}{1}{+Handle}
Close the conversation associated with \arg{Handle}. All opened
conversations should be closed when they're no longer needed, although
the system will close any that remain open on process termination.
\predicate{dde_request}{3}{+Handle, +Item, -Value}
Request a value from the server. \arg{Item} is an atom that identifies
the requested data, and \arg{Value} will be a string (\const{CF_TEXT} data
in DDE parlance) representing that data, if the request is successful.
If unsuccessful, \arg{Value} will be unified with a term of form
\mbox{\tt error(<Reason>)}, identifying the problem. This call uses
SWI-Prolog string objects to return the value rather then atoms to
reduce the load on the atom-space. See \secref{strings} for
a discussion on this data type.
\predicate{dde_execute}{2}{+Handle, +Command}
Request the DDE server to execute the given command-string. Succeeds
if the command could be executed and fails with error message otherwise.
\predicate{dde_poke}{4}{+Handle, +Item, +Command}
Issue a \const{POKE} command to the server on the specified \arg{Item}.
Command is passed as data of type \const{CF_TEXT}.
\end{description}
\subsection{DDE server mode}
The (autoload) \file{library(dde)} defines primitives to realise simple
DDE server applications in SWI-Prolog. These features are provided as
of version 2.0.6 and should be regarded prototypes. The C-part of
the DDE server can handle some more primitives, so if you need features
not provided by this interface, please study \file{library(dde)}.
\begin{description}
\predicate{dde_register_service}{2}{+Template, +Goal}
Register a server to handle DDE request or DDE execute requests from
other applications. To register a service for a DDE request, \arg{Template} is of the form:
\begin{quote}
+Service(+Topic, +Item, +Value)
\end{quote}
\arg{Service} is the name of the DDE service provided (like
\program{progman} in the client example above). \arg{Topic} is either an
atom, indicating \arg{Goal} only handles requests on this topic or a
variable that also appears in \arg{Goal}. \arg{Item} and \arg{Value} are
variables that also appear in \arg{Goal}. \arg{Item} represents the
request data as a Prolog atom.%
\footnote{Upto version 3.4.5 this was a list of character codes.
As recent versions have atom garbage collection there is
no need for this anymore.}
The example below registers the Prolog current_prolog_flag/2 predicate
to be accessible from other applications. The request may be given from
the same Prolog as well as from another application.
\begin{code}
?- dde_register_service(prolog(current_prolog_flag, F, V),
current_prolog_flag(F, V)).
?- open_dde_conversation(prolog, current_prolog_flag, Handle),
dde_request(Handle, home, Home),
close_dde_conversation(Handle).
Home = '/usr/local/lib/pl-2.0.6/'
\end{code}
Handling DDE \const{execute} requests is very similar. In this case the
template is of the form:
\begin{quote}
+Service(+Topic, +Item)
\end{quote}
Passing a \arg{Value} argument is not needed as execute requests either
succeed or fail. If \arg{Goal} fails, a `not processed' is passed back
to the caller of the DDE request.
\predicate{dde_unregister_service}{1}{+Service}
Stop responding to \arg{Service}. If Prolog is halted, it will
automatically call this on all open services.
\predicate{dde_current_service}{2}{-Service, -Topic}
Find currently registered services and the topics served on them.
\predicate{dde_current_connection}{2}{-Service, -Topic}
Find currently open conversations.
\end{description}
\section{Miscellaneous} \label{sec:miscpreds}
\begin{description}
\predicate{dwim_match}{2}{+Atom1, +Atom2}
Succeeds if \arg{Atom1} matches \arg{Atom2} in `Do What I Mean' sense.
Both \arg{Atom1} and \arg{Atom2} may also be integers or floats.
The two atoms match if:
\begin{shortlist}
\item They are identical
\item They differ by one character (spy $\equiv$ spu)
\item One character is inserted/deleted (debug $\equiv$ deug)
\item Two characters are transposed (trace $\equiv$ tarce)
\item `Sub-words' are glued differently (existsfile $\equiv$ existsFile $\equiv$ exists_file)
\item Two adjacent sub words are transposed (existsFile $\equiv$ fileExists)
\end{shortlist}
\predicate{dwim_match}{3}{+Atom1, +Atom2, -Difference}
Equivalent to dwim_match/2, but unifies \arg{Difference} with an atom
identifying the the difference between \arg{Atom1} and \arg{Atom2}. The
return values are (in the same order as above): \const{equal},
\const{mismatched_char}, \const{inserted_char}, \const{transposed_char},
\const{separated} and \const{transposed_word}.
\predicate{wildcard_match}{2}{+Pattern, +String}
Succeeds if \arg{String} matches the wildcard pattern \arg{Pattern}.
\arg{Pattern} is very similar the the Unix csh pattern matcher. The
patterns are given below:
\begin{center}\begin{tabular}{ll}
\const{?} & Matches one arbitrary character. \\
\const{*} & Matches any number of arbitrary characters. \\
\const{[\ldots]} & Matches one of the characters specified between the
brackets. \\
& \mbox{\tt <char1>-<char2>} indicates a range. \\
\const{\{\ldots\}} & Matches any of the patterns of the comma separated
list between the braces.
\end{tabular}\end{center}
Example:
\begin{code}
?- wildcard_match('[a-z]*.{pro,pl}[%~]', 'a_hello.pl%').
Yes
\end{code}
\predicate{gensym}{2}{+Base, -Unique}
Generate a unique atom from base \arg{Base} and unify it with \arg{Unique}.
\arg{Base} should be an atom. The first call will return \mbox{<base>1},
the next \mbox{<base>2}, etc. Note that this is no warrant that the atom
is unique in the system.%
\bug{I plan to supply a real gensym/2 which does give this warrant for
future versions.}
\predicate{sleep}{1}{+Time}
Suspend execution \arg{Time} seconds. \arg{Time} is either a floating
point number or an integer. Granularity is dependent on the system's
timer granularity. A negative time causes the timer to return
immediately. On most non-realtime operating systems we can only ensure
execution is suspended for {\bf at least} \arg{Time} seconds.
\end{description}
|