Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: 0bd3785059
Fetching contributors…

Cannot retrieve contributors at this time

file 5693 lines (5534 sloc) 211.812 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title>Clojure - Functional Programming for the JVM</title>
    <style type="text/css">
            body {
                color: rgb(0, 0, 0);
                background-color: rgb(255, 255, 255);
                font-family: Verdana, sans-serif;
                margin-left: 0.25in;
                margin-right: 0.25in;
            }
            a:hover {
                color: rgb(0, 0, 255);
                background-color: rgb(255, 253, 160);
            }
            code {
                font-family: "Courier New", monospace;
            }
            div.center {
                text-align: center;
            }
            h1 {
                text-align: center;
            }
            h2 {
                text-align: left;
            }
            h3 {
                text-align: left;
            }
            hr {
                height: 1px;
                color: rgb(122, 96, 86);
                background-color: transparent;
            }
            p {
                text-align: justify;
            }
            p.author {
                text-align: center;
            }
            p.footer {
                text-align: justify;
            }
            pre {
                font-family: "Courier New", monospace;
            }
            .educationquicklinks {
                text-align: center;
            }
            .quicklinks {
                text-align: right;
            }
            .red {
                color: rgb(255, 0, 0);
                background-color: rgb(255, 255, 255);
            }
            .green {
                color: rgb(0, 128, 0);
                background-color: rgb(255, 255, 255);
            }
            .blue {
                color: rgb(0, 0, 192);
                background-color: rgb(255, 255, 255);
            }
            .code {
                background-color: #FFFFF0;
                border: dashed black 1px;
                padding-left: 10px;
            }
    </style>
  </head>
  <body>
    <div class="quicklinks">
      <a href="http://www.ociweb.com">Home</a> |
      <a href="http://www.ociweb.com/articles/publications/jnb.html/">Java News Brief Archive</a> |
      <a href="http://www.ociweb.com/education/">OCI Educational Services</a>
    </div>
    <table width="100%" border="0" cellpadding="0" cellspacing="0">
      <tr>
        <td>
          <img alt="" src="images/OCILogo.png" width="180" height="120"/>
        </td>
        <td>
          <img alt="" src="images/MarchJavaNewsBriefLeft.png" width="10" height="58"/>
        </td>
        <td style="width:100%">
          <img alt="" src="images/MarchJavaNewsBriefMiddle.png" width="100%" height="58"/>
        </td>
        <td>
          <img alt="" src="images/MarchJavaNewsBriefRight.png" width="278" height="58"/>
        </td>
      </tr>
    </table>
    <div>
      <hr />
      <img alt="" src="images/MarchTechnicalInsightoftheMonth.png" width="377" height="34"/>
    </div>

    <h1>Clojure - Functional Programming for the JVM</h1>
    <p class="author">
      by<br />
      <a href="http://www.ociweb.com/mark/" onclick="window.open(this.href,'_blank');return false;" title="Author Bio">R. Mark Volkmann</a>,
      Partner <br />Object Computing, Inc. (OCI)<br />
      last updated on 7/22/12
    </p>
    
    <p style="text-align:center">
      <img src="images/clojure.png" alt="Clojure logo" width="400px"/>
    </p>
    <h2>Contents</h2>
    <table border="1">
      <tr>
        <td colspan="1" rowspan="1" style="padding:5px">
<a href="#Intro">Introduction</a>
</td>
        <td colspan="1" rowspan="1" style="padding:5px">
<a href="#ConditionalProcessing">Conditional Processing</a>
</td>
        <td colspan="1" rowspan="1" style="padding:5px">
<a href="#ReferenceTypes">Reference Types</a>
</td>
      </tr>
      <tr>
        <td colspan="1" rowspan="1" style="padding:5px">
<a href="#FP">Functional Programming</a>
</td>
        <td colspan="1" rowspan="1" style="padding:5px">
<a href="#Iteration">Iteration</a>
</td>
        <td colspan="1" rowspan="1" style="padding:5px">
<a href="#Compiling">Compiling</a>
</td>
      </tr>
      <tr>
        <td colspan="1" rowspan="1" style="padding:5px">
<a href="#Overview">Clojure Overview</a>
</td>
        <td colspan="1" rowspan="1" style="padding:5px">
<a href="#Recursion">Recursion</a>
</td>
        <td colspan="1" rowspan="1" style="padding:5px">
<a href="#Testing">Automated Testing</a>
</td>
      </tr>
      <tr>
        <td colspan="1" rowspan="1" style="padding:5px">
<a href="#GettingStarted">Getting Started</a>
</td>
        <td colspan="1" rowspan="1" style="padding:5px">
<a href="#Predicates">Predicates</a>
</td>
        <td colspan="1" rowspan="1" style="padding:5px">
<a href="#EditorsIDEs">Editors and IDEs</a>
</td>
      </tr>
      <tr>
        <td colspan="1" rowspan="1" style="padding:5px">
<a href="#Syntax">Clojure Syntax</a>
</td>
        <td colspan="1" rowspan="1" style="padding:5px">
<a href="#Sequences">Sequences</a>
</td>
        <td colspan="1" rowspan="1" style="padding:5px">
<a href="#DesktopApps">Desktop Applications</a>
</td>
      </tr>
      <tr>
        <td colspan="1" rowspan="1" style="padding:5px">
<a href="#REPL">REPL</a>
</td>
        <td colspan="1" rowspan="1" style="padding:5px">
<a href="#IO">Input/Output</a>
</td>
        <td colspan="1" rowspan="1" style="padding:5px">
<a href="#WebApps">Web Applications</a>
</td>
      </tr>
      <tr>
        <td colspan="1" rowspan="1" style="padding:5px">
<a href="#Vars">Vars</a>
</td>
        <td colspan="1" rowspan="1" style="padding:5px">
<a href="#Destructuring">Destructuring</a>
</td>
        <td colspan="1" rowspan="1" style="padding:5px">
<a href="#Databases">Databases</a>
</td>
      </tr>
      <tr>
        <td colspan="1" rowspan="1" style="padding:5px">
<a href="#Collections">Collections</a>
</td>
        <td colspan="1" rowspan="1" style="padding:5px">
<a href="#Namespaces">Namespaces</a>
</td>
        <td colspan="1" rowspan="1" style="padding:5px">
<a href="#Libraries">Libraries</a>
</td>
      </tr>
      <tr>
        <td colspan="1" rowspan="1" style="padding:5px">
<a href="#StructMaps">StructMaps</a>
</td>
        <td colspan="1" rowspan="1" style="padding:5px">
<a href="#Metadata">Metadata</a>
</td>
        <td colspan="1" rowspan="1" style="padding:5px">
<a href="#Conclusion">Conclusion</a>
</td>
      </tr>
      <tr>
        <td colspan="1" rowspan="1" style="padding:5px">
<a href="#DefiningFunctions">Defining Functions</a>
</td>
        <td colspan="1" rowspan="1" style="padding:5px">
<a href="#Macros">Macros</a>
</td>
        <td colspan="1" rowspan="1" style="padding:5px">
<a href="#References">References</a>
</td>
      </tr>
      <tr>
        <td colspan="1" rowspan="1" style="padding:5px">
<a href="#JavaInterop">Java Interoperability</a>
</td>
        <td colspan="1" rowspan="1" style="padding:5px">
<a href="#Concurrency">Concurrency</a>
</td>
        <td colspan="1" rowspan="1" style="padding:5px">&nbsp;</td>
      </tr>
    </table>

    <h2><a name="Intro">Introduction</a></h2>
    <p>
      The goal of this article is to provide a fairly comprehensive
      introduction to the Clojure programming language.
      A large number of features are covered, each in a fairly brief manner.
      Feel free to skip around to the sections of most interest.
      The section names in the table of contents are hyperlinks
      to make this easier when reading on-line.
    </p>
    <p>
      Please send feedback on errors and ways to improve explanations to
      <a href="mailto:mark@ociweb.com">mark@ociweb.com</a>, or fork
      <a href="https://github.com/mvolkmann/Clojure-Article">the repository</a>
      and send a pull-request.
      I'm especially interested in feedback such as:
    </p>
    <ul>
      <li>You said X, but the correct thing to say is Y.</li>
      <li>You said X, but it would be more clear if you said Y.</li>
      <li>You didn't discuss X and I think it is an important topic.</li>
    </ul>
    <p>
      Updates to this article that indicate the "last updated" date
      and provide a dated list of changes will be provided at
      <a href="http://www.ociweb.com/mark/clojure/">http://www.ociweb.com/mark/clojure/</a>.
      Also see my article on software transactional memory
      and the Clojure implementation of it at
      <a href="http://www.ociweb.com/mark/stm/">http://www.ociweb.com/mark/stm/</a>.
    </p>
    <p>
      Code examples in this article often show
      the return value of a function call or its output
      in a line comment (begins with a semicolon)
      followed by "-&gt;" and the result.
      For example:
    </p>
    <div class="code">
<pre xml:space="preserve">
(+ 1 2) ; showing return value -&gt; 3
(println "Hello") ; return value is nil, showing output -&gt; Hello
</pre>
</div>

    <h2><a name="FP">Functional Programming</a></h2>
    <p>
      <a href="http://en.wikipedia.org/wiki/Functional_programming">Functional programming</a>
      is a style of programming that emphasizes
      "first-class" functions that are "pure".
      It was inspired by ideas from the
      <a href="http://en.wikipedia.org/wiki/Lambda_calculus">lambda calculus</a>.
    </p>
    <p>
      "Pure functions" are functions that
      always return the same result when passed the same arguments,
      as opposed to depending on state that can change with time.
      This makes them much easier to understand, debug and test.
      They have no side effects such as changing global state or
      performing any kind of I/O, including file I/O and database updates.
      State is maintained in the values of function parameters
      saved on the stack (often placed there by recursive calls)
      rather than in global variables saved on the heap.
      This allows functions to be executed repeatedly
      without affecting global state (an important characteristic
      to consider when transactions are discussed later).
      It also opens the door for smart compilers to improve performance
      by automatically reordering and parallelizing code,
      although the latter is not yet common.
    </p>
    <p>
      In practice, applications need to have some side effects.
      Simon Peyton-Jones, a major contributor to the
      functional programming language Haskell, said the following:
      "In the end, any program must manipulate state.
       A program that has no side effects whatsoever is a kind of black box.
       All you can tell is that the box gets hotter."
       (<a href="http://oscon.blip.tv/file/324976">http://oscon.blip.tv/file/324976</a>)
      The key is to limit side effects, clearly identify them,
      and avoid scattering them throughout the code.
    </p>
    <p>
      Languages that support "first-class functions" allow functions to be
      held in variables, passed to other functions and returned from them.
      The ability to return a function supports
      selection of behavior to be executed later.
      Functions that accept other functions as arguments are called
      "higher-order functions". In a sense, their operation is
      configured by the functions that are passed to them.
      The functions passed in can be executed any number of times,
      including not at all.
    </p>
    <p>
      Data in functional programming languages is typically immutable.
      This allows data to be accessed concurrently
      from multiple threads without locking.
      There's no need to lock data that can't be changed.
      With multicore processors becoming prevalent,
      this simplification of programming for concurrency
      is perhaps the biggest benefit of functional programming.
    </p>
    <p>
      If all of this sounds intriguing and
      you're ready to try functional programming,
      be prepared for a sizable learning curve.
      Many claim that functional programming isn't more difficult
      than object-oriented programming, it's just different.
      Taking the time to learn this style of programming
      is a worthwhile investment in order to
      obtain the benefits described above.
    </p>
    <p>
      Popular functional programming languages include
      <a href="http://clojure.org/">Clojure</a>,
      <a href="http://en.wikipedia.org/wiki/Common_Lisp">Common Lisp</a>,
      <a href="http://erlang.org/">Erlang</a>,
      <a href="http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/default.aspx">F#</a>,
      <a href="http://www.haskell.org/">Haskell</a>,
      <!--a href="http://en.wikipedia.org/wiki/Lisp_(programming_language)">Lisp</a>,-->
      <a href="http://en.wikipedia.org/wiki/ML_(programming_language)">ML</a>,
      <a href="http://caml.inria.fr/ocaml/index.en.html">OCaml</a>,
      <a href="http://en.wikipedia.org/wiki/Scheme_(programming_language)">Scheme</a> and
      <a href="http://www.scala-lang.org/">Scala</a>.
      Clojure and Scala were written to
      run on the Java Virtual Machine (JVM).
      Other functional programming languages that have implementations
      that run on the JVM include:
      <a href="http://common-lisp.net/project/armedbear/">Armed Bear Common Lisp (ABCL)</a>,
      <a href="http://ocamljava.x9c.fr/">OCaml-Java</a> and
      <a href="http://www.gnu.org/software/kawa/">Kawa (Scheme)</a>.
    </p>
    
    <h2><a name="Overview">Clojure Overview</a></h2>
    <p>
      Clojure is a dynamically-typed, functional programming language
      that runs on the JVM (Java 5 or greater)
      and provides interoperability with Java.
      A major goal of the language is to make it easier to implement
      applications that access data from multiple threads (concurrency).
    </p>
    <p>
      Clojure is pronounced the same as the word "closure".
      The creator of the language, Rich Hickey, explains the name this way:
      "I wanted to involve C (C#), L (Lisp) and J (Java).
      Once I came up with Clojure, given the pun on closure,
      the available domains and vast emptiness of the googlespace,
      it was an easy decision."
    </p>
    <p>
      Soon Clojure will also be available for the .NET platform.
      ClojureCLR is an implementation of Clojure that runs on the
      Microsoft Common Language Runtime instead of the JVM.
      At the time of this writing it is considered to be alpha quality.
    </p>
    <p>
      In July 2011, ClojureScript was announced.
      It compiles Clojure code to JavaScript. See
      <a href="https://github.com/clojure/clojurescript">https://github.com/clojure/clojurescript</a>.
    </p>
    <p>
      Clojure is an open source language released under the
      <a href="http://www.eclipse.org/legal/epl-v10.html">Eclipse Public License v 1.0</a> (EPL).
      This is a very liberal license.
      See <a href="http://www.eclipse.org/legal/eplfaq.php">http://www.eclipse.org/legal/eplfaq.php</a> for more information.
    </p>
    <p>
      Running on the JVM provides
      portability, stability, performance and security.
      It also provides access to a wealth of existing Java libraries
      supporting functionality including
      file I/O, multithreading, database access, GUIs, web applications,
      and much more.
    </p>
    <p>
      Each "operation" in Clojure is implemented as either
      a function, macro or special form.
      Nearly all functions and macros
      are implemented in Clojure source code.
      The differences between functions and macros are explained later.
      Special forms are recognized by the Clojure compiler and
      not implemented in Clojure source code.
      There are a relatively small number of special forms
      and new ones cannot be implemented.
      They include
      <a href="http://clojure.org/special_forms#try">catch</a>,
      <a href="http://clojure.org/special_forms#toc1">def</a>,
      <a href="http://clojure.org/special_forms#toc3">do</a>,
      <a href="http://clojure.org/java_interop#dot">dot</a> ('.'),
      <a href="http://clojure.org/special_forms#try">finally</a>,
      <a href="http://clojure.org/special_forms#toc7">fn</a>,
      <a href="http://clojure.org/special_forms#toc2">if</a>,
      <a href="http://clojure.org/special_forms#toc4">let</a>,
      <a href="http://clojure.org/special_forms#toc9">loop</a>,
      <a href="http://clojure.org/special_forms#toc13">monitor-enter</a>,
      <a href="http://clojure.org/special_forms#toc14">monitor-exit</a>,
      <a href="http://clojure.org/java_interop#new">new</a>,
      <a href="http://clojure.org/special_forms#toc5">quote</a>,
      <a href="http://clojure.org/special_forms#toc12">recur</a>,
      <a href="http://clojure.org/java_interop#set">set!</a>,
      <a href="http://clojure.org/special_forms#try">throw</a>,
      <a href="http://clojure.org/special_forms#try">try</a> and
      <a href="http://clojure.org/special_forms#toc6">var</a>.
    </p>
    <p>
      Clojure provides many functions that make it easy to operate on
      "sequences" which are logical views of collections.
      Many things can be treated as sequences.
      These include Java collections, Clojure-specific collections,
      strings, streams, directory structures and XML trees.
      New instances of Clojure collections can be created
      from existing ones in an efficient manner because they are
      <a href="http://en.wikipedia.org/wiki/Persistent_data_structure">persistent data structures</a>.
    </p>
    <p>
      Clojure provides three ways of safely sharing mutable data,
      all of which use mutable references to immutable data.
      <a href="#Refs">Refs</a> provide synchronous access
      to multiple pieces of shared data ("coordinated") by using
      <a href="http://en.wikipedia.org/wiki/Software_transactional_memory">Software Transactional Memory</a> (STM).
      <a href="#Atoms">Atoms</a> provide synchronous access
      to a single piece of shared data.
      <a href="#Agents">Agents</a> provide asynchronous access
      to a single piece of shared data.
      These are discussed in more detail in
      the "<a href="#ReferenceTypes">Reference Types</a>" section.
    </p>
    <p>
      Clojure is a
      <a href="http://en.wikipedia.org/wiki/Lisp_(programming_language)">Lisp</a>
      dialect. However, it makes some departures from older Lisps.
      For example, older Lisps use the <code>car</code> function to get
      the first item in a list. Clojure calls this <code>first</code>
      as does Common Lisp.
      For a list of other differences, see
      <a href="http://clojure.org/lisps">http://clojure.org/lisps</a>.
    </p>
    <p>
      Lisp has a syntax that many people love… and many people hate,
      mainly due to its use of parentheses and prefix notation.
      If you tend toward the latter camp, consider these facts.
      Many text editors and IDEs highlight matching parentheses, so it
      isn't necessary to count them in order to ensure they are balanced.
      Clojure function calls are less noisy than Java method calls.
      A Java method call looks like this:
    </p>
    <div class="code">
<pre xml:space="preserve">
methodName(arg1, arg2, arg3);
</pre>
</div>
    <p>
      A Clojure function call looks like this:
    </p>
    <div class="code">
<pre xml:space="preserve">
(function-name arg1 arg2 arg3)
</pre>
</div>
    <p>
      The open paren moves to the front and
      the commas and semicolon disappear.
      This syntax is referred to as a "form".
      There is simple beauty in the fact that
      everything in Lisp has this form.
      Note that the naming convention in Clojure is to use
      all lowercase with hyphens separating words in multi-word names,
      unlike the Java convention of using camelcase.
    </p>
    <p>
      Defining functions is similarly less noisy in Clojure.
      The Clojure <code>println</code> function
      adds a space between the output from each of its arguments.
      To avoid this, pass the same arguments
      to the <code>str</code> function and
      pass its result to <code>println</code> .
    </p>
    <div class="code">
<pre xml:space="preserve">
// Java
public void hello(String name) {
    System.out.println("Hello, " + name);
}

; Clojure
(defn hello [name]
  (println "Hello," name))
</pre>
</div>
    <p>
      Clojure makes heavy use of lazy evaluation.
      This allows functions to be invoked
      only when their result is needed.
      "Lazy sequences" are collections of results
      that are not computed until needed.
      This supports the efficient creation of infinite collections.
    </p>
    <p>
      Clojure code is processed in three phases:
      read-time, compile-time and run-time.
      At read-time the Reader reads source code and
      converts it to a data structure, mostly a list of lists of lists…
      At compile-time this data structure is converted to Java bytecode.
      At run-time the bytecode is executed.
      Functions are only invoked at run-time.
      Macros are special constructs
      whose invocation looks similar to that of functions,
      but are expanded into new Clojure code at compile-time.
    </p>
    <p>
      Is Clojure code hard to understand?
      Imagine if every time you read Java source code and
      encountered syntax elements like <code>if</code> statements,
      <code>for</code> loops, and anonymous classes,
      you had to pause and puzzle over what they mean.
      There are certain things that must be obvious to
      a person who wants to be a productive Java developer.
      Likewise there are parts of Clojure syntax that must be obvious
      for one to efficiently read and understand code.
      Examples include being comfortable with the use of
      <code>let</code>, <code>apply</code>, <code>map</code>,
      <code>filter</code>, <code>reduce</code>
      and anonymous functions… all of which are described later.
    </p>
    
    <h2><a name="GettingStarted">Getting Started</a></h2>

    <p>
      Clojure code for your own library and application projects will
      typically reside in its own directory (named after the project)
      and will be managed by the
      <a href="http://leiningen.org/index.html">Leiningen</a>
      project management tool. Leiningen (or "lein" for short) will
      take care of downloading Clojure for you and making it available
      to your projects. To start using Clojure, you don't need to
      install Clojure, nor deal with jar files or
      the <code>java</code> command &mdash; just install and use
      <code>lein</code> (instructions on the Leiningen homepage,
      linked to above).
    </p>

    <p>
      Once you've installed lein, create a trivial project to start
      playing around with:
    </p>
<div class="code">
<pre xml:space="preserve">cd ~/temp
lein new my-proj
cd my-proj
lein repl # starts up the interactive REPL
</pre>
</div>
    <p>
      To create a new <i>application</i> project, do
      "<code>lein new app my-app</code>"
    </p>
    <p>
      For more about getting started, see
      <a href="http://dev.clojure.org/display/doc/Getting+Started">http://dev.clojure.org/display/doc/Getting+Started</a>.
    </p>

    <h2><a name="Syntax">Clojure Syntax</a></h2>
    <p>
      Lisp dialects have a very simple, some would say beautiful, syntax.
      Data and code have the same representation, lists of lists
      that can be represented in memory quite naturally as a tree.
      <code>(a b c)</code> is a call to a function named <code>a</code>
      with arguments <code>b</code> and <code>c</code>.
      To make this data instead of code, the list needs to be quoted.
      <code>'(a b c)</code> or <code>(quote (a b c))</code>
      is a list of the values
      <code>a</code>, <code>b</code> and <code>c</code>.
      That's it except for some special cases.
      The number of special cases there are depends on the dialect.
    </p>
    <p>
      The special cases are seen by some as syntactic sugar.
      The more of them there are, the shorter certain kinds of code become
      and the more readers of the code have to learn and remember.
      It's a tricky balance.
      Many of them have an equivalent function name
      that can be used instead.
      I'll leave it to you to decide if Clojure
      has too much or too little syntactic sugar.
    </p>
    <p>
      The table below briefly describes each of the special cases
      encountered in Clojure code.
      These will be described in more detail later.
      Don't try to understand everything in the table now.
    </p>
    <table border="1">
      <tr style="background:pink">
        <th colspan="1" rowspan="1">Purpose</th>
        <th colspan="1" rowspan="1">Sugar</th>
        <th colspan="1" rowspan="1">Function</th>
      </tr>
      <tr>
        <td colspan="1" rowspan="1">comment</td>
        <td colspan="1" rowspan="1">
          <code>; <i>text</i></code><br />
          for line comments</td>
        <td colspan="1" rowspan="1">
          <code>(comment <i>text</i>)</code> macro<br />
          for block comments
        </td>
      </tr>
      <tr>
        <td colspan="1" rowspan="1">
          character literal (uses Java <code>char</code> type)</td>
        <td colspan="1" rowspan="1">
          <code>\<i>char</i></code>
          <code>\tab</code><br />
          <code>\newline</code>
          <code>\space</code><br />
          <code>\u<i>unicode-hex-value</i></code>
        </td>
        <td colspan="1" rowspan="1">
          <code>(char <i>ascii-code</i>)</code><br />
          <code>(char \u<i>unicode</i></code>)
        </td>
      </tr>
      <tr>
        <td colspan="1" rowspan="1">
          string (uses Java <code>String</code> objects)</td>
        <td colspan="1" rowspan="1">
          <code>"<i>text</i>"</code>
        </td>
        <td colspan="1" rowspan="1">
          <code>(str <i>char1</i> <i>char2</i> ...)</code><br />
          concatenates characters and
          many other kinds of values to create a string.
        </td>
      </tr>
      <tr>
        <td colspan="1" rowspan="1">
          keyword; an interned string;
          keywords with the same name refer to the same object;
          often used for map keys
        </td>
        <td colspan="1" rowspan="1">
          <code>:<i>name</i></code>
        </td>
        <td colspan="1" rowspan="1">
          <code>(keyword "<i>name</i>")</code>
        </td>
      </tr>
      <tr>
        <td colspan="1" rowspan="1">
          keyword resolved in the current namespace
        </td>
        <td colspan="1" rowspan="1">
          <code>::<i>name</i></code>
        </td>
        <td colspan="1" rowspan="1">
          none
        </td>
      </tr>
      <tr>
        <td colspan="1" rowspan="1">regular expression</td>
        <td colspan="1" rowspan="1">
          <code>#"<i>pattern</i>"</code><br />
          quoting rules differ from function form
        </td>
        <td colspan="1" rowspan="1">
          <code>(re-pattern <i>pattern</i>)</code>
        </td>
      </tr>
      <tr>
        <td colspan="1" rowspan="1">
          treated as whitespace;
          sometimes used in collections to aid readability
        </td>
        <td colspan="1" rowspan="1">
          <code>,</code> (a comma)</td>
        <td colspan="1" rowspan="1">N/A</td>
      </tr>
      <tr>
        <td colspan="1" rowspan="1">list - a linked list</td>
        <td colspan="1" rowspan="1">
          <code>'(<i>items</i>)</code><br />
          doesn't evaluate items
        </td>
        <td colspan="1" rowspan="1">
          <code>(list <i>items</i>)</code><br />
          evaluates items
        </td>
      </tr>
      <tr>
        <td colspan="1" rowspan="1">vector - similar to an array</td>
        <td colspan="1" rowspan="1">
          <code>[<i>items</i>]</code>
        </td>
        <td colspan="1" rowspan="1">
          <code>(vector <i>items</i>)</code>
        </td>
      </tr>
      <tr>
        <td colspan="1" rowspan="1">set</td>
        <td colspan="1" rowspan="1">
          <code>#{<i>items</i>}</code><br />
          creates a hash set
        </td>
        <td colspan="1" rowspan="1">
          <code>(hash-set <i>items</i>)</code><br />
          <code>(sorted-set <i>items</i>)</code>
        </td>
      </tr>
      <tr>
        <td colspan="1" rowspan="1">map</td>
        <td colspan="1" rowspan="1">
          <code>{<i>key-value-pairs</i>}</code><br />
          creates a hash map
        </td>
        <td colspan="1" rowspan="1">
          <code>(hash-map <i>key-value-pairs</i>)</code><br />
          <code>(sorted-map <i>key-value-pairs</i>)</code>
        </td>
      </tr>
      <tr>
        <td colspan="1" rowspan="1">
          add metadata to a symbol or collection
        </td>
        <td colspan="1" rowspan="1">
          <code>^{<i>key-value-pairs</i>} <i>object</i></code><br />
          processed at read-time
        </td>
        <td colspan="1" rowspan="1">
          <code>(with-meta <i>object</i> <i>metadata-map</i>)</code><br />
          processed at run-time
        </td>
      </tr>
      <tr>
        <td colspan="1" rowspan="1">
          get metadata map from a symbol or collection
        </td>
        <td colspan="1" rowspan="1">
        </td>
        <td colspan="1" rowspan="1">
          <code>(meta <i>object</i>)</code>
        </td>
      </tr>
      <tr>
        <td colspan="1" rowspan="1">
          gather a variable number of arguments<br />
          in a function parameter list</td>
        <td colspan="1" rowspan="1">
          <code>&amp; <i>name</i></code>
        </td>
        <td colspan="1" rowspan="1">N/A</td>
      </tr>
      <tr>
        <td colspan="1" rowspan="1">conventional name given to<br />
          function parameters that aren't used</td>
        <td colspan="1" rowspan="1">
          <code>_</code> (an underscore)</td>
        <td colspan="1" rowspan="1">N/A</td>
      </tr>
      <tr>
        <td colspan="1" rowspan="1">construct a Java object;<br />
          note the period after the class name</td>
        <td colspan="1" rowspan="1">
          <code>(<i>class-name</i>. <i>args</i>)</code>
        </td>
        <td colspan="1" rowspan="1">
          <code>(new <i>class-name</i> <i>args</i>)</code>
        </td>
      </tr>
      <tr>
        <td colspan="1" rowspan="1">call a Java method</td>
        <td colspan="1" rowspan="1">
          <code>(. <i>class-or-instance</i> <i>method-name</i> <i>args</i>)</code> or <br />
          <code>(.<i>method-name</i> <i>class-or-instance</i> <i>args</i>)</code>
        </td>
        <td colspan="1" rowspan="1">none</td>
      </tr>
      <tr>
        <td colspan="1" rowspan="1">
          call several Java methods, threading the result
          from each into the next as its first argument;<br />
          each method can have additional arguments
          specified inside the parens;<br />
          note the double period</td>
        <td colspan="1" rowspan="1">
          <code>(.. <i>class-or-object</i>
          (<i>method1 args</i>) (<i>method2 args</i>) ...)</code>
        </td>
        <td colspan="1" rowspan="1">none</td>
      </tr>
      <tr>
        <td colspan="1" rowspan="1">create an anonymous function</td>
        <td colspan="1" rowspan="1">
          <code>#(<i>single-expression</i>)</code><br />
          use <code>%</code> (same as <code>%1</code>), <code>%1</code>,
          <code>%2</code> and so on for arguments
        </td>
        <td colspan="1" rowspan="1">
          <code>(fn [<i>arg-names</i>] <i>expressions</i>)</code>
        </td>
      </tr>
      <tr>
        <td colspan="1" rowspan="1">dereference a Ref, Atom or Agent</td>
        <td colspan="1" rowspan="1">
          <code>@<i>ref</i></code>
        </td>
        <td colspan="1" rowspan="1">
          <code>(deref <i>ref</i>)</code>
        </td>
      </tr>
      <tr>
        <td colspan="1" rowspan="1">
          get <code>Var</code> object instead of<br />
          the value of a symbol (var-quote)</td>
        <td colspan="1" rowspan="1">
          <code>#'<i>name</i></code>
        </td>
        <td colspan="1" rowspan="1">
          <code>(var <i>name</i>)</code>
        </td>
      </tr>
      <tr>
        <td colspan="1" rowspan="1">syntax quote (used in macros)</td>
        <td colspan="1" rowspan="1">
          <code>`</code>
        </td>
        <td colspan="1" rowspan="1">none</td>
      </tr>
      <tr>
        <td colspan="1" rowspan="1">unquote (used in macros)</td>
        <td colspan="1" rowspan="1">
          <code>~<i>value</i></code>
        </td>
        <td colspan="1" rowspan="1">
          <code>(unquote <i>value</i>)</code>
        </td>
      </tr>
      <tr>
        <td colspan="1" rowspan="1">unquote splicing (used in macros)</td>
        <td colspan="1" rowspan="1">
          <code>~@<i>value</i></code>
        </td>
        <td colspan="1" rowspan="1">none</td>
      </tr>
      <tr>
        <td colspan="1" rowspan="1">auto-gensym
          (used in macros to generate a unique symbol name)</td>
        <td colspan="1" rowspan="1">
          <code><i>prefix</i>#</code>
        </td>
        <td colspan="1" rowspan="1">
          <code>(gensym <i>prefix</i>?)</code>
        </td>
      </tr>
    </table>

    <p>
      Lisp dialects use prefix notation rather than
      the typical infix notation used by most programming languages
      for binary operators such as <code>+</code> and <code>*</code>.
      For example, in Java one might write <code>a + b + c</code>,
      whereas in a Lisp dialect this becomes <code>(+ a b c)</code>.
      One benefit of this notation is that any number of arguments
      can be specified without repeating the operator.
      Binary operators from other languages are Lisp functions
      that aren't restricted to two operands.
    </p>
    <p>
      One reason Lisp code contains more parentheses
      than code in other languages is that it also uses them
      where languages like Java use curly braces.
      For example, the statements in a Java method are inside curly braces,
      whereas the expressions in a Lisp function are inside
      the function definition which is surrounded by parentheses.
    </p>
    <p>
      Compare the following snippets of Java and Clojure code
      that each define a simple function and invoke it.
      The output from both is "edray" and "orangeay".
    </p>
    <div class="code">
<pre xml:space="preserve">
// This is Java code.
public class PigLatin {

    public static String pigLatin(String word) {
        char firstLetter = word.charAt(0);
        if ("aeiou".indexOf(firstLetter) != -1) return word + "ay";
        return word.substring(1) + firstLetter + "ay";
    }

    public static void main(String args[]) {
        System.out.println(pigLatin("red"));
        System.out.println(pigLatin("orange"));
    }
}
</pre>
</div>
    <p/>
    <div class="code">
<pre xml:space="preserve">
; This is Clojure code.
; When a set is used as a function, it returns a boolean
; that indicates whether the argument is in the set.
(def vowel? (set "aeiou"))

(defn pig-latin [word] ; defines a function
  ; word is expected to be a string
  ; which can be treated like a sequence of characters.
  (let [first-letter (first word)] ; assigns a local binding
    (if (vowel? first-letter)
      (str word "ay") ; then part of if
      (str (subs word 1) first-letter "ay")))) ; else part of if

(println (pig-latin "red"))
(println (pig-latin "orange"))
</pre>
</div>
    <p>
      Clojure supports all the common data types such as booleans
      (with literal values of <code>true</code> and <code>false</code>),
      integers, decimals,
      characters (see "character literal" in the table above) and strings.
      It also supports ratios which retain a numerator and denominator
      so numeric precision is not lost when they are used in calculations.
    </p>
    <p>
      Symbols are used to name things.
      These names are scoped in a namespace,
      either one that is specified or the default namespace.
      Symbols evaluate to their value.
      To access the <code>Symbol</code> object itself, it must be quoted.
    </p>
    <p>
      Keywords begin with a colon and are used as unique identifiers.
      Examples include keys in maps and enumerated values
      (such as <code>:red</code>, <code>:green</code>
      and <code>:blue</code>).
    </p>
    <p>
      It is possible in Clojure, as it is any programming language,
      to write code that is difficult to understand.
      Following a few guidelines can make a big difference.
      Write short, well-focused functions to make them
      easier to read, test and reuse.
      Use the "extract method" refactoring pattern often.
      Deeply nested function calls can be hard to read.
      Limit this nesting where possible,
      often by using <code>let</code> to break
      complicated expressions into several less complicated expressions.
      Passing anonymous functions to named functions is common.
      However, avoid passing anonymous functions
      to other anonymous functions
      because such code is difficult to read.
    </p>

    <h2><a name="REPL">REPL</a></h2>
    <p>
      REPL stands for read-eval-print loop.
      This is a standard tool in Lisp dialects that
      allows a user to enter expressions, have them read and evaluated,
      and have their result printed.
      It is a very useful tool for testing and
      gaining an understanding of code.
    </p>
    <p>
      To start a REPL, run the script created earlier by
      entering "<code>clj</code>" at a command prompt.
      This will display a prompt of "<code>user=&gt;</code>".
      The part before "<code>=&gt;</code>"
      indicates the current default namespace.
      Forms entered after this prompt are evaluated
      and their result is output.
      Here's a sample REPL session that shows both input and output.
    </p>
    <div class="code">
<pre xml:space="preserve">
user=&gt; (def n 2)
#'user/n
user=&gt; (* n 3)
6
</pre>
</div>
    <p>
      <code>def</code> is a special form that
      doesn't evaluate its first argument,
      but instead uses the literal value as a name.
      Its REPL output shows that a symbol named "<code>n</code>"
      in the namespace "<code>user</code>" was defined.
    </p>
    <p>
      To view documentation for a function, macro or namespace,
      enter <code>(doc <i>name</i>)</code>.
      If it is a macro, the word "Macro" will appear on a line by itself
      immediately after its parameter list.
      The item for which documentation is being requested
      must already be loaded (see the
      <a href="#require">require</a> function).
      For example:
    </p>
    <div class="code">
<pre xml:space="preserve">
(require 'clojure.string)
(doc clojure.string/join) ; -&gt;
; -------------------------
; clojure.string/join
; ([coll] [separator coll])
; Returns a string of all elements in coll, as returned by (seq coll),
; separated by an optional separator.
</pre>
</div>
    <p>
      To find documentation on all functions/macros whose
      name or documentation string contains a given string,
      enter <code>(find-doc "<i>text</i>")</code>.
    </p>
    <p>
      To see the source for a function/macro,
      enter <code>(source <i>name</i>)</code>.
      <code>source</code> is a macro defined in the
      <code>clojure.repl</code> namespace
      which is automatically loaded in the REPL environment.
    </p>
    <p>
      To load and execute the forms in a source file,
      enter <code>(load-file "<i>file-path</i>")</code>.
      Typically these files have a <code>.clj</code> extension.
    </p>
    <p>
      To exit the REPL under Windows,
      type ctrl-z followed by the enter key or just ctrl-c.
      To exit the REPL on every other platform
      (including UNIX, Linux and Mac OS X), type ctrl-d.
    </p>
    
    <h2><a name="Vars">Vars</a></h2>
    <p>
      Clojure provides bindings to Vars, which are containers bound to mutable
      storage locations. There are global bindings, thread-local bindings,
      bindings that are local to a function, and bindings that are local to a given form.
    </p>
    </p>
      Function parameters are bound to Vars that are local to the function.
    </p>
    <p>
      The <code>def</code> special form binds a value to a symbol. It provides a
      mechanism to define metadata, <code>:dynamic</code>, which allows a thread-local value
      within the scope of a <code>binding</code> call.
      In other words, it allows re-definition of assigned value per execution thread
      and scope. If the Var is not re-assigned to a new value in a separate
      execution thread, the Var refers to the value of the root binding,
      if accessed from another thread.
    <p>
      The <code>let</code> special form creates bindings to Vars
      that are bound to the scope within the statement.
      Its first argument is a vector containing name/expression pairs.
      The expressions are evaluated in order and their results
      are assigned to the names on their left.
      These Vars can be used in the binding of other Vars declared within the vector.
      The expressions following the Var declaration vector
      contain the Var(s) that are executed only within the <code>let</code> scope.
      Vars within functions that are called within <code>let</code> but
      defined outside of that scope are not affected
      by the declarations in the <code>let</code>'s vector.
       </p>
    <p>
      <a name="binding">The</a> <code>binding</code> macro
      is similar to <code>let</code>,
      but it gives new, thread-local values
      to existing global bindings throughout the scope's
      thread of execution.
      The values of Vars bound within the <code>let</code>
      vector argument are also used in functions, if they use
      the same Var names, called from inside that scope.
      When the execution thread leaves the <code>binding</code> macro's scope,
      the global Var bindings revert to their previous values.
      Starting in Clojure 1.3, binding can only do this for vars
      declared <code>:dynamic</code>.
    </p>
    <p>
      Vars intended to be bound to new, thread-local values
      using <code>binding</code> have their own naming convention.
      These symbols have names that
      begin and end with an asterisk.
      Examples that appear in this article include
      <code>*command-line-args*</code>,
      <code>*agent*</code>,
      <code>*err*</code>,
      <code>*flush-on-newline*</code>,
      <code>*in*</code>,
      <code>*load-tests*</code>,
      <code>*ns*</code>,
      <code>*out*</code>,
      <code>*print-length*</code>,
      <code>*print-level*</code> and
      <code>*stack-trace-depth*</code>.
      Functions that use these bindings are affected by their values.
      For example, binding a new value to <code>*out*</code>
      changes the output destination of
      the <code>println</code> function.
    </p>
    <p>
      The following code demonstrates usage of
      <code>def</code>, <code>defn</code>, <code>let</code>, <code>binding</code>, and <code>println</code>.
    </p>
    <div class="code">
<pre xml:space="preserve">
(def ^:dynamic v 1) ; v is a global binding

(defn f1 []
  (println "f1: v:" v))

(defn f2 []
  (println "f2: before let v:" v)
  ; creates local binding v that shadows global one
  (let [v 2]
    ; local binding only within this let statement
    (println "f2: in let, v:" v)
    (f1))
  ; outside of this let, v refers to global binding
  (println "f2: after let v:" v))

(defn f3 []
  (println "f3: before binding v:" v)
  ; same global binding with new, temporary value
  (binding [v 3]
    ; global binding, new value
    (println "f3: within binding function v: " v)
    (f1)) ; calling f1 with new value to v
  ; outside of binding v refers to first global value
  (println "f3: after binding v:" v))

(defn f4 []
 (def v 4)) ; changes the value of v in the global scope

(println "(= v 1) => " (= v 1))
(println "Calling f2: ")
(f2)
(println)
(println "Calling f3: ")
(f3)
(println)
(println "Calling f4: ")
(f4)
(println "after calling f4, v =" v)
</pre>
    </div>
    <p>
      To run the code above, save it in a file named "vars.clj" and
      use the shell script for executing Clojure files described earlier
      as follows:
    </p>
    <div class="code">
<pre xml:space="preserve">
$ clj vars.clj
</pre>
    </div>
    <p>
      The output produced by the code above follows:
    </p>
    <div class="code">
<pre xml:space="preserve">
; (= v 1) => true
Calling f2
f2: before let v: 1
f2: in let, v: 2
f1: v: 1
f2: after let v: 1

Calling f3
f3: before binding v: 1
f3: within binding function v: 3
f1: v: 3
f3: after binding v: 1

Calling f4
after calling f4, v: 4
</pre>
    </div>
    <h4>Recap:</h4>
    </p>
    <p>
      Notice in the first call to f2, the <code>let</code>
      function's binding to v did not change its originally
      declared value, as is shown in the call to
      f1 within the <code>let</code> statement.
      The value of v in f1 is 1, not 2.
    </p>
    <p>
      Next, inside f3 within the scope of the <code>binding</code> call,
      the value of v was re-assigned within f1 since f1 was called within the
      execution thread of <code>binding</code> call's scope. Once f3's
      function execution thread exits from the <code>binding</code> call,
      v is bound to the initially declared binding, 1.
    </p>
    <p>
      When f4 is called, the binding of v is not within the context of a
      new execution thread so v is bound to the new value, 4, in the global scope.
      Remember that changing a global value is not necessarily a best
      practice. It is presented in f4's definition for demonstration purposes.
    </p>

    <h2><a name="Collections">Collections</a></h2>
    <p>
      Clojure provides the collection types list, vector, set and map.
      Clojure can also use any of the Java collection classes,
      but this is not typically done because the Clojure variety
      are a much better fit for functional programming.
    </p>
    <p>
      The Clojure collection types have characteristics
      that differ from Java's collection types.
      All of them are immutable, heterogeneous and persistent.
      Being immutable means that their contents cannot be changed.
      Being heterogeneous means that they can hold any kind of object.
      Being persistent means that old versions of them are preserved
      when new versions are created.
      Clojure does this in a very efficient manner
      where new versions share memory with old versions.
      For example, a new version of
      a map containing thousands of key/value pairs
      where just one value needs to be modified
      can be created quickly and consumes very little additional memory.
    </p>
    <p>
      There are many core functions that operate on
      all kinds of collections… far too many to describe here.
      A small subset of them are described next using vectors.
      Keep in mind that since Clojure collections are immutable,
      there are no functions that modify them.
      Instead, there are many functions that use the magic of
      <a href="http://en.wikipedia.org/wiki/Persistent_data_structure">persistent data structures</a>
      to efficiently create new collections from existing ones.
      Also, some functions that operate on a collection (for example, a vector)
      return a collection of a different type
      (for example, a <code>LazySeq</code>)
      that has different characteristics.
    </p>
    <p>
      WARNING: This section presents information about Clojure collections
      that is important to learn.
      However, it drones on a bit,
      presenting function after function
      for operating on various types of collections.
      Should drowsiness set in, please skip ahead to
      the sections that follow and return to this section later.
    </p>
    <p>
      The <code>count</code> function returns
      the number of items in any collection.
      For example:
    </p>
    <div class="code">
<pre xml:space="preserve">
(count [19 "yellow" true]) ; -&gt; 3
</pre>
</div>
    <p>
      The <code>conj</code> function, short for conjoin,
      adds one or more items to a collection.
      Where they are added depends on the type of the collection.
      This is explained in the information on
      specific collection types below.
    </p>
    <p>
      The <code>reverse</code> function returns a sequence
      of the items in the collection in reverse order.
    </p>
    <div class="code">
<pre xml:space="preserve">
(reverse [2 4 7]) ; -&gt; (7 4 2)
</pre>
</div>
    <p>
      The <code>map</code> function applies a given function
      that takes one parameter to each item in a collection,
      returning a lazy sequence of the results.
      It can also apply functions that take more than one parameter
      if a collection is supplied for each argument.
      If those collections contain different numbers of items,
      the items used from each will be those at the beginning
      up to the number of items in the smallest collection.
      For example:
    </p>
    <div class="code">
<pre xml:space="preserve">
; The next line uses an anonymous function that adds 3 to its argument.
(map #(+ % 3) [2 4 7]) ; -&gt; (5 7 10)
(map + [2 4 7] [5 6] [1 2 3 4]) ; adds corresponding items -&gt; (8 12)
</pre>
</div>
    <p>
      The <code>apply</code> function returns
      the result of a given function when
      all the items in a given collection are used as arguments.
      For example:
    </p>
    <div class="code">
<pre xml:space="preserve">
(apply + [2 4 7]); -&gt; 13
</pre>
</div>
    <p>
      There are many functions that retrieve a single item
      from a collection. For example:
    </p>
    <div class="code">
<pre xml:space="preserve">
(def stooges ["Moe" "Larry" "Curly" "Shemp"])
(first stooges) ; -&gt; "Moe"
(second stooges) ; -&gt; "Larry"
(last stooges) ; -&gt; "Shemp"
(nth stooges 2) ; indexes start at 0 -&gt; "Curly"
</pre>
</div>
    <p>
      There are many functions that retrieve several items
      from a collection. For example:
    </p>
    <div class="code">
<pre xml:space="preserve">
(next stooges) ; -&gt; ("Larry" "Curly" "Shemp")
(butlast stooges) ; -&gt; ("Moe" "Larry" "Curly")
(drop-last 2 stooges) ; -&gt; ("Moe" "Larry")
; Get names containing more than three characters.
(filter #(&gt; (count %) 3) stooges) ; -&gt; ("Larry" "Curly" "Shemp")
(nthnext stooges 2) ; -&gt; ("Curly" "Shemp")
</pre>
</div>
    <p>
      There are several predicate functions that test the items
      in a collection and have a boolean result.
      These "short-circuit" so they only evaluate as many items
      as necessary to determine their result. For example:
    </p>
    <div class="code">
<pre xml:space="preserve">
(every? #(instance? String %) stooges) ; -&gt; true
(not-every? #(instance? String %) stooges) ; -&gt; false
(some #(instance? Number %) stooges) ; -&gt; nil
(not-any? #(instance? Number %) stooges) ; -&gt; true
</pre>
</div>

    <h3><a name="Lists">Lists</a></h3>
    <p>
      Lists are ordered collections of items.
      They are ideal when new items will be
      added to or removed from the front (constant-time).
      They are not efficient (linear time)
      for finding items by index (using <code>nth</code>)
      and there is no efficient way to change items by index.
    </p>
    <p>
      Here are some ways to create a list that all have the same result:
    </p>
    <div class="code">
<pre xml:space="preserve">
(def stooges (list "Moe" "Larry" "Curly"))
(def stooges (quote ("Moe" "Larry" "Curly")))
(def stooges '("Moe" "Larry" "Curly"))
</pre>
</div>
    <p>
      The <code>some</code> function can be used to determine
      if a collection contains a given item.
      It takes a predicate function and a collection.
      While it may seem tedious to need to specify a predicate function
      in order to test for the existence of a single item,
      it is somewhat intentional to discourage this usage.
      Searching a list for a single item is a linear operation.
      Using a set instead of a list is more efficient and easier.
      Nevertheless, it can be done as follows:
    </p>
    <div class="code">
<pre xml:space="preserve">
(some #(= % "Moe") stooges) ; -&gt; true
(some #(= % "Mark") stooges) ; -&gt; nil
; Another approach is to create a set from the list
; and then use the contains? function on the set as follows.
(contains? (set stooges) "Moe") ; -&gt; true
</pre>
</div>
    <p>
      Both the <code>conj</code> and <code>cons</code> functions
      create a new list
      that contains additional items added to the front.
      The <code>remove</code> function creates a new list containing
      only the items for which a predicate function returns false.
      For example:
    </p>
    <div class="code">
<pre xml:space="preserve">
(def more-stooges (conj stooges "Shemp")) ; -&gt; ("Shemp" "Moe" "Larry" "Curly")
(def less-stooges (remove #(= % "Curly") more-stooges)) ; -&gt; ("Shemp" "Moe" "Larry")
</pre>
</div>
    <p>
      The <code>into</code> function creates a new list
      that contains all the items in two lists. For example:
    </p>
    <div class="code">
<pre xml:space="preserve">
(def kids-of-mike '("Greg" "Peter" "Bobby"))
(def kids-of-carol '("Marcia" "Jan" "Cindy"))
(def brady-bunch (into kids-of-mike kids-of-carol))
(println brady-bunch) ; -&gt; (Cindy Jan Marcia Greg Peter Bobby)
</pre>
</div>
    <p>
      The <code>peek</code> and <code>pop</code> functions
      can be used to treat a list as a stack.
      They operate on the beginning or head of the list.
    </p>

    <h3><a name="Vectors">Vectors</a></h3>
    <p>
      Vectors are also ordered collections of items.
      They are ideal when new items will be
      added to or removed from the back (constant-time).
      This means that using <code>conj</code> is more efficient
      than <code>cons</code> for adding items.
      They are efficient (constant time)
      for finding (using <code>nth</code>)
      or changing (using <code>assoc</code>) items by index.
      Function definitions specify their parameter list using a vector.
    </p>
    <p>
      Here are some ways to create a vector:
    </p>
    <div class="code">
<pre xml:space="preserve">
(def stooges (vector "Moe" "Larry" "Curly"))
(def stooges ["Moe" "Larry" "Curly"])
</pre>
</div>
    <p>
      Unless the list characteristic of being more efficient at
      adding to or removing from the front is significant for a given use,
      vectors are typically preferred over lists.
      This is mainly due to the vector syntax of <code>[...]</code>
      being a bit more appealing than the list syntax of <code>'(...)</code>.
      It doesn't have the possibility of being confused
      with a call to a function, macro or special form.
    </p>
    <p>
      The <code>get</code> function retrieves an item
      from a vector by index.
      As shown later, it also retrieves a value from a map by key.
      Indexes start from zero.
      The <code>get</code> function is similar to
      the <code>nth</code> function.
      Both take an optional value to be returned
      if the index is out of range.
      If this is not supplied and the index is out of range,
      <code>get</code> returns <code>nil</code>
      and <code>nth</code> throws an exception.
      For example:
    </p>
    <div class="code">
<pre xml:space="preserve">
(get stooges 1 "unknown") ; -&gt; "Larry"
(get stooges 3 "unknown") ; -&gt; "unknown"
</pre>
</div>
    <p>
      The <code>assoc</code> function operates on vectors and maps.
      When applied to a vector, it creates a new vector
      where the item specified by an index is replaced.
      If the index is equal to the number of items in the vector,
      a new item is added to the end.
      If it is greater than the number of items in the vector,
      an <code>IndexOutOfBoundsException</code> is thrown.
      For example:
    </p>
    <div class="code">
<pre xml:space="preserve">
(assoc stooges 2 "Shemp") ; -&gt; ["Moe" "Larry" "Shemp"]
</pre>
</div>
    <p>
      The <code>subvec</code> function returns a new vector that
      is a subset of an existing one that retains the order of the items.
      It takes a vector, a start index and an optional end index.
      If the end index is omitted, the subset runs to the end.
      The new vector shares the structure of the original one.
    </p>
    <p>
      All the code examples provided above for lists also work for vectors.
      The <code>peek</code> and <code>pop</code> functions
      also work with vectors, but operate on the end or tail
      rather than the beginning or head as they do for lists.
      The <code>conj</code> function creates a new vector
      that contains an additional item added to the back.
      The <code>cons</code> function creates a new vector
      that contains an additional item added to the front.
    </p>

    <h3><a name="Sets">Sets</a></h3>
    <p>
      Sets are collections of unique items.
      They are preferred over lists and vectors when
      duplicates are not allowed and
      items do not need to be maintained in the order in which they were added.
      Clojure supports two kinds of sets, unsorted and sorted.
      If the items being added to a sorted set can't be compared to each other,
      a <code>ClassCastException</code> is thrown.
      Here are some ways to create a set:
    </p>
    <div class="code">
<pre xml:space="preserve">
(def stooges (hash-set "Moe" "Larry" "Curly")) ; not sorted
(def stooges #{"Moe" "Larry" "Curly"}) ; same as previous
(def stooges (sorted-set "Moe" "Larry" "Curly"))
</pre>
</div>
    <p>
      The <code>contains?</code> function operates on sets and maps.
      When used on a set, it determines
      whether the set contains a given item.
      This is much simpler than using the <code>some</code> function
      which is needed to test this with a list or vector.
      For example:
    </p>
    <div class="code">
<pre xml:space="preserve">
(contains? stooges "Moe") ; -&gt; true
(contains? stooges "Mark") ; -&gt; false
</pre>
</div>
    <p>
      Sets can be used as functions of their items.
      When used in this way, they return the item or nil.
      This provides an even more compact way to test
      whether a set contains a given item.
      For example:
    </p>
<pre xml:space="preserve">
(stooges "Moe") ; -&gt; "Moe"
(stooges "Mark") ; -&gt; nil
(println (if (stooges person) "stooge" "regular person"))
</pre>
    <p>
      The <code>conj</code> and <code>into</code> functions
      demonstrated above with lists also work with sets.
      The location where the items are added is only defined for sorted sets.
    </p>
    <p>
      The <code>disj</code> function creates a new set
      where one or more items are removed.
      For example:
    </p>
    <div class="code">
<pre xml:space="preserve">
(def more-stooges (conj stooges "Shemp")) ; -&gt; #{"Moe" "Larry" "Curly" "Shemp"}
(def less-stooges (disj more-stooges "Curly")) ; -&gt; #{"Moe" "Larry" "Shemp"}
</pre>
</div>
    <p>
      Also consider the functions in the <code>clojure.set</code> namespace
      which include:
      <code>difference</code>, <code>index</code>,
      <code>intersection</code>, <code>join</code>,
      <code>map-invert</code>, <code>project</code>,
      <code>rename</code>, <code>rename-keys</code>,
      <code>select</code> and <code>union</code>.
      Some of these functions operate on maps instead of sets.
    </p>

    <h3><a name="Maps">Maps</a></h3>
    <p>
      Maps store associations between keys and their corresponding values
      where both can be any kind of object.
      Often keywords are used for map keys.
      Entries can be stored in such a way that the pairs can be
      quickly retrieved in sorted order based on their keys.
    </p>
    <p>
      Here are some ways to create maps that
      store associations from popsicle colors
      to their flavors where the keys and values are both keywords.
      The commas aid readability.
      They are optional and are treated as whitespace.
    </p>
    <div class="code">
<pre xml:space="preserve">
(def popsicle-map
  (hash-map :red :cherry, :green :apple, :purple :grape))
(def popsicle-map
  {:red :cherry, :green :apple, :purple :grape}) ; same as previous
(def popsicle-map
  (sorted-map :red :cherry, :green :apple, :purple :grape))
</pre>
</div>
    <p>
      Maps can be used as functions of their keys.
      Also, in some cases keys can be used as functions of maps.
      For example, keyword keys can, but string and integer keys cannot.
      The following are all valid ways to get
      the flavor of green popsicles, which is <code>:apple</code>:
    </p>
    <div class="code">
<pre xml:space="preserve">
(get popsicle-map :green)
(popsicle-map :green)
(:green popsicle-map)
</pre>
</div>
    <p>
      The <code>contains?</code> function operates on sets and maps.
      When used on a map, it determines
      whether the map contains a given key.
      The <code>keys</code> function returns a sequence containing
      all the keys in a given map.
      The <code>vals</code> function returns a sequence containing
      all the values in a given map.
      For example:
    </p>
    <div class="code">
<pre xml:space="preserve">
(contains? popsicle-map :green) ; -&gt; true
(keys popsicle-map) ; -&gt; (:red :green :purple)
(vals popsicle-map) ; -&gt; (:cherry :apple :grape)
</pre>
</div>
    <p>
      The <code>assoc</code> function operates on maps and vectors.
      When applied to a map, it creates a new map
      where any number of key/value pairs are added.
      Values for existing keys are replaced by new values.
      For example:
    </p>
    <div class="code">
<pre xml:space="preserve">
(assoc popsicle-map :green :lime :blue :blueberry)
; -&gt; {:blue :blueberry, :green :lime, :purple :grape, :red :cherry}
</pre>
</div>
    <p>
      The <code>dissoc</code> function takes a map and any number of keys.
      It returns a new map where those keys are removed.
      Specified keys that aren't in the map are ignored.
      For example:
    </p>
    <div class="code">
<pre xml:space="preserve">
(dissoc popsicle-map :green :blue) ; -&gt; {:purple :grape, :red :cherry}
</pre>
</div>
    <p>
      When used in the context of a sequence, maps are treated like
      a sequence of <code>clojure.lang.MapEntry</code> objects.
      This can be combined with the use of
      <a href="#ListComprehension">doseq</a> and
      <a href="#Destructuring">destructuring</a>,
      both of which are described in more detail later,
      to easily iterate through all the keys and values.
      The following example iterates through
      all the key/value pairs in <code>popsicle-map</code>
      and binds the key to <code>color</code>
      and the value to <code>flavor</code>.
      The <code>name</code> function returns the string name of a keyword.
    </p>
    <div class="code">
<pre xml:space="preserve">
(doseq [[color flavor] popsicle-map]
  (println (str "The flavor of " (name color)
    " popsicles is " (name flavor) ".")))
</pre>
</div>
    <p>
      The output produced by the code above follows:
    </p>
    <div class="code">
<pre xml:space="preserve">
The flavor of green popsicles is apple.
The flavor of purple popsicles is grape.
The flavor of red popsicles is cherry.
</pre>
</div>
    <p>
      The <code>select-keys</code> function takes a map and a sequence of keys.
      It returns a new map where only those keys are in the map.
      Specified keys that aren't in the map are ignored.
      For example:
    </p>
    <div class="code">
<pre xml:space="preserve">
(select-keys popsicle-map [:red :green :blue]) ; -&gt; {:green :apple, :red :cherry}
</pre>
</div>
    <p>
      The <code>conj</code> function adds all the key/value pairs
      from one map to another.
      If any keys in the source map already exist in the target map,
      the target map values are replaced by the corresponding source map values.
    </p>
    <p>
      Values in maps can be maps, and they can be nested to any depth.
      Retrieving nested values is easy.
      Likewise, creating new maps where nested values are modified is easy.
    </p>
    <p>
      To demonstrate this we'll create a map that describes a person.
      It has a key whose value describes their address using a map.
      It also has a key whose value describes their employer
      which has its own address map.
    </p>
    <div class="code">
<pre xml:space="preserve">
(def person {
  :name "Mark Volkmann"
  :address {
    :street "644 Glen Summit"
    :city "St. Charles"
    :state "Missouri"
    :zip 63304}
  :employer {
    :name "Object Computing, Inc."
    :address {
      :street "12140 Woodcrest Executive Drive, Suite 250"
      :city "Creve Coeur"
      :state "Missouri"
      :zip 63141}}})
</pre>
</div>
    <p>
      The <code>get-in</code> function takes a map and a key sequence.
      It returns the value of the nested map key at the end of the sequence.
      The <code>-&gt;</code> macro and the <code>reduce</code> function
      can also be used for this purpose.
      All of these are demonstrated below
      to retrieve the employer city which is "Creve Coeur".
    </p>
    <div class="code">
<pre xml:space="preserve">
(get-in person [:employer :address :city])
(-&gt; person :employer :address :city) ; explained below
(reduce get person [:employer :address :city]) ; explained below
</pre>
</div>
    <p>
      The <code>-&gt;</code> macro, referred to as the "thread" macro,
      calls a series of functions,
      passing the result of each as an argument to the next.
      For example the following lines have the same result:
    </p>
    <div class="code">
<pre xml:space="preserve">
(f1 (f2 (f3 x)))
(-&gt; x f3 f2 f1)
</pre>
</div>
    <p>
      There is also a <code>-?></code> macro
      in the <code>clojure.core.incubator</code> namespace that
      stops and returns nil if any function in the chain returns nil.
      This avoids getting a <code>NullPointerException</code>.
    </p>
    <p>
      <a name="reduce">The</a> <code>reduce</code> function
      takes a function of two arguments,
      an optional value and a collection.
      It begins by calling the function with either
      the value and the first item in the collection
      or the first two items in the collection if the value is omitted.
      It then calls the function repeatedly
      with the previous function result
      and the next item in the collection
      until every item in the collection has been processed.
      This function is the same as <code>inject</code> in Ruby
      and <code>foldl</code> in Haskell.
    </p>
    <p>
      The <code>assoc-in</code> function takes a map, a key sequence
      and a new value.
      It returns a new map where the nested map key
      at the end of the sequence has the new value.
      For example, a new map where the employer city
      is changed to "Clayton" can be created as follows:
    </p>
    <div class="code">
<pre xml:space="preserve">
(assoc-in person [:employer :address :city] "Clayton")
</pre>
</div>
    <p>
      The <code>update-in</code> function takes a map, a key sequence,
      a function and any number of additional arguments.
      The function is passed the old value of the key
      at the end of the sequence and the additional arguments.
      The value it returns is used as the new value of that key.
      For example, a new map where the employer zip code is
      changed to a string in the U.S. "ZIP + 4" format
      can be created using as follows:
    </p>
    <div class="code">
<pre xml:space="preserve">
(update-in person [:employer :address :zip] str "-1234") ; using the str function
</pre>
</div>

    <h2><a name="StructMaps">StructMaps</a></h2>
    <p>
      Note: StructMaps have been deprecated. Records are generally
      recommended instead. A section on Records will be added shortly.
    </p>
    <p>
      StructMaps are similar to regular maps, but are optimized
      to take advantage of common keys in multiple instances
      so they don't have to be repeated.
      Their use is similar to that of Java Beans.
      Proper <code>equals</code> and <code>hashCode</code> methods
      are generated for them.
      Accessor functions that are faster than ordinary map key lookups
      can easily be created.
    </p>
    <p>
      The <code>create-struct</code> function
      and <code>defstruct</code> macro,
      which uses <code>create-struct</code>,
      both define StructMaps.
      The keys are normally specified with keywords.
      For example:
    </p>
    <div class="code">
<pre xml:space="preserve">
(def vehicle-struct (create-struct :make :model :year :color)) ; long way
(defstruct vehicle-struct :make :model :year :color) ; short way
</pre>
</div>
    <p>
      The <code>struct</code> function creates
      an instance of a given StructMap.
      Values must be specified in the same order as their
      corresponding keys were specified when the StructMap was defined.
      Values for keys at the end can be omitted
      and their values will be <code>nil</code>.
      For example:
    </p>
    <div class="code">
<pre xml:space="preserve">
(def vehicle (struct vehicle-struct "Toyota" "Prius" 2009))
</pre>
</div>
    <p>
      The <code>accessor</code> function creates a function for
      accessing the value of a given key in instances
      that avoids performing a hash map lookup.
      For example:
    </p>
    <div class="code">
<pre xml:space="preserve">
; Note the use of def instead of defn because accessor returns
; a function that is then bound to "make".
(def make (accessor vehicle-struct :make))
(make vehicle) ; -&gt; "Toyota"
(vehicle :make) ; same but slower
(:make vehicle) ; same but slower
</pre>
</div>
    <p>
      New keys not specified when the StructMap was defined
      can be added to instances.
      However, keys specified when the StructMap was defined
      cannot be removed from instances.
    </p>
    
    <h2><a name="DefiningFunctions">Defining Functions</a></h2>
    <p>
      The <code>defn</code> macro defines a function.
      Its arguments are the function name,
      an optional documentation string
      (displayed by the <code>doc</code> macro),
      the parameter list (specified with a vector that can be empty)
      and the function body.
      The result of the last expression in the body is returned.
      Every function returns a value, but it may be <code>nil</code>.
      For example:
    </p>
    <div class="code">
<pre xml:space="preserve">
(defn parting
  "returns a String parting"
  [name]
  (str "Goodbye, " name)) ; concatenation

(println (parting "Mark")) ; -&gt; Goodbye, Mark
</pre>
</div>
    <p>
      Function definitions must appear before their first use.
      Sometimes this isn't possible due to
      a set of functions that invoke each other.
      The <code>declare</code> special form
      takes any number of function names and
      creates forward declarations that resolve these cases. For example:
    </p>
    <div class="code">
<pre xml:space="preserve">
(declare <i>function-names</i>)
</pre>
</div>
    <p>
      Functions defined with the <code>defn-</code> macro are private.
      This means they are only visible in the namespace
      in which they are defined.
      Other macros that produce private definitions,
      such as <code>defmacro-</code>,
      are in <code>clojure.core.incubator</code>.
    </p>
    <p>
      Functions can take a variable number of parameters.
      Optional parameters must appear at the end.
      They are gathered into a list by adding an ampersand and
      a name for the list at the end of the parameter list.
    </p>
    <div class="code">
<pre xml:space="preserve">
(defn power [base &amp; exponents]
  ; Using java.lang.Math static method pow.
  (reduce #(Math/pow %1 %2) base exponents))
(power 2 3 4) ; 2 to the 3rd = 8; 8 to the 4th = 4096
</pre>
</div>
    <p>
      Function definitions can contain more than one parameter list
      and corresponding body.
      Each parameter list must contain a different number of parameters.
      This supports overloading functions based on arity.
      Often it is useful for a body to call the same function
      with a different number of arguments in order to
      provide default values for some of them.
      For example:
    </p>
    <div class="code">
<pre xml:space="preserve">
(defn parting
  "returns a String parting in a given language"
  ([] (parting "World"))
  ([name] (parting name "en"))
  ([name language]
    ; condp is similar to a case statement in other languages.
    ; It is described in more detail later.
    ; It is used here to take different actions based on whether the
    ; parameter "language" is set to "en", "es" or something else.
    (condp = language
      "en" (str "Goodbye, " name)
      "es" (str "Adios, " name)
      (throw (IllegalArgumentException.
        (str "unsupported language " language))))))

(println (parting)) ; -&gt; Goodbye, World
(println (parting "Mark")) ; -&gt; Goodbye, Mark
(println (parting "Mark" "es")) ; -&gt; Adios, Mark
(println (parting "Mark", "xy"))
; -&gt; java.lang.IllegalArgumentException: unsupported language xy
</pre>
</div>
    <p>
      Anonymous functions have no name.
      These are often passed as arguments to a named function.
      They are handy for short function definitions
      that are only used in one place.
      There are two ways to define them, shown below:
    </p>
    <div class="code">
<pre xml:space="preserve">
(def years [1940 1944 1961 1985 1987])
(filter (fn [year] (even? year)) years) ; long way w/ named arguments -&gt; (1940 1944)
(filter #(even? %) years) ; short way where % refers to the argument
</pre>
</div>
    <p>
      When an anonymous function is defined
      using the <code>fn</code> special form,
      the body can contain any number of expressions.
    </p>
    <p>
      When an anonymous function is defined in the short way
      using <code>#(...)</code>,
      it can only contain a single expression.
      To use more than one expression,
      wrap them in the <code>do</code> special form.
      If there is only one parameter, it can be referred to with <code>%</code>.
      If there are multiple parameters, they are referred to with
      <code>%1</code>, <code>%2</code> and so on.
      For example:
    </p>
    <div class="code">
<pre xml:space="preserve">
(defn pair-test [test-fn n1 n2]
  (if (test-fn n1 n2) "pass" "fail"))

; Use a test-fn that determines whether
; the sum of its two arguments is an even number.
(println (pair-test #(even? (+ %1 %2)) 3 5)) ; -&gt; pass
</pre>
</div>
    <p>
      Java methods can be overloaded based on parameter types.
      Clojure functions can only be overloaded on arity.
      Clojure multimethods however, can be overloaded based on anything.
    </p>
    <p>
      The <code>defmulti</code> and <code>defmethod</code> macros
      are used together to define a multimethod.
      The arguments to <code>defmulti</code> are
      the method name and the dispatch function
      which returns a value that will be used to select a method.
      The arguments to <code>defmethod</code> are the method name,
      the dispatch value that triggers use of the method,
      the parameter list and the body.
      The special dispatch value <code>:default</code> is used to
      designate a method to be used when none of the others match.
      Each <code>defmethod</code> for the same multimethod name
      must take the same number of arguments.
      The arguments passed to a multimethod
      are passed to the dispatch function.
    </p>
    <p>
      Here's an example of a multimethod that overloads based on type.
    </p>
    <div class="code">
<pre xml:space="preserve">
(defmulti what-am-i class) ; class is the dispatch function
(defmethod what-am-i Number [arg] (println arg "is a Number"))
(defmethod what-am-i String [arg] (println arg "is a String"))
(defmethod what-am-i :default [arg] (println arg "is something else"))
(what-am-i 19) ; -&gt; 19 is a Number
(what-am-i "Hello") ; -&gt; Hello is a String
(what-am-i true) ; -&gt; true is something else
</pre>
</div>
    <p>
      Since the dispatch function can be any function,
      including one you write, the possibilities are endless.
      For example, a custom dispatch function could examine its arguments
      and return a keyword to indicate a size such as
      <code>:small</code>, <code>:medium</code> or <code>:large</code>.
      One method for each size keyword can provide logic
      that is specific to a given size.
    </p>
    <p>
      Underscores can be used as placeholders for function parameters
      that won't be used and therefore don't need a name.
      This is often useful in callback functions which are
      passed to another function so they can be invoked later.
      A particular callback function may not use all the arguments
      that are passed to it. For example:
    </p>
    <div class="code">
<pre xml:space="preserve">
(defn callback1 [n1 n2 n3] (+ n1 n2 n3)) ; uses all three arguments
(defn callback2 [n1 _ n3] (+ n1 n3)) ; only uses 1st &amp; 3rd arguments
(defn caller [callback value]
  (callback (+ value 1) (+ value 2) (+ value 3)))
(caller callback1 10) ; 11 + 12 + 13 -&gt; 36
(caller callback2 10) ; 11 + 13 -&gt; 24
</pre>
</div>
    <p>
      The <code>complement</code> function returns a new function
      that is just like a given function,
      but returns the opposite logical truth value.
      For example:
    </p>
    <div class="code">
<pre xml:space="preserve">
(defn teenager? [age] (and (&gt;= age 13) (&lt; age 20)))
(def non-teen? (complement teenager?))
(println (non-teen? 47)) ; -&gt; true
</pre>
</div>
    <p>
      The <code>comp</code> function composes a new function
      by combining any number of existing ones.
      They are called from right to left.
      For example:
    </p>
    <div class="code">
<pre xml:space="preserve">
(defn times2 [n] (* n 2))
(defn minus3 [n] (- n 3))
; Note the use of def instead of defn because comp returns
; a function that is then bound to "my-composition".
(def my-composition (comp minus3 times2))
(my-composition 4) ; 4*2 - 3 -&gt; 5
</pre>
</div>
    <p>
      The <code>partial</code> function creates a new function
      from an existing one
      so that it provides fixed values for initial parameters
      and calls the original function.
      This is called a "partial application".
      For example, <code>*</code> is a function that
      takes any number of arguments and multiplies them together.
      Suppose we want a new version of that function
      that always multiplies by two.
    </p>
    <div class="code">
<pre xml:space="preserve">
; Note the use of def instead of defn because partial returns
; a function that is then bound to "times2".
(def times2 (partial * 2))
(times2 3 4) ; 2 * 3 * 4 -&gt; 24
</pre>
</div>
    <p>
      <a name="polynomials">Here's</a> an interesting use of both
      the <code>map</code> and <code>partial</code> functions.
      We'll define functions that use the <code>map</code> function
      to compute the value of an arbitrary polynomial
      and its derivative for given x values.
      The polynomials are described by a vector of their coefficients.
      Next, we'll define functions that use <code>partial</code>
      to define functions for a specific polynomial and its derivative.
      Finally, we'll demonstrate using the functions.
    </p>
    <p>
      The <code>range</code> function returns a lazy sequence of integers
      from an inclusive lower bound to an exclusive upper bound.
      The lower bound defaults to 0, the step size defaults to 1,
      and the upper bound defaults to infinity.
    </p>
    <div class="code">
<pre xml:space="preserve">
(defn- polynomial
  "computes the value of a polynomial
   with the given coefficients for a given value x"
  [coefs x]
  ; For example, if coefs contains 3 values then exponents is (2 1 0).
  (let [exponents (reverse (range (count coefs)))]
    ; Multiply each coefficient by x raised to the corresponding exponent
    ; and sum those results.
    ; coefs go into %1 and exponents go into %2.
    (apply + (map #(* %1 (Math/pow x %2)) coefs exponents))))

(defn- derivative
  "computes the value of the derivative of a polynomial
   with the given coefficients for a given value x"
  [coefs x]
  ; The coefficients of the derivative function are obtained by
  ; multiplying all but the last coefficient by its corresponding exponent.
  ; The extra exponent will be ignored.
  (let [exponents (reverse (range (count coefs)))
        derivative-coefs (map #(* %1 %2) (butlast coefs) exponents)]
    (polynomial derivative-coefs x)))

(def f (partial polynomial [2 1 3])) ; 2x^2 + x + 3
(def f-prime (partial derivative [2 1 3])) ; 4x + 1

(println "f(2) =" (f 2)) ; -&gt; 13.0
(println "f'(2) =" (f-prime 2)) ; -&gt; 9.0
</pre>
</div>
    <p>
      Here's an another way that the polynomial function
      could be implemented (suggested by Francesco Strino).
      For a polynomial with coefficients a, b and c,
      it computes the value for x as follows:<br />
%1 = a, %2 = b, result is ax + b<br />
%1 = ax + b, %2 = c, result is (ax + b)x + c = ax^2 + bx + c
    </p>
    <div class="code">
<pre xml:space="preserve">
(defn- polynomial
  "computes the value of a polynomial
   with the given coefficients for a given value x"
  [coefs x]
  (reduce #(+ (* x %1) %2) coefs))
</pre>
</div>
    <p>
      The <code>memoize</code> function takes another function
      and returns a new function that
      stores a mapping from previous arguments to
      previous results for the given function.
      The new function uses the mapping to avoid invoking the given function
      with arguments that have already been evaluated.
      This results in better performance,
      but also requires memory to store the mappings.
    </p>
    <p>
      The <code>time</code> macro evaluates an expression,
      prints the elapsed time, and returns the expression result.
      It is used in the following code to measure the time
      to compute the value of a polynomial at a given x value.
    </p>
    <p>
      The following example demonstrates memoizing a polynomial function:
    </p>
    <div class="code">
<pre xml:space="preserve">
; Note the use of def instead of defn because memoize returns
; a function that is then bound to "memo-f".
(def memo-f (memoize f))

(println "priming call")
(time (f 2))

(println "without memoization")
; Note the use of an underscore for the binding that isn't used.
(dotimes [_ 3] (time (f 2)))

(println "with memoization")
(dotimes [_ 3] (time (memo-f 2)))
</pre>
</div>
    <p>
      The output produced by this code from a sample run is shown below.
    </p>
    <div class="code">
<pre xml:space="preserve">
priming call
"Elapsed time: 4.128 msecs"
without memoization
"Elapsed time: 0.172 msecs"
"Elapsed time: 0.365 msecs"
"Elapsed time: 0.19 msecs"
with memoization
"Elapsed time: 0.241 msecs"
"Elapsed time: 0.033 msecs"
"Elapsed time: 0.019 msecs"
</pre>
</div>
    <p>
      There are several observations than can be made from this output.
      The first call to the function <code>f</code>, the "priming call",
      takes considerably longer than the other calls.
      This is true regardless of whether memoization is used.
      The first call to the memoized function takes longer than
      the first non-priming call to the original function,
      due to the overhead of caching its result.
      Subsequent calls to the memoized function are much faster.
    </p>

    <h2><a name="JavaInterop">Java Interoperability</a></h2>
    <p>
      Clojure programs can use all Java classes and interfaces.
      As in Java, classes in the <code>java.lang</code> package
      can be used without importing them.
      Java classes in other packages can be used by either
      specifying their package when referencing them or
      using the <code>import</code> function.
      For example:
    </p>
    <div class="code">
<pre xml:space="preserve">
(import
  '(java.util Calendar GregorianCalendar)
  '(javax.swing JFrame JLabel))
</pre>
</div>
    <p>
      Also see the
      <code>
<a href="#nsMacro">:import</a>
</code> directive
      of the <code>ns</code> macro which is described later. </p>
    <p>
      There are two ways to access constants in a Java class,
      shown in the examples below:
    </p>
    <div class="code">
<pre xml:space="preserve">
(. java.util.Calendar APRIL) ; -&gt; 3
(. Calendar APRIL) ; works if the Calendar class was imported
java.util.Calendar/APRIL
Calendar/APRIL ; works if the Calendar class was imported
</pre>
</div>
    <p>
      Invoking Java methods from Clojure code is very easy.
      Because of this, Clojure doesn't provide functions for
      many common operations and instead relies on Java methods.
      For example, Clojure doesn't provide a function to find
      the absolute value of a floating point number
      because the <code>abs</code> method of the Java class
      <code>java.lang.Math</code> class already does that.
      On the other hand, while that class provides the method <code>max</code>
      to find the largest of two values, it only works with two values,
      so Clojure provides the <code>max</code> function
      which takes one or more values.
    </p>
    <p>
      There are two ways to invoke a static method in a Java class,
      shown in the examples below:
    </p>
    <div class="code">
<pre xml:space="preserve">
(. Math pow 2 4) ; -&gt; 16.0
(Math/pow 2 4)
</pre>
</div>
    <p>
      There are two ways to invoke a constructor to create a Java object,
      shown in the examples below.
      Note the use of the <code>def</code> special form
      to retain a reference to the new object in a global binding.
      This is not required.
      A reference could be retained in several other ways
      such as adding it to a collection or passing it to a function.
    </p>
    <div class="code">
<pre xml:space="preserve">
(import '(java.util Calendar GregorianCalendar))
(def calendar (new GregorianCalendar 2008 Calendar/APRIL 16)) ; April 16, 2008
(def calendar (GregorianCalendar. 2008 Calendar/APRIL 16))
</pre>
</div>
    <p>
      There are two ways to invoke an instance method on a Java object,
      shown in the examples below:
    </p>
    <div class="code">
<pre xml:space="preserve">
(. calendar add Calendar/MONTH 2)
(. calendar get Calendar/MONTH) ; -&gt; 5
(.add calendar Calendar/MONTH 2)
(.get calendar Calendar/MONTH) ; -&gt; 7
</pre>
</div>
    <p>
      The option in the examples above where
      the method name appears first is generally preferred.
      The option where the object appears first
      is easier to use inside macro definitions
      because syntax quoting can be used instead of string concatenation.
      This statement will make more sense after
      reading the "<a href="#Macros">Macros</a>" section ahead.
    </p>
    <p>
      Method calls can be chained using the <code>..</code> macro.
      The result from the previous method call in the chain
      becomes the target of the next method call. For example:
    </p>
    <div class="code">
<pre xml:space="preserve">
(. (. calendar getTimeZone) getDisplayName) ; long way
(.. calendar getTimeZone getDisplayName) ; -&gt; "Central Standard Time"
</pre>
</div>
    <p>
      There is also a <code>.?.</code> macro
      in the <code>clojure.core.incubator</code> namespace that
      stops and returns nil if any method in the chain returns null.
      This avoids getting a <code>NullPointerException</code>.
    </p>
    <p>
      The <code>doto</code> macro is used to
      invoke many methods on the same object.
      It returns the value of its first argument which is the target object.
      This makes it convenient to create the target object
      with an expression that is the first argument
      (see the creation of a <code>JFrame</code> GUI object
      in the "<a href="#doto">Namespaces</a>" section ahead).
      For example:
    </p>
    <div class="code">
<pre xml:space="preserve">
(doto calendar
  (.set Calendar/YEAR 1981)
  (.set Calendar/MONTH Calendar/AUGUST)
  (.set Calendar/DATE 1))
(def formatter (java.text.DateFormat/getDateInstance))
(.format formatter (.getTime calendar)) ; -&gt; "Aug 1, 1981"
</pre>
</div>
    <p>
      The <code>memfn</code> macro expands to code that allows
      a Java method to be treated as a first class function.
      It is an alternative to using an anonymous function
      for calling a Java method.
      When using <code>memfn</code> to invoke Java methods that take arguments,
      a name for each argument must be specified.
      This indicates the arity of the method to be invoked.
      These names are arbitrary, but they must be unique
      because they are used in the generated code.
      The following examples apply an instance method
      (<code>substring</code>)
      to a Java object from the first collection
      (a <code>String</code>),
      passing the corresponding item from the second collection
      (an <code>int</code>)
      as an argument:
    </p>
    <div class="code">
<pre xml:space="preserve">
(println (map #(.substring %1 %2)
           ["Moe" "Larry" "Curly"] [1 2 3])) ; -&gt; (oe rry ly)

(println (map (memfn substring beginIndex)
           ["Moe" "Larry" "Curly"] [1 2 3])) ; -&gt; same
</pre>
</div>

    <h3>Proxies</h3>
    <p>
      The <code>proxy</code> macro expands to code that creates a Java object
      that extends a given Java class and/or
      implements zero or more Java interfaces.
      This is often needed to implement callback methods in
      listener objects that must implement a certain interface
      in order to register for notifications from another object.
      For an example, see the
      "<a href="#DesktopApps">Desktop Applications</a>" section
      near the end of this article.
      It creates an object that extends the JFrame GUI class
      and implements the ActionListener interface.
    </p>

    <h3><a name="Threads">Threads</a></h3>
    <p>
      All Clojure functions implement both the
      <code>
<a href="http://java.sun.com/javase/6/docs/api/java/lang/Runnable.html">java.lang.Runnable</a>
</code>
      interface and the
      <code>
<a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/Callable.html">java.util.concurrent.Callable</a>
</code>
      interface.
      This makes it easy to execute them in new Java threads.
      For example:
    </p>
    <div class="code">
<pre xml:space="preserve">
(defn delayed-print [ms text]
  (Thread/sleep ms)
  (println text))

; Pass an anonymous function that invokes delayed-print
; to the Thread constructor so the delayed-print function
; executes inside the Thread instead of
; while the Thread object is being created.
(.start (Thread. #(delayed-print 1000 ", World!"))) ; prints 2nd
(print "Hello") ; prints 1st
; output is "Hello, World!"
</pre>
</div>

    <h3>Exception Handling</h3>
    <p>
      All exceptions thrown by Clojure code are runtime exceptions.
      Java methods invoked from Clojure code
      can still throw checked exceptions.
      The <code>try</code>, <code>catch</code>,
      <code>finally</code> and <code>throw</code>
      special forms provide functionality similar to
      their Java counterparts.
      For example:
    </p>
    <div class="code">
<pre xml:space="preserve">
 (defn collection? [obj]
  (println "obj is a" (class obj))
  ; Clojure collections implement clojure.lang.IPersistentCollection.
  (or (coll? obj) ; Clojure collection?
      (instance? java.util.Collection obj))) ; Java collection?

(defn average [coll]
  (when-not (collection? coll)
    (throw (IllegalArgumentException. "expected a collection")))
  (when (empty? coll)
    (throw (IllegalArgumentException. "collection is empty")))
  ; Apply the + function to all the items in coll,
  ; then divide by the number of items in it.
  (let [sum (apply + coll)]
    (/ sum (count coll))))

(try
  (println "list average =" (average '(2 3))) ; result is a clojure.lang.Ratio object
  (println "vector average =" (average [2 3])) ; same
  (println "set average =" (average #{2 3})) ; same
  (let [al (java.util.ArrayList.)]
    (doto al (.add 2) (.add 3))
    (println "ArrayList average =" (average al))) ; same
  (println "string average =" (average "1 2 3 4")) ; illegal argument
  (catch IllegalArgumentException e
    (println e)
    ;(.printStackTrace e) ; if a stack trace is desired
  )
  (finally
    (println "in finally")))
</pre>
</div>
    <p>
      The output produced by the code above follows:
    </p>
    <div class="code">
<pre xml:space="preserve">
obj is a clojure.lang.PersistentList
list average = 5/2
obj is a clojure.lang.LazilyPersistentVector
vector average = 5/2
obj is a clojure.lang.PersistentHashSet
set average = 5/2
obj is a java.util.ArrayList
ArrayList average = 5/2
obj is a java.lang.String
#&lt;IllegalArgumentException java.lang.IllegalArgumentException:
expected a collection&gt;
in finally
</pre>
</div>

    <h2><a name="ConditionalProcessing">Conditional Processing</a></h2>
    <p>
      The <code>if</code> special form tests a condition and
      executes one of two expressions based on
      whether the condition evaluates to true.
      Its syntax is
      <code>(if <i>condition</i> <i>then-expr</i> <i>else-expr</i>)</code>.
      The else expression is optional.
      If more than one expression is needed for the then or else part,
      use the <code>do</code> special form
      to wrap them in a single expression.
      For example:
    </p>
    <div class="code">
<pre xml:space="preserve">
(import '(java.util Calendar GregorianCalendar))
(let [gc (GregorianCalendar.)
      day-of-week (.get gc Calendar/DAY_OF_WEEK)
      is-weekend (or (= day-of-week Calendar/SATURDAY) (= day-of-week Calendar/SUNDAY))]
  (if is-weekend
    (println "play")
    (do (println "work")
        (println "sleep"))))
</pre>
</div>
    <p>
      The <code>when</code> and <code>when-not</code> macros
      provide alternatives to <code>if</code>
      when only one branch is needed.
      Any number of body expressions can be supplied
      without wrapping them in a <code>do</code>.
      For example:
    </p>
    <div class="code">
<pre xml:space="preserve">
(when is-weekend (println "play"))
(when-not is-weekend (println "work") (println "sleep"))
</pre>
</div>
    <p>
      The <code>if-let</code> macro binds a value to a single binding
      and chooses an expression to evaluate based on
      whether the value is logically true or false
      (explained in the "<a href="#Predicates">Predicates</a>" section).
      The following code prints the name of the first person
      waiting in line or prints "no waiting" if the line is empty.
    </p>
    <div class="code">
<pre xml:space="preserve">
(defn process-next [waiting-line]
  (if-let [name (first waiting-line)]
    (println name "is next")
    (println "no waiting")))

(process-next '("Jeremy" "Amanda" "Tami")) ; -&gt; Jeremy is next
(process-next '()) ; -&gt; no waiting
</pre>
</div>
    <p>
      The <code>when-let</code> macro is similar to
      the <code>if-let</code> macro, but it differs
      in the same way that <code>if</code> differs from <code>when</code>.
      It doesn't support an else part and
      the then part can contain any number of expressions.
      For example:
    </p>
    <div class="code">
<pre xml:space="preserve">
(defn summarize
  "prints the first item in a collection
  followed by a period for each remaining item"
  [coll]
  ; Execute the when-let body only if the collection isn't empty.
  (when-let [head (first coll)]
    (print head)
    ; Below, dec subtracts one (decrements) from
    ; the number of items in the collection.
    (dotimes [_ (dec (count coll))] (print \.))
    (println)))

(summarize ["Moe" "Larry" "Curly"]) ; -&gt; Moe..
(summarize []) ; -&gt; no output
</pre>
</div>
    <p>
      The <code>condp</code> macro is similar to
      a case statement in other languages.
      It takes a two parameter predicate
      (often <code>=</code> or <code>instance?</code>)
      and an expression to act as its second argument.
      After those it takes any number of value/result expression pairs
      that are evaluated in order.
      If the predicate evaluates to true
      when one of the values is used as its first argument
      then the corresponding result is returned.
      An optional final argument specifies the result to be returned
      if no given value causes the predicate to evaluate to true.
      If this is omitted and no given value causes
      the predicate to evaluate to true
      then an <code>IllegalArgumentException</code> is thrown.
    </p>
    <p>
      The following example prompts the user to enter a number
      and prints the name of that number only for 1, 2 and 3.
      Otherwise, it prints "unexpected value".
      After that, it examines the type of the local binding "value".
      If it is a <code>Number</code>,
      it prints the number times two.
      If it is a <code>String</code>,
      it prints the length of the string times two.
    </p>
    <div class="code">
<pre xml:space="preserve">
(print "Enter a number: ") (flush) ; stays in a buffer otherwise
(let [reader (java.io.BufferedReader. *in*) ; stdin
      line (.readLine reader)
      value (try
              (Integer/parseInt line)
              (catch NumberFormatException e line))] ; use string value if not integer
  (println
    (condp = value
      1 "one"
      2 "two"
      3 "three"
      (str "unexpected value, \"" value \")))
  (println
    (condp instance? value
      Number (* value 2)
      String (* (count value) 2))))
</pre>
</div>
    <p>
      The <code>cond</code> macro takes
      any number of predicate/result expression pairs.
      It evaluates the predicates in order until one evaluates to true
      and then returns the corresponding result.
      If none evaluate to true
      then an <code>IllegalArgumentException</code> is thrown.
      Often the predicate in the last pair is simply <code>true</code>
      to handle all remaining cases.
    </p>
    <p>
      The following example prompts the user to enter a water temperature.
      It then prints whether the water is freezing, boiling or neither.
    </p>
    <div class="code">
<pre xml:space="preserve">
(print "Enter water temperature in Celsius: ") (flush)
(let [reader (java.io.BufferedReader. *in*)
      line (.readLine reader)
      temperature (try
        (Float/parseFloat line)
        (catch NumberFormatException e line))] ; use string value if not float
  (println
    (cond
      (instance? String temperature) "invalid temperature"
      (&lt;= temperature 0) "freezing"
      (&gt;= temperature 100) "boiling"
      true "neither")))
</pre>
</div>

    <h2><a name="Iteration">Iteration</a></h2>
    <p>
      There are many ways to "loop" or iterate through items in a sequence.
    </p>
    <p>
      The <code>dotimes</code> macro executes the expressions in its body
      a given number of times, assigning values from zero to
      one less than that number to a specified local binding.
      If the binding isn't needed
      (<code>card-number</code> in the example below),
      an underscore can be used as its placeholder.
      For example:
    </p>
    <div class="code">
<pre xml:space="preserve">
(dotimes [card-number 3]
  (println "deal card number" (inc card-number))) ; adds one to card-number
</pre>
</div>
    <p>
      Note that the <code>inc</code> function is used so that
      the values 1, 2 and 3 are output instead of 0, 1 and 2.
      The code above produces the following output:
    </p>
    <div class="code">
<pre xml:space="preserve">
deal card number 1
deal card number 2
deal card number 3
</pre>
</div>
    <p>
      The <code>while</code> macro executes the expressions in its body
      while a test expression evaluates to true.
      The following example executes the <code>while</code> body
      while a given thread is still running:
    </p>
    <div class="code">
<pre xml:space="preserve">
(defn my-fn [ms]
  (println "entered my-fn")
  (Thread/sleep ms)
  (println "leaving my-fn"))

(let [thread (Thread. #(my-fn 1))]
  (.start thread)
  (println "started thread")
  (while (.isAlive thread)
    (print ".")
    (flush))
  (println "thread stopped"))
</pre>
</div>
    <p>
      The output from the code above will be similar to the following:
    </p>
    <div class="code">
<pre xml:space="preserve">
started thread
.....entered my-fn.
.............leaving my-fn.
thread stopped
</pre>
</div>
    <h3><a name="ListComprehension">List Comprehension</a></h3>
    <p>
      The <code>for</code> and <code>doseq</code> macros
      perform list comprehension.
      They support iterating through multiple collections
      (rightmost collection fastest)
      and optional filtering
      using <code>:when</code> and <code>:while</code> expressions.
      The <code>for</code> macro takes a single expression body
      and returns a lazy sequence of the results.
      The <code>doseq</code> macro takes a body containing
      any number of expressions, executes them for their side effects,
      and returns <code>nil</code>.
    </p>
    <p>
      The following examples both output names of some spreadsheet cells
      working down rows and then across columns.
      They skip the "B" column and only use rows that are less than 3.
      Note how the <code>dorun</code> function,
      described later in the "<a href="#Sequences">Sequences</a>" section,
      is used to force evaluation of the lazy sequence
      returned by the <code>for</code> macro.
    </p>
    <div class="code">
<pre xml:space="preserve">
(def cols "ABCD")
(def rows (range 1 4)) ; purposely larger than needed to demonstrate :while

(println "for demo")
(dorun
  (for [col cols :when (not= col \B)
        row rows :while (&lt; row 3)]
    (println (str col row))))

(println "\ndoseq demo")
(doseq [col cols :when (not= col \B)
        row rows :while (&lt; row 3)]
  (println (str col row)))
</pre>
</div>
    <p>
      The code above produces the following output:
    </p>
    <div class="code">
<pre xml:space="preserve">
for demo
A1
A2
C1
C2
D1
D2

doseq demo
A1
A2
C1
C2
D1
D2
</pre>
</div>
    <p>
      The <code>loop</code> special form, as its name suggests,
      supports looping. It and its companion special form
      <code>recur</code> are described in the next section.
    </p>

    <h2><a name="Recursion">Recursion</a></h2>
    <p>
      Recursion occurs when a function invokes itself either directly
      or indirectly through another function that it calls.
      Common ways in which recursion is terminated include
      checking for a collection of items to become empty
      or checking for a number to reach a specific value such as zero.
      The former case is often implemented by successively using
      the <code>next</code> function to process all but the first item.
      The latter case is often implemented by
      decrementing a number with the <code>dec</code> function.
    </p>
    <p>
      Recursive calls can result in running out of memory
      if the call stack becomes too deep.
      Some programming languages address this by supporting
      "<a href="http://en.wikipedia.org/wiki/Tail_call">tail call optimization</a>" (TCO).
      Java doesn't currently support TCO and neither does Clojure.
      One way to avoid this issue in Clojure is to use the
      <code>loop</code> and <code>recur</code> special forms.
      Another way is to use the
      <a href="http://clojure.github.com/clojure/clojure.core-api.html#clojure.core/trampoline">trampoline</a>
      function.
    </p>
    <p>
      The <code>loop</code>/<code>recur</code> idiom
      turns what looks like a recursive call
      into a loop that doesn't consume stack space.
      The <code>loop</code> special form is
      like the <code>let</code> special form
      in that they both establish local bindings,
      but it also establishes a recursion point
      that is the target of calls to <code>recur</code>.
      The bindings specified by <code>loop</code>
      provide initial values for the local bindings.
      Calls to <code>recur</code> cause control to
      return to the <code>loop</code> and
      assign new values to its local bindings.
      The number of arguments passed to <code>recur</code>
      must match the number of bindings in the <code>loop</code>.
      Also, <code>recur</code> can only appear
      as the last call in the <code>loop</code>.
    </p>
    <div class="code">
<pre xml:space="preserve">
(defn factorial-1 [number]
  "computes the factorial of a positive integer
   in a way that doesn't consume stack space"
  (loop [n number factorial 1]
    (if (zero? n)
      factorial
      (recur (dec n) (* factorial n)))))

(println (time (factorial-1 5))) ; -&gt; "Elapsed time: 0.071 msecs"\n120
</pre>
</div>
    <p>
      The <code>defn</code> macro,
      like the <code>loop</code> special form,
      establishes a recursion point.
      The <code>recur</code> special form can also be used
      as the last call in a function to
      return to the beginning of that function with new arguments.
    </p>
    <p>
      Another way to implement the factorial function
      is to use the <code>reduce</code> function.
      This was described back in the
      "<a href="#reduce">Collections</a>" section.
      It supports a more functional, less imperative style.
      Unfortunately, in this case, it is less efficient.
      Note that the <code>range</code> function takes
      a lower bound that is inclusive and
      an upper bound that is exclusive.
    </p>
    <div class="code">
<pre xml:space="preserve">
(defn factorial-2 [number] (reduce * (range 2 (inc number))))

(println (time (factorial-2 5))) ; -&gt; "Elapsed time: 0.335 msecs"\n120
</pre>
</div>
    <p>
      The same result can be obtained by replacing <code>reduce</code>
      with <code>apply,</code> but that takes even longer.
      This illustrates the importance of understanding
      the characteristics of functions when choosing between them.
    </p>
    <p>
      The <code>recur</code> special form
      isn't suitable for mutual recursion
      where a function calls another function
      which calls back to the original function.
      The <code>
<a href="http://clojure.github.com/clojure/clojure.core-api.html#clojure.core/trampoline">trampoline</a>
</code>
      function, not covered here, does support mutual recursion.
    </p>

    <h2><a name="Predicates">Predicates</a></h2>
    <p>
      Clojure provides many functions that act as predicates,
      used to test a condition.
      They return a value that can be interpreted as true or false.
      The values <code>false</code> and <code>nil</code>
      are interpreted as false.
      The value <code>true</code> and every other value, including zero,
      are interpreted as true.
      Predicate functions usually have a name that ends in a question mark.
    </p>
    <p>
      Reflection involves obtaining information about an object
      other than its value, such as its type.
      There are many predicate functions that perform reflection.
      Predicate functions that test the type of a single object include
      <code>class?</code>, <code>coll?</code>, <code>decimal?</code>,
      <code>delay?</code>, <code>float?</code>, <code>fn?</code>,
      <code>instance?</code>, <code>integer?</code>, <code>isa?</code>,
      <code>keyword?</code>, <code>list?</code>,
      <code>macro?</code>, <code>map?</code>, <code>number?</code>,
      <code>seq?</code>, <code>set?</code>, <code>string?</code>
      and <code>vector?</code>.
      Some non-predicate functions that perform reflection include
      <code>ancestors</code>, <code>bases</code>, <code>class</code>,
      <code>ns-publics</code> and <code>parents</code>.
    </p>
    <p>
      Predicate functions that test relationships between values include
      <code>&lt;</code>, <code>&lt;=</code>, <code>=</code>,
      <code>not=</code>, <code>==</code>, <code>&gt;</code>,
      <code>&gt;=</code>, <code>compare</code>, <code>distinct?</code>
      and <code>identical?</code>.
    </p>
    <p>
      Predicate functions that test logical relationships include
      <code>and</code>, <code>or</code>, <code>not</code>,
      <code>true?</code>, <code>false?</code> and <code>nil?</code>
    </p>
    <p>
      Predicate functions that test sequences,
      most of which were discussed earlier, include
      <code>empty?</code>, <code>not-empty</code>,
      <code>every?</code>, <code>not-every?</code>,
      <code>some</code> and <code>not-any?</code>.
    </p>
    <p>
      Predicate functions that test numbers include
      <code>even?</code>, <code>neg?</code>, <code>odd?</code>,
      <code>pos?</code> and <code>zero?</code>.
    </p>

    <h2><a name="Sequences">Sequences</a></h2>
    <p>
      Sequences are logical views of collections.
      Many things can be treated as sequences.
      These include Java collections, Clojure-specific collections,
      strings, streams, directory structures and XML trees.
    </p>
    <p>
      Many Clojure functions return a lazy sequence.
      This is a sequence whose items can be the result of function calls
      that aren't evaluated until they are needed.
      A benefit of creating a lazy sequence is that it isn't
      necessary to anticipate how many items in it will
      actually be used at the time the sequence is created.
      Examples of functions and macros that return lazy sequences include:
      <code>cache-seq</code>, <code>concat</code>, <code>cycle</code>,
      <code>distinct</code>, <code>drop</code>, <code>drop-last</code>,
      <code>drop-while</code>, <code>filter</code>, <code>for</code>,
      <code>interleave</code>, <code>interpose</code>,
      <code>iterate</code>, <code>lazy-cat</code>,
      <code>lazy-seq</code>, <code>line-seq</code>, <code>map</code>,
      <code>partition</code>, <code>range</code>, <code>re-seq</code>,
      <code>remove</code>, <code>repeat</code>, <code>replicate</code>,
      <code>take</code>, <code>take-nth</code>, <code>take-while</code>
      and <code>tree-seq</code>.
    </p>
    <p>
      Lazy sequences are a common source of confusion
      for new Clojure developers.
      For example, what does the following code output?
    </p>
    <div class="code">
<pre xml:space="preserve">
(map #(println %) [1 2 3])
</pre>
</div>
    <p>
      When run in a REPL, this outputs the values 1, 2 and 3
      on separate lines interspersed with
      a sequence of three <code>nil</code>s
      which are the return values from three calls
      to the <code>println</code> function.
      The REPL always fully evaluates
      the results of the expressions that are entered.
      However, when run as part of a script, nothing is output by this code.
      This is because the <code>map</code> function returns a lazy sequence
      containing the results of applying its first argument function
      to each of the items in its second argument collection.
      The documentation string for the <code>map</code> function
      clearly states that it returns a lazy sequence.
    </p>
    <p>
      There are many ways to force the evaluation
      of items in a lazy sequence.
      Functions that extract a single item such as
      <code>first</code>, <code>second</code>, <code>nth</code>
      and <code>last</code> do this.
      The items in the sequence are evaluated in order,
      so items before the one requested are also evaluated.
      For example, requesting the last item
      causes every item to be evaluated.
    </p>
    <p>
      If the head of a lazy sequence is held in a binding,
      once an item has been evaluated its value is cached
      so it isn't reevaluated if requested again.
    </p>
    <p>
      The <code>dorun</code> and <code>doall</code> functions
      force the evaluation of items in a single lazy sequence.
      The <code>doseq</code> macro, discussed earlier
      in the "<a href="#Iteration">Iteration</a>" section,
      forces the evaluation of items in one or more lazy sequences.
      The <code>for</code> macro, discussed in that same section,
      does not force evaluation and instead returns another lazy sequence.
    </p>
    <p>
      Using <code>doseq</code> or <code>dorun</code> is appropriate
      when the goal is to simply cause
      the side effects of the evaluations to occur.
      The results of the evaluations are not retained,
      so less memory is consumed.
      They both return <code>nil</code>.
      Using <code>doall</code> is appropriate
      when the evaluation results need to be retained.
      It holds the head of the sequence
      which causes the results to be cached
      and it returns the evaluated sequence.
    </p>
    <p>
      The table below illustrates the options for
      forcing the evaluation of items in a lazy sequence.
    </p>
    <table border="1">
      <tr>
        <th></th>
        <th valign="bottom">Retain evaluation results</th>
        <th align="left" valign="bottom">
          Discard evaluation results<br />
          and only cause side effects
        </th>
      </tr>
      <tr>
        <th style="text-align:left">Operate on a single sequence</th>
        <td><code>doall</code></td>
        <td><code>dorun</code></td>
      </tr>
      <tr>
        <th style="text-align:left">
          Operate on any number of sequences<br />
          with list comprehension syntax
        </th>
        <td>N/A</td>
        <td><code>doseq</code></td>
      </tr>
    </table>
    <p>
      The <code>doseq</code> macro is typically preferred
      over the <code>dorun</code> function
      because the code is easier to read.
      It is also faster because a call to <code>map</code>
      inside <code>dorun</code> creates another sequence.
      For example, the following lines both produce the same output:
    </p>
    <div class="code">
<pre xml:space="preserve">
(dorun (map #(println %) [1 2 3]))
(doseq [i [1 2 3]] (println i))
</pre>
</div>
    <p>
      If a function creates a lazy sequence that
      will have side effects when its items are evaluated,
      in most cases it should force the evaluation of the sequence
      with <code>doall</code> and return its result.
      This makes the timing of the side effects more predictable.
      Otherwise callers could evaluate the lazy sequence
      any number of times
      resulting in the side effects being repeated.
    </p>
    <p>
      The following expressions all output 1, 2, 3 on separate lines,
      but they have different return values.
      The <code>do</code> special form is used here to implement
      an anonymous function that does more than one thing,
      print the value passed in and return it.
    </p>
    <div class="code">
<pre xml:space="preserve">
(doseq [item [1 2 3]] (println item)) ; -&gt; nil
(dorun (map #(println %) [1 2 3])) ; -&gt; nil
(doall (map #(do (println %) %) [1 2 3])) ; -&gt; (1 2 3)
</pre>
</div>
    <p>
      Lazy sequences make it possible to create infinite sequences
      since all the items don't need to be evaluated.
      For example:
    </p>
    <div class="code">
<pre xml:space="preserve">
(defn f
  "square the argument and divide by 2"
  [x]
  (println "calculating f of" x)
  (/ (* x x) 2.0))

; Create an infinite sequence of results from the function f
; for the values 0 through infinity.
; Note that the head of this sequence is being held in the binding "f-seq".
; This will cause the values of all evaluated items to be cached.
(def f-seq (map f (iterate inc 0)))

; Force evaluation of the first item in the infinite sequence, (f 0).
(println "first is" (first f-seq)) ; -&gt; 0.0

; Force evaluation of the first three items in the infinite sequence.
; Since the (f 0) has already been evaluated,
; only (f 1) and (f 2) will be evaluated.
(doall (take 3 f-seq))

(println (nth f-seq 2)) ; uses cached result -&gt; 2.0
</pre>
</div>
    <p>
      Here's a variation on the previous code that does not
      hold the head of the lazy sequence in a binding.
      Note how the sequence is defined as the result of a function
      rather than the value of a binding.
      The results for evaluated items are not cached.
      This reduces memory requirements, but is less efficient
      when items are requested more than once.
    </p>
    <div class="code">
<pre xml:space="preserve">
(defn f-seq [] (map f (iterate inc 0)))
(println (first (f-seq))) ; evaluates (f 0), but doesn't cache result
(println (nth (f-seq) 2)) ; evaluates (f 0), (f 1) and (f 2)
</pre>
</div>
    <p>
      Another way to avoid
      holding the head of a lazy sequence in a binding
      is to pass the lazy sequence directly to a function
      that will evaluate its items.
      For example:
    </p>
    <div class="code">
<pre xml:space="preserve">
(defn consumer [seq]
  ; Since seq is a local binding, the evaluated items in it
  ; are cached while in this function and then garbage collected.
  (println (first seq)) ; evaluates (f 0)
  (println (nth seq 2))) ; evaluates (f 1) and (f 2)

(consumer (map f (iterate inc 0)))
</pre>
</div>
    
    <h2><a name="IO">Input/Output</a></h2>
    <p>
      Clojure provides a minimal set of functions
      that perform I/O operations.
      Since Java classes are easy to use from Clojure code,
      the classes in the <code>java.io</code> package
      can be used directly.
      However, the clojure.java.io library
      makes many uses of those classes easier.
    </p>
    <p>
      The predefined, special symbols
      <code>*in*</code>, <code>*out*</code> and <code>*err*</code>
      are set to stdin, stdout and stderr by default.
      To flush buffered output in <code>*out*</code>,
      use <code>(flush)</code>
      which is the same as <code>(.flush *out*)</code>.
      The bindings for these symbols can be modified.
      For example, to redirect output that goes to stdout by default
      so it goes to a file named "<code>my.log</code>",
      surround the code to be affected as follows:
    </p>
    <div class="code">
<pre xml:space="preserve">
(binding [*out* (java.io.FileWriter. "my.log")]
  ...
  (println "This goes to the file my.log.")
  ...
  (flush))
</pre>
</div>
    <p>
      The <code>print</code> function prints the string representation
      of any number of objects, with a space between each one,
      to the stream in the special symbol <code>*out*</code>.
    </p>
    <p>
      The <code>println</code> function is like <code>print</code>,
      but it outputs a newline character at the end.
      By default, it also flushes its output.
      This can be changed by binding the special symbol
      <code>*flush-on-newline*</code> to <code>false</code>.
    </p>
    <p>
      The <code>newline</code> function writes a newline character
      to the stream in <code>*out*</code> .
      Calling <code>print</code> followed by <code>newline</code>
      is equivalent to <code>println</code>.
    </p>
    <p>
      The <code>pr</code> and <code>prn</code> functions are like
      their <code>print</code> and <code>println</code> counterparts,
      but their output is in a form that can be read by the Clojure reader.
      They are suitable for serializing Clojure data structures.
      By default, they do not print metadata.
      This can be changed by binding
      the special symbol <code>*print-meta*</code> to <code>true</code>.
    </p>
    <p>
      The following examples demonstrate all four of the printing functions.
      Note how the output for strings and characters differs depending on
      whether the <code>print</code> or <code>pr</code> functions are used.
    </p>
    <div class="code">
<pre xml:space="preserve">
(let [obj1 "foo"
      obj2 {:letter \a :number (Math/PI)}] ; a map
  (println "Output from print:")
  (print obj1 obj2)

  (println "Output from println:")
  (println obj1 obj2)

  (println "Output from pr:")
  (pr obj1 obj2)

  (println "Output from prn:")
  (prn obj1 obj2))
</pre>
</div>
    <p>
      The code above produces the following output:
    </p>
    <div class="code">
<pre xml:space="preserve">
Output from print:
foo {:letter a, :number 3.141592653589793}Output from println:
foo {:letter a, :number 3.141592653589793}
Output from pr:
"foo" {:letter \a, :number 3.141592653589793}Output from prn:
"foo" {:letter \a, :number 3.141592653589793}
</pre>
</div>
    <p>
      All the printing functions discussed above add a space between
      the output of their arguments.
      The <code>str</code> function can be used to avoid this.
      It concatenates the string representations of its arguments.
      For example:
    </p>
    <div class="code">
<pre xml:space="preserve">
(println "foo" 19) ; -&gt; foo 19
(println (str "foo" 19)) ; -&gt; foo19
</pre>
</div>
    <p>
      The <code>print-str</code>, <code>println-str</code>,
      <code>pr-str</code> and <code>prn-str</code> functions
      are similar to their
      <code>print</code>, <code>println</code>,
      <code>pr</code> and <code>prn</code> counterparts,
      but they print to a string that is returned
      instead of printing to <code>*out*</code>.
    </p>
    <p>
      The <code>printf</code> function is similar to <code>print</code>,
      but uses a format string.
      The <code>format</code> function is similar to <code>printf</code>,
      but prints to a string that is returned
      instead of printing to <code>*out*</code>.
    </p>
    <p>
      The <code>with-out-str</code> macro captures the output from
      all the expressions in its body in a string and returns it.
    </p>
    <p>
      The <code>with-open</code> macro takes any number of bindings
      to objects on which <code>.close</code> should be called
      after the expressions in its body are executed.
      It is ideal for processing resources such as
      files and database connections.
    </p>
    <p>
      The <code>line-seq</code> function
      takes a <code>java.io.BufferedReader</code>
      and returns a lazy sequence of all the lines of text in it.
      The significance of returning a "lazy" sequence is that
      it doesn't really read all of the lines when it is called.
      That could consume too much memory.
      Instead it reads a line each time
      one is requested from the lazy sequence.
    </p>
    <p>
      The following example demonstrates both
      <code>with-open</code> and <code>line-seq</code>.
      It reads all the lines in a file
      and prints those that contain a given word.
    </p>
    <div class="code">
<pre xml:space="preserve">
(use '[clojure.java.io :only (reader)])

(defn print-if-contains [line word]
  (when (.contains line word) (println line)))

(let [file "story.txt"
      word "fur"]

  ; with-open will close the reader after
  ; evaluating all the expressions in its body.
  (with-open [rdr (reader file)]
    (doseq [line (line-seq rdr)] (print-if-contains line word))))
</pre>
</div>
    <p>
      The <code>slurp</code> function reads the entire contents of a file
      into a string and returns it.
      The <code>spit</code> function
      writes a string to a given file and closes it.
    </p>
    <p>
      This article only scratches the surface
      of what the core and java.io libraries provide.
      It's a worthwhile investment to read through
      the file <code>clojure/java/io.clj</code>
      to learn about the other functions it defines.
    </p>

    <h2><a name="Destructuring">Destructuring</a></h2>
    <p>
      Destructuring can be used in the parameter list of a function or macro
      to extract parts of collections into local bindings.
      It can also be used in bindings created using
      the <code>let</code> special form and the <code>binding</code> macro.
    </p>
    <p>
      For example, suppose we want a function that takes a list or vector
      and returns the sum of its first and third items.
    </p>
    <div class="code">
<pre xml:space="preserve">
(defn approach1 [numbers]
  (let [n1 (first numbers)
        n3 (nth numbers 2)]
    (+ n1 n3)))

; Note the underscore used to represent the
; second item in the collection which isn't used.
(defn approach2 [[n1 _ n3]] (+ n1 n3))

(approach1 [4 5 6 7]) ; -&gt; 10
(approach2 [4 5 6 7]) ; -&gt; 10
</pre>
</div>
    <p>
      The ampersand character can be used with destructuring
      to capture the remaining items in a collection. For example:
    </p>
    <div class="code">
<pre xml:space="preserve">
(defn name-summary [[name1 name2 &amp; others]]
  (println (str name1 ", " name2) "and" (count others) "others"))

(name-summary ["Moe" "Larry" "Curly" "Shemp"]) ; -&gt; Moe, Larry and 2 others
</pre>
</div>
    <p>
      The <code>:as</code> keyword can be used to retain access to
      the entire collection that is being destructured.
      Suppose we want a function that takes a list or vector
      and returns the sum of the first and third items
      divided by the sum of all the items.
    </p>
    <div class="code">
<pre xml:space="preserve">
(defn first-and-third-percentage [[n1 _ n3 :as coll]]
  (/ (+ n1 n3) (apply + coll)))

(first-and-third-percentage [4 5 6 7]) ; ratio reduced from 10/22 -&gt; 5/11
</pre>
</div>
    <p>
      Destructuring can also be used to extract values from maps.
      Suppose we want a function that takes a map of sales figures where
      each key is a month and each value is the sales total for that month.
      The function sums the sales for summer months and divides by the
      sales for all the months to determine the percentage of all sales
      that occurred in the summer.
    </p>
    <div class="code">
<pre xml:space="preserve">
(defn summer-sales-percentage
  ; The keywords below indicate the keys whose values
  ; should be extracted by destructuring.
  ; The non-keywords are the local bindings
  ; into which the values are placed.
  [{june :june july :july august :august :as all}]
  (let [summer-sales (+ june july august)
        all-sales (apply + (vals all))]
    (/ summer-sales all-sales)))

(def sales {
  :january 100 :february 200 :march 0 :april 300
  :may 200 :june 100 :july 400 :august 500
  :september 200 :october 300 :november 400 :december 600})

(summer-sales-percentage sales) ; ratio reduced from 1000/3300 -&gt; 10/33
</pre>
</div>
    <p>
      It is common when destructuring maps to use
      local binding names whose names match corresponding keys.
      For example, in the code above we used
      <code>{june :june july :july august :august :as all}</code>.
      This can be simplified using <code>:keys</code>.
      For example, <code>{:keys [june july august] :as all}</code>.
    </p>

    <h2><a name="Namespaces">Namespaces</a></h2>
    <p>
      Java groups methods in classes and classes in packages.
      Clojure groups things that are named by symbols in namespaces.
      These include Vars, Refs, Atoms, Agents,
      functions, macros and namespaces themselves.
    </p>
    <p>
      Symbols are used to assign names to functions, macros and bindings.
      Symbols are partitioned into namespaces.
      There is always a current default namespace, initially set to "user",
      and it is stored in the special symbol <code>*ns*</code>.
      The default namespace can be changed in two ways.
      The <code>in-ns</code> function merely changes it.
      The <code>ns</code> macro does that and much more.
      One extra thing it does is make all the symbols in the
      <code>clojure.core</code> namespace available in the new namespace
      (using <code>refer</code> which is described later).
      Other features of the <code>ns</code> macro are described later.
    </p>
    <p>
      The "user" namespace provides access to all the symbols in
      the <code>clojure.core</code> namespace.
      The same is true of any namespace that is made the default
      through use of the <code>ns</code> macro.
    </p>
    <p>
      In order to access items that are not in the default namespace
      they must be namespace-qualified.
      This is done by preceding a name with a namespace name and a slash.
      For example, the clojure.string library defines
      the <code>join</code> function.
      It creates a string by concatenating a given
      separator string between the string representation of
      all the items in a sequence.
      The namespace-qualified name of this function is
      <code>clojure.string/join</code>.
    </p>
    <p>
      <a name="require">The</a> <code>require</code> function
      loads Clojure libraries.
      It takes one or more quoted namespace names.
      For example:
    </p>
    <div class="code">
<pre xml:space="preserve">
(require 'clojure.string)
</pre>
</div>
    <p>
      This merely loads the library.
      Names in it must still be namespace-qualified
      in order to refer to them.
      Note that namespace names are separated from a name with a slash,
      whereas Java package names are separated from a class name with a period.
      For example:
    </p>
    <div class="code">
<pre xml:space="preserve">
(clojure.string/join "$" [1 2 3]) ; -&gt; "1$2$3"
</pre>
</div>
    <p>
      The <code>alias</code> function creates an alias for a namespace
      to reduce the amount of typing required to namespace-qualify symbols.
      Aliases are defined and only known within the current namespace.
      For example:
    </p>
    <div class="code">
<pre xml:space="preserve">
(alias 'su 'clojure.string)
(su/join "$" [1 2 3]) ; -&gt; "1$2$3"
</pre>
</div>
    <p>
      The <code>refer</code> function makes all the symbols
      in a given namespace accessible in the current namespace
      without namespace-qualifying them.
      An exception is thrown if a name in the given namespace
      is already defined in the current namespace.
      For example:
    </p>
    <div class="code">
<pre xml:space="preserve">
(refer 'clojure.string)
</pre>
</div>
    <p>
      Now the previous code can be written as:
    </p>
    <div class="code">
<pre xml:space="preserve">
(join "$" [1 2 3]) ; -&gt; "1$2$3"
</pre>
</div>
    <p>
      The combination of <code>require</code> and <code>refer</code>
      is used often, so the shortcut function <code>use</code>
      is provided to do both.
    </p>
    <div class="code">
<pre xml:space="preserve">
(use 'clojure.string)
</pre>
</div>
    <p>
      <a name="nsMacro">The</a> <code>ns</code> macro, mentioned earlier,
      changes the default namespace.
      It is typically used at the top of a source file.
      It supports the directives
      <code>:require</code>, <code>:use</code> and
      <code>:import</code> (for importing Java classes)
      that are alternatives to using their function forms.
      Using these is preferred over using their function forms.
      In the example below,
      note the use of <code>:as</code> to create an alias for a namespace.
      Also note the use of <code>:only</code>
      to load only part of a Clojure library.
    </p>
    <div class="code">
<pre xml:space="preserve">
(ns com.ociweb.demo
  (:require [clojure.string :as su])
  ; assumes this dependency: [org.clojure/math.numeric-tower "0.0.1"]
  (:use [clojure.math.numeric-tower :only (gcd, sqrt)])
  (:import (java.text NumberFormat) (javax.swing JFrame JLabel)))

(println (su/join "$" [1 2 3])) ; -&gt; 1$2$3
(println (gcd 27 72)) ; -&gt; 9
(println (sqrt 5)) ; -&gt; 2.23606797749979
(println (.format (NumberFormat/getInstance) Math/PI)) ; -&gt; 3.142
    
; See the screenshot that follows this code.
(<a name="doto">doto</a> (JFrame. "Hello")
  (.add (JLabel. "Hello, World!"))
  (.pack)
  (.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE)
  (.setVisible true))
</pre>
</div>
    <p>
      <img src="images/SwingDemo.png" alt="Swing demo" width="400px"/>
    </p>
    <p>
      The <code>create-ns</code> function creates a new namespace,
      but doesn't make it the default.
      The <code>def</code> function defines a symbol in the
      default namespace with an optional initial value.
      The <code>intern</code> function defines a symbol
      in a given namespace (if the symbol doesn't already exist)
      and optionally gives it an initial value.
      Note that the symbol name needs to be
      quoted for <code>intern</code>, but not for <code>def</code>.
      This is because <code>def</code> is a special form that
      doesn't evaluate all of its arguments, whereas <code>intern</code>
      is a function, which means it evaluates all of its arguments.
      For example:
    </p>
    <div class="code">
<pre xml:space="preserve">
(def foo 1)
(create-ns 'com.ociweb.demo)
(intern 'com.ociweb.demo 'foo 2)
(println (+ foo com.ociweb.demo/foo)) ; -&gt; 3
</pre>
</div>
    <p>
      The <code>ns-interns</code> function returns a map containing
      all the symbols defined in a given, currently loaded namespace.
      The map has keys that are <code>Symbol</code> objects
      for the names and
      values which are <code>Var</code> objects
      representing functions, macros and bindings.
      For example:
    </p>
    <div class="code">
<pre xml:space="preserve">
(ns-interns 'clojure.math.numeric-tower)
</pre>
</div>
    <p>
      The <code>all-ns</code> function returns
      a sequence of the currently loaded namespaces.
      The following namespaces are loaded by default
      when a Clojure program is run:
      <code>clojure.core</code>,
      <code>clojure.main</code>,
      <code>clojure.set</code>,
      <code>clojure.xml</code>,
      <code>clojure.zip</code> and
      <code>user</code>.
      The following additional namespaces are loaded by default in a REPL:
      <code>clojure.repl</code> and
      <code>clojure.java.javadoc</code>.
    </p>
    <p>
      The <code>namespace</code> function returns
      the namespace of a given symbol or keyword.
    </p>
    <p>
      Other namespace related functions not discussed here include
      <code>ns-aliases</code>,
      <code>ns-imports</code>,
      <code>ns-map</code>,
      <code>ns-name</code>,
      <code>ns-publics</code>,
      <code>ns-refers</code>,
      <code>ns-unalias</code>,
      <code>ns-unmap</code> and
      <code>remove-ns</code>.
    </p>
    <h3>Some Fine Print</h3>
    <p>
      A <code>Symbol</code> object has a <code>String</code> name and
      a <code>String</code> namespace name (called <code>ns</code>),
      but no value.
      The fact that it uses a String namespace name
      instead of a <code>Namespace</code> object reference
      allows it to be in a namespace that doesn't yet exist.
      A <code>Var</code> objects has references to
      a <code>Symbol</code> object (called <code>sym</code>),
      a <code>Namespace</code> object (called <code>ns</code>)
      and an <code>Object</code> object which is its "root value"
      (called <code>root</code>).
      <code>Namespace</code> objects have a reference to a <code>Map</code>
      that holds associations between <code>Symbol</code> objects
      and <code>Var</code> objects (named <code>mappings</code>).
      They also have a reference to a <code>Map</code> that holds
      associations between <code>Symbol</code> aliases
      and <code>Namespace</code> objects (called <code>namespaces</code>).
      See the class diagram below which shows a small subset
      of the attributes and key relationships between the
      Java classes and interfaces in the Clojure implementation.
      In Clojure, the term "interning" typically refers to adding a
      <code>Symbol</code>-to-<code>Var</code> mapping
      to a <code>Namespace</code>.
    </p>
    <p>
      <img src="images/ClassDiagram.png" alt="class diagram"/>
    </p>

    <h2><a name="Metadata">Metadata</a></h2>
    <p>
      Clojure metadata is data attached to a symbol or collection
      that is not related to its logical value.
      Two objects that are logically equal,
      such as two cards that are both the king of clubs,
      can have different metadata.
      For example, metadata can be used to indicate whether a card is bent.
      For the purpose of most card games, the fact that a card is bent
      has no bearing on the value of the card.
    </p>
    <div class="code">
<pre xml:space="preserve">
(defstruct card-struct :rank :suit)

(def card1 (struct card-struct :king :club))
(def card2 (struct card-struct :king :club))

(println (== card1 card2)) ; same identity? -&gt; false
(println (= card1 card2)) ; same value? -&gt; true

(def card2 ^{:bent true} card2) ; adds metadata at read-time
(def card2 (with-meta card2 {:bent true})) ; adds metadata at run-time
(println (meta card1)) ; -&gt; nil
(println (meta card2)) ; -&gt; {:bent true}
(println (= card1 card2)) ; still same value despite metadata diff. -&gt; true
</pre>
</div>
    <p>
      Some metadata names have a designated use in Clojure.
      <code>:private</code> has a boolean value that indicates whether
      access to a Var is restricted
      to the namespace in which it is defined.
      <code>:doc</code> is a documentation string for a Var.
      <code>:test</code> has a boolean value that indicates whether
      a function that takes no arguments is a test function.
    </p>
    <p>
      <code>:tag</code> is a string class name
      or a <code>Class</code> object that describes
      the Java type of a Var or the return type of a function.
      These are referred to as "type hints".
      Providing them can improve performance.
      To see where in your code Clojure is using reflection
      to determine types, and therefore taking a performance hit,
      set the global variable <code>*warn-on-reflection*</code>
      to <code>true</code>.
    </p>
    <p>
      Some metadata is automatically attached to Vars
      by the Clojure compiler.
      <code>:file</code> is the string name of the file
      that defines the Var.
      <code>:line</code> is the integer line number within the file
      where the Var is defined.
      <code>:name</code> is a <code>Symbol</code>
      that provides a name for the Var.
      <code>:ns</code> is a <code>Namespace</code> object
      that describes the namespace
      in which the Var is defined.
      <code>:macro</code> is a boolean that indicates
      whether a Var is a macro
      as opposed to a function or binding.
      <code>:arglist</code> is a list of vectors where each vector
      describes the names of the parameters a function accepts.
      Recall that a function can have
      more than one parameter list and body.
    </p>
    <p>
      Functions and macros, both represented by a <code>Var</code> object,
      have associated metadata.
      For example, enter the following in a REPL:
      <code>(meta (var reverse))</code>.
      The output will be similar to the following, but on a single line:
    </p>
    <div class="code">
<pre xml:space="preserve">
{
  :ns #&lt;Namespace clojure.core&gt;,
  :name reverse,
  :file "core.clj",
  :line 630,
  :arglists ([coll]),
  :doc "Returns a seq of the items in coll in reverse order. Not lazy."
}
</pre>
</div>
    <p>
      The <code>source</code> macro, in the clojure.repl library,
      uses this metadata to retrieve the source code
      for a given function or macro. For example:
    </p>
    <div class="code">
<pre xml:space="preserve">
(source reverse)
</pre>
</div>
    <p>
      The code above produces the following output:
    </p>
    <div class="code">
<pre xml:space="preserve">
(defn reverse
  "Returns a seq of the items in coll in reverse order. Not lazy."
  [coll]
    (reduce conj nil coll))
</pre>
</div>

    <h2><a name="Macros">Macros</a></h2>
    <p>
      Macros are used to add new constructs to the language.
      They are code that generates code at read-time.
    </p>
    <p>
      While functions always evaluate all their arguments,
      macros can decide which of their arguments will be evaluated.
      This is important for implementing forms like
      <code>(if <i>condition</i> <i>then-expr</i> <i>else-expr</i>)</code>.
      If the condition is <code>true</code>,
      only the "then" expression should be evaluated.
      If the condition is <code>false</code>,
      only the "else" expression should be evaluated.
      This means that <code>if</code> cannot be implemented as a function
      (it is in fact a special form, not a macro).
      Other forms that must be implemented as macros for this reason include
      <code>and</code> and <code>or</code>
      because they need to "short-circuit".
    </p>
    <p>
      To determine whether a given operation
      is implemented as a function or a macro,
      either enter <code>(doc <i>name</i>)</code> in a REPL
      or examine its metadata.
      If it is a macro then the metadata will contain
      a <code>:macro</code> key with a value of <code>true</code>.
      For example, to determine this for <code>and</code>,
      enter the following code in a REPL:
    </p>
    <div class="code">
<pre xml:space="preserve">
((meta (var and)) :macro) ; long way -&gt; true
(^#'and :macro) ; short way -&gt; true
</pre>
</div>
    <p>
      Let's walk through some examples of writing and using macros.
      Suppose there are many places in our code that need to
      take different actions based on whether a number is
      really close to zero, negative or positive.
      We want to avoid code duplication.
      This must be implemented as a macro instead of a function
      because only one of the three actions should be evaluated.
      The <code>defmacro</code> macro defines a macro.
    </p>
    <div class="code">
<pre xml:space="preserve">
(defmacro around-zero [number negative-expr zero-expr positive-expr]
  `(let [number# ~number] ; so number is only evaluated once
    (cond
      (&lt; (Math/abs number#) 1e-15) ~zero-expr
      (pos? number#) ~positive-expr
      true ~negative-expr)))
</pre>
</div>
    <p>
      The Reader expands calls to the <code>around-zero</code> macro
      into a call to the <code>let</code> special form.
      That contains a call to the <code>cond</code> function
      whose arguments are its conditions and return values.
      The <code>let</code> special form is used here for efficiency
      in the event that the first parameter, <code>number</code>,
      is passed as an expression instead of a simple value.
      It evaluates <code>number</code> once and then
      uses its value in two places within the <code>cond</code>.
      The auto-gensym <code>number#</code> is used to
      generate a unique symbol name so there is no chance
      the binding name can conflict with that of another symbol.
      This enables the creation of
      <a href="http://en.wikipedia.org/wiki/Hygienic_macros">hygienic macros</a>.
    </p>
    <p>
      The back-quote (a.k.a. syntax quote)
      at the beginning of the macro definition
      prevents everything inside from being evaluated unless it is unquoted.
      This means the contents will appear literally in the expansion,
      except items preceded by a tilde (in this case,
      <code>number</code>, <code>zero-expr</code>,
      <code>positive-expr</code> and <code>negative-expr</code>).
      When a symbol name is preceded by a tilde inside a syntax quoted list,
      its value is substituted.
      Bindings in syntax quoted lists whose values are sequences
      can be preceded by <code>~@</code> to substitute their individual items.
    </p>
    <p>
      Here are two example uses of this macro
      where the expected output is "<code>+</code>".
    </p>
    <div class="code">
<pre xml:space="preserve">
(around-zero 0.1 (println "-") (println "0") (println "+"))
(println (around-zero 0.1 "-" "0" "+")) ; same thing
</pre>
</div>
    <p>
      To execute more than one form for one of the cases,
      wrap them in a <code>do</code> form.
      For example, if the number represented a temperature
      and we had a <code>log</code> function to write to a log file,
      we might write this:
    </p>
    <div class="code">
<pre xml:space="preserve">
(around-zero 0.1
  (do (log "really cold!") (println "-"))
  (println "0")
  (println "+"))
</pre>
</div>
    <p>
      To verify that this macro is expanded properly,
      enter the following in a REPL:
    </p>
    <div class="code">
<pre xml:space="preserve">
(macroexpand-1
  '(around-zero 0.1 (println "-") (println "0") (println "+")))
</pre>
</div>
    <p>
      This will output the following on a single line
      without the indentation:
    </p>
    <div class="code">
<pre xml:space="preserve">
(clojure.core/let [number__3382__auto__ 0.1]
  (clojure.core/cond
    (clojure.core/&lt; (Math/abs number__3382__auto__) 1.0E-15) (println "0")
    (clojure.core/pos? number__3382__auto__) (println "+")
    true (println "-")))
</pre>
</div>
    <p>
      Here's a function that uses the macro
      to return a word describing a number.
    </p>
    <div class="code">
<pre xml:space="preserve">
(defn number-category [number]
  (around-zero number "negative" "zero" "positive"))
</pre>
</div>
    <p>
      Here are some example uses.
    </p>
    <div class="code">
<pre xml:space="preserve">
(println (number-category -0.1)) ; -&gt; negative
(println (number-category 0)) ; -&gt; zero
(println (number-category 0.1)) ; -&gt; positive
</pre>
</div>
    <p>
      Since macros don't evaluate their arguments,
      unquoted function names can be passed to them
      and calls to the functions with arguments can be constructed.
      Function definitions cannot do this and instead must be passed
      anonymous functions that wrap calls to functions.
    </p>
    <p>
      Here's a macro that takes two arguments.
      The first is a function that expects one argument
      that is a number of radians, such as a trigonometry function.
      The second is a number of degrees.
      If this were written as a function instead of a macro,
      we would have to pass <code>#(Math/sin %)</code>
      instead of simply <code>Math/sin</code> for the function.
      Note the use of the <code>#</code> suffix to
      generate unique, local binding names.
      This is sometimes necessary to avoid collisions with other bindings.
      Both <code>#</code> and <code>~</code> must be used
      inside a syntax quoted list.
    </p>
    <div class="code">
<pre xml:space="preserve">
(defmacro trig-y-category [fn degrees]
  `(let [radians# (Math/toRadians ~degrees)
         result# (~fn radians#)]
     (number-category result#)))
</pre>
</div>
    <p>
      Let's try it.
      The expected output from the code below is
      "zero", "positive", "zero" and "negative".
    </p>
    <div class="code">
<pre xml:space="preserve">
(doseq [angle (range 0 360 90)] ; 0, 90, 180 and 270
  (println (trig-y-category Math/sin angle)))
</pre>
</div>
    <p>
      Macro names cannot be passed as arguments to functions.
      For example, a macro name such as <code>and</code>
      cannot be passed to the <code>reduce</code> function.
      A workaround is to define an anonymous function that calls the macro.
      For example, <code>(fn [x y] (and x y))</code>
      or <code>#(and %1 %2)</code>.
      The macro is expanded inside the anonymous function body at read-time.
      When this function is passed to
      another function such as <code>reduce</code>,
      a function object rather than a macro name is passed.
    </p>
    <p>
      Macro calls are processed at read-time.
    </p>
    
    <h2><a name="Concurrency">Concurrency</a></h2>
    <p>
      Wikipedia has a great definition of concurrency:
      "Concurrency is a property of systems in which
      several computations are executing and overlapping in time,
      and potentially interacting with each other.
      The overlapping computations may be executing on
      multiple cores in the same chip,
      preemptively time-shared threads on the same processor,
      or executed on physically separated processors."
      The primary challenge of concurrency
      is managing access to shared, mutable state.
    </p>
    <p>
      Managing concurrency with locks is hard.
      It requires determining which objects need to be locked
      and when they need to be locked.
      These decisions need to be reevaluated when
      the code is modified or new code is added.
      If a developer forgets to lock objects that need to be locked
      or locks them at the wrong times, bad things can happen.
      These include
      <a href="http://en.wikipedia.org/wiki/Deadlock">deadlocks</a> and
      <a href="http://en.wikipedia.org/wiki/Race_condition">race conditions</a>.
      If objects are locked unnecessarily, there is a performance penalty.
    </p>
    <p>
      Support for concurrency is one of the main reasons why
      many developers choose to use Clojure.
      All data is immutable unless explicitly marked as mutable by using
      the reference types <a href="#Vars">Var</a>,
      <a href="#Refs">Ref</a>, <a href="#Atoms">Atom</a>
      and <a href="#Agents">Agent</a>.
      These provide safe ways to manage shared state
      and are described in the next section titled
      "<a href="#ReferenceTypes">Reference Types</a>".
    </p>
    <p>
      It is easy to run any Clojure function,
      including user-written functions that are either named or anonymous,
      in a new thread.
      See the earlier discussion on threads
      in the "<a href="#Threads">Java Interoperability</a>" section.
    </p>
    <p>
      Since Clojure can use all Java classes and interfaces,
      it can use all the Java concurrency capabilities.
      A great source of information on these is the book
      "<a href="http://jcip.net/">Java Concurrency In Practice</a>".
      This book contains excellent advice
      for managing concurrency using Java,
      but following the advice is not easy.
      In most cases, using Clojure reference types is easier
      than using Java-based concurrency.
    </p>
    <p>
      In addition to reference types, Clojure provides many functions
      that assist with running code in different threads.
    </p>
    <p>
      The <code>future</code> macro runs a body of expressions
      in a different thread using one of the thread pools
      (<code>CachedThreadPool</code>) that are also used by
      <a href="#Agents">Agents</a> (described later).
      This is useful for long running expressions
      whose results aren't needed immediately.
      The result is obtained by dereferencing the object
      returned by <code>future</code>.
      If the body hasn't yet completed when its result is requested,
      the current thread blocks until it does.
      Since a thread from an Agent thread pool is used,
      <code>shutdown-agents</code> should be called at some point
      so those threads are stopped and the application can exit.
    </p>
    <p>
      To demonstrate using <code>future</code>, a <code>println</code>
      was added to the <code>derivative</code> function
      described at the end of the
      "<a href="#polynomials">Defining Functions</a>" section.
      It helps identify when that function is executed.
      Note the order of the output from the code below:
    </p>
    <div class="code">
<pre xml:space="preserve">
(println "creating future")
(def my-future (future (f-prime 2))) ; f-prime is called in another thread
(println "created future")
(println "result is" @my-future)
(shutdown-agents)
</pre>
</div>
    <p>
      If the <code>f-prime</code> function doesn't complete quickly,
      the output from the code above will be:
    </p>
    <div class="code">
<pre xml:space="preserve">
creating future
created future
derivative entered
result is 9.0
</pre>
</div>
    <p>
      The <code>pmap</code> function applies a function
      to all the items in a collection in parallel.
      It provides better performance than the <code>map</code> function
      when the function being applied is time consuming
      compared to the overhead of managing the threads.
    </p>
    <p>
      The <code>clojure.parallel</code> namespace provides
      many more functions that help with parallelizing code.
      These include
      <code>par</code>,
      <code>pdistinct</code>,
      <code>pfilter-dupes</code>,
      <code>pfilter-nils</code>,
      <code>pmax</code>,
      <code>pmin</code>,
      <code>preduce</code>,
      <code>psort</code>,
      <code>psummary</code> and
      <code>pvec</code>.
    </p>

    <h2><a name="ReferenceTypes">Reference Types</a></h2>
    <p>
      Reference types are mutable references to immutable data.
      There are four references types in Clojure:
      <a href="#Vars">Vars</a>,
      <a href="#Refs">Refs</a>,
      <a href="#Atoms">Atoms</a> and
      <a href="#Agents">Agents</a>.
      They have many things in common:
    </p>
    <ul>
      <li>They can hold any kind of object.</li>
      <li>They can be dereferenced to retrieve the object they hold
        with the <code>deref</code> function
        or the <code>@</code> reader macro.
      </li>
      <li>
        They support validators which are
        functions that are invoked when the value changes.
        If the new value is valid, they return <code>true</code>.
        Otherwise they either return <code>false</code> or throw an exception.
        If they simply return <code>false</code>,
        an <code>IllegalStateException</code>
        with the message "Invalid reference state" will be thrown.
      </li>
      <li>
        They support watchers which are Agents.
        When the value of a watched reference changes,
        the Agent is notified.
        For more detail, see the "<a href="#Agents">Agents</a>" section.
      </li>
    </ul>
    <p>
      The table below summarizes some of the differences
      between the four reference types and
      the functions used to create and modify them.
      Each of the functions in the table below are described later.
    </p>
    <table border="1" style="font-size:8pt; width:100%">
      <tr>
        <th colspan="1" rowspan="1" style="width:8%"/>
        <th colspan="1" rowspan="1" style="width:23%">Var</th>
        <th colspan="1" rowspan="1" style="width:23%">Ref</th>
        <th colspan="1" rowspan="1" style="width:23%">Atom</th>
        <th colspan="1" rowspan="1" style="width:23%">Agent</th>
      </tr>
      <tr style="vertical-align:top">
        <th colspan="1" rowspan="1" style="text-align:left">Purpose</th>
        <td colspan="1" rowspan="1">synchronous changes<br />to a single, thread-local value</td>
        <td colspan="1" rowspan="1">synchronous, coordinated changes<br />to one or more values</td>
        <td colspan="1" rowspan="1">synchronous changes<br />to a single value</td>
        <td colspan="1" rowspan="1">asynchronous changes<br />to a single value</td>
      </tr>
      <tr style="vertical-align:top">
        <th colspan="1" rowspan="1" style="text-align:left">To create</th>
        <td colspan="1" rowspan="1">
          <code>(def <i>name</i> <i>initial-value</i>)</code>
        </td>
        <td colspan="1" rowspan="1">
          <code>(ref <i>initial-value</i>)</code>
        </td>
        <td colspan="1" rowspan="1">
          <code>(atom <i>initial-value</i>)</code>
        </td>
        <td colspan="1" rowspan="1">
          <code>(agent <i>initial-value</i>)</code>
        </td>
      </tr>
      <tr style="vertical-align:top">
        <th colspan="1" rowspan="1" style="text-align:left">To modify</th>
        <td colspan="1" rowspan="1">
          <code>(def <i>name</i> <i>new-value</i>)</code>
<br />
          sets new root value
          <hr />
          <code>(alter-var-root<br />
            (var <i>name</i>) <i>update-fn</i> <i>args</i>)</code>
<br />
          atomically sets new root value
          <hr />
          <code>(set! <i>name</i> <i>new-value</i>)</code>
<br />
          sets new, thread-local value
          inside a <code>binding</code> form
        </td>
        <td colspan="1" rowspan="1">
          <code>(ref-set <i>ref</i> <i>new-value</i>)</code>
<br />
          must be inside a <code>dosync</code>
<br />
          <hr />
          <code>(alter <i>ref</i>
<br />
            <i>update-fn</i> <i>arguments</i>)</code>
<br />
          must be inside a <code>dosync</code>
<br />
          <hr />
          <code>(commute <i>ref</i>
<br />
            <i>update-fn</i> <i>arguments</i>)</code>
<br />
          must be inside a <code>dosync</code>
        </td>
        <td colspan="1" rowspan="1">
          <code>(reset! <i>atom</i> <i>new-value</i>)</code>
<br />
          <hr />
          <code>(compare-and-set! <i>atom</i> <i>current-value</i> <i>new-value</i>)</code>
<br />
          <hr />
          <code>(swap! <i>atom</i>
<br />
            <i>update-fn</i> <i>arguments</i>)</code>
        </td>
        <td colspan="1" rowspan="1">
          <code>(send <i>agent</i>
<br />
            <i>update-fn</i> <i>arguments</i>)</code>
<br />
          <hr />
          <code>(send-off <i>agent</i>
<br />
            <i>update-fn</i> <i>arguments</i>)</code>
        </td>
      </tr>
    </table>

    <h3><a name="Vars">Vars</a></h3>
    <p>
      <a href="http://clojure.org/vars">Vars</a> are references that
      can have a root binding that is shared by all threads
      and can have a different value in each thread (thread-local).
    </p>
    <p>
      To create a Var and give it a root binding:
    </p>
    <div class="code">
<pre xml:space="preserve">
(def <i>name</i> <i>value</i>)
</pre>
</div>
    <p>
      Providing a value is optional.
      If none is given then the Var is said to be "unbound".
      The same form is used to change the root binding of an existing Var.
    </p>
    <p>
      There are two ways to create a thread-local binding
      for an existing Var:
    </p>
    <div class="code">
<pre xml:space="preserve">
(binding [<i>name</i> <i>expression</i>] <i>body</i>)
(set! <i>name</i> <i>expression</i>) ; inside a binding that bound the same name
</pre>
</div>
    <p>
      Use of the <a href="#binding">binding</a> macro was described earlier.
      The following example demonstrates using it in conjunction with
      the <code>set!</code> special form.
      That changes the thread-local value of a Var
      that was bound to a thread-local value
      by the <code>binding</code> macro.
    </p>
    <div class="code">
<pre xml:space="preserve">
(def v 1)

(defn change-it []
  (println "2) v =" v) ; -&gt; 1

  (def v 2) ; changes root value
  (println "3) v =" v) ; -&gt; 2

  (binding [v 3] ; binds a thread-local value
    (println "4) v =" v) ; -&gt; 3

    (set! v 4) ; changes thread-local value
    (println "5) v =" v)) ; -&gt; 4

  (println "6) v =" v)) ; thread-local value is gone now -&gt; 2

(println "1) v =" v) ; -&gt; 1

(let [thread (Thread. #(change-it))]
  (.start thread)
  (.join thread)) ; wait for thread to finish

(println "7) v =" v) ; -&gt; 2
</pre>
</div>
    <p>
      The use of Vars is often frowned upon because
      changes to their values are not coordinated across threads.
      For example, a thread A could use the root value of a Var
      and then later discover that another thread B changed that value
      before thread A finished executing.
    </p>

    <h3><a name="Refs">Refs</a></h3>
    <p>
      Refs are used to ensure that changes to
      one or more bindings are coordinated between multiple threads.
      This coordination is implemented using
      <a href="http://en.wikipedia.org/wiki/Software_transactional_memory">Software Transactional Memory</a> (STM).
      Refs can only be modified inside a transaction.
    </p>
    <p>
      STM has properties that are similar to database transactions.
      All changes made inside an STM transaction
      only become visible to other threads
      at a single point in time when the transaction commits.
      This makes them both atomic and isolated.
      Validation functions make it possible to insure that
      changes are consistent with the values of other data.
    </p>
    <p>
      Code to be executed inside a transaction appears
      inside the body of a call to the <code>dosync</code> macro
      which demarcates the transaction.
      While inside a transaction, Refs that are changed
      have a private, in-transaction value that is
      not seen by other threads until the transaction commits.
    </p>
    <p>
      If no exceptions are thrown before
      the end of the transaction is reached then
      changes to Refs made in the transaction are committed.
      This means the in-transaction changes
      become visible outside the transaction.
    </p>
    <p>
      If an exception is thrown from any code
      executed inside the transaction,
      including those thrown from validation functions,
      the transaction rolls back.
      This means the in-transaction changes are discarded.
    </p>
    <p>
      While in a transaction, if an attempt is made to
      read or modify a Ref that has been modified
      in another transaction that has committed
      since the current transaction started (a conflict),
      the current transaction will retry.
      This means it will discard all its in-transaction changes
      and return to the beginning of the <code>dosync</code> body.
      There are no guarantees about
      when a transaction will detect a conflict
      or when it will begin a retry,
      only that they will be detected and retries will be performed.
    </p>
    <p>
      It is important that the code executed inside transactions
      be free of side effects since
      it may be run multiple times due to these retries.
      One way to support calls to functions that have side effects
      is to make the calls in actions that are sent to agents
      from inside a transaction.
      Those are held until the transaction completes.
      If the transaction commits then the actions are sent once
      regardless of the number of retries that occur.
      If the transaction rolls back then the actions are not sent.
    </p>
    <p>
      The <code>ref </code>function creates a new Ref object.
      One way to create a Ref and retain access to it
      is to use the <code>def</code> special form.
    </p>
    <div class="code">
<pre xml:space="preserve">
(def <i>name</i> (ref <i>value</i>))
</pre>
</div>
    <p>
      The <code>dosync </code>macro starts a transaction that
      continues while the expressions in its body are evaluated.
      The <code>ref-set</code> function changes
      the in-transaction value of a Ref and returns it.
      It must be called inside a transaction, otherwise
      an <code>IllegalStateException</code> is thrown.
      The change will only be visible outside the transaction
      if and when the transaction commits.
      This happens when a <code>dosync</code> exits
      without an exception being thrown.
      For example:
    </p>
    <div class="code">
<pre xml:space="preserve">
(dosync
  ...
  (ref-set <i>name</i> <i>new-value</i>)
  ...)
</pre>
</div>
    <p>
      If the new value must be computed from the old value
      then three steps are required.
    </p>
    <ol>
      <li>deference the Ref to get the old value</li>
      <li>compute the new value</li>
      <li>set the new value</li>
    </ol>
    <p>
      The <code>alter</code> and <code>commute</code> functions
      perform these three steps as a single operation.
      The <code>alter</code> function is used for changes that
      must be made in a specific order.
      The <code>commute</code> function is used for changes
      whose order is not important (i.e., commutative)
      and can be performed in parallel.
      Like <code>ref-set</code>, both must be called inside a transaction.
      Both take an "update function" that will compute the new value
      and additional arguments to be passed to it.
      This function will be passed
      the current in-transaction value of the Ref
      followed by the additional arguments, if any.
      Whenever the new value is based on the old value
      (computed as a function of the old value),
      using <code>alter</code> or <code>commute</code>
      is preferred over <code>ref-set</code>.
    </p>
    <p>
      For example, suppose we want to add one
      to the value of a Ref named <code>counter</code>.
      This could be implemented as follows,
      using <code>inc</code> for the update function:
    </p>
    <div class="code">
<pre xml:space="preserve">
(dosync
  ...
  (alter counter inc)
  ; or as
  (commute counter inc)
  ...)
</pre>
</div>
    <p>
      If an <code>alter</code> attempts to modify a Ref
      that has been changed by another thread
      since the current transaction began,
      the current transaction will retry from the beginning.
      Calls to <code>commute</code> do not do this.
      They proceed through the current transaction
      using in-transaction values for the Refs.
      This results in better performance because retries aren't performed.
      Remember though that <code>commute</code> should only be used when
      the order of the updates they make across multiple transactions
      are not important.
    </p>
    <p>
      If the transaction commits, something extra happens for the
      <code>commute</code> calls that were made in the transaction.
      For each <code>commute</code> call,
      the Ref they set will be reset using the result of the following call:
    </p>
    <div class="code">
<pre xml:space="preserve">
(apply <i>update-function</i> <i>last-committed-value-of-ref</i> <i>args</i>)
</pre>
</div>
    <p>
      Note that the update function will be passed
      the last committed value of the Ref.
      This may be the result of a transaction that committed
      in another thread after the current transaction began.
      It is not passed the in-transaction value of the Ref
      from the current transaction.
    </p>
    <p>
      Using <code>commute</code> instead of <code>alter</code>
      is an optimization.
      It will not produce different end results
      unless the order of the updates really does matter.
    </p>
    <p>
      Let's walk through an example that uses both Refs and
      Atoms (which are explained in more detail later).
      This example involves bank accounts and their transactions.
      First we'll define the data model.
    </p>
    <div class="code">
<pre xml:space="preserve">
(ns com.ociweb.bank)

; Assume the only account data that can change is its balance.
(defstruct account-struct :id :owner :balance-ref)

; We need to be able to add and delete accounts to and from a map.
; We want it to be sorted so we can easily
; find the highest account number
; for the purpose of assigning the next one.
(def account-map-ref (ref (sorted-map)))
</pre>
</div>
    <p>
      The following function creates a new account
      saves it in the account map, and returns it.
    </p>
    <div class="code">
<pre xml:space="preserve">
(defn open-account
  "creates a new account, stores it in the account map and returns it"
  [owner]
  (dosync ; required because a Ref is being changed
    (let [account-map @account-map-ref
          last-entry (last account-map)
          ; The id for the new account is one higher than the last one.
          id (if last-entry (inc (key last-entry)) 1)
          ; Create the new account with a zero starting balance.
          account (struct account-struct id owner (ref 0))]
      ; Add the new account to the map of accounts.
      (alter account-map-ref assoc id account)
      ; Return the account that was just created.
      account)))
</pre>
</div>
    <p>
      The following functions support
      depositing and withdrawing money to and from an account.
    </p>
    <div class="code">
<pre xml:space="preserve">
(defn deposit [account amount]
  "adds money to an account; can be a negative amount"
  (dosync ; required because a Ref is being changed
    (Thread/sleep 50) ; simulate a long-running operation
    (let [owner (account :owner)
          balance-ref (account :balance-ref)
          type (if (pos? amount) "deposit" "withdraw")
          direction (if (pos? amount) "to" "from")
          abs-amount (Math/abs amount)]
      (if (&gt;= (+ @balance-ref amount) 0) ; sufficient balance?
        (do
          (alter balance-ref + amount)
          (println (str type "ing") abs-amount direction owner))
        (throw (IllegalArgumentException.
                 (str "insufficient balance for " owner
                      " to withdraw " abs-amount)))))))

(defn withdraw
  "removes money from an account"
  [account amount]
  ; A withdrawal is like a negative deposit.
  (deposit account (- amount)))
</pre>
</div>
    <p>
      The following function supports
      transferring money from one account to another.
      The transaction started by <code>dosync</code> ensures that
      either both the withdrawal and the deposit occur
      or neither occurs.
    </p>
    <div class="code">
<pre xml:space="preserve">
(defn transfer [from-account to-account amount]
  (dosync
    (println "transferring" amount
             "from" (from-account :owner)
             "to" (to-account :owner))
    (withdraw from-account amount)
    (deposit to-account amount)))
</pre>
</div>
    <p>
      The following functions support reporting on the state of accounts.
      The transaction started by <code>dosync</code> ensures that
      the report will be consistent across accounts.
      For example, it won't report balances that are
      the result of a half-completed transfer.
    </p>
    <div class="code">
<pre xml:space="preserve">
(defn- report-1 ; a private function
  "prints information about a single account"
  [account]
  ; This assumes it is being called from within
  ; the transaction started in report.
  (let [balance-ref (account :balance-ref)]
    (println "balance for" (account :owner) "is" @balance-ref)))

(defn report
  "prints information about any number of accounts"
  [&amp; accounts]
  (dosync (doseq [account accounts] (report-1 account))))
</pre>
</div>
    <p>
      This code doesn't handle exceptions that occur
      within the threads it starts.
      Instead we'll define an exception handler for them
      in the current thread.
    </p>
    <div class="code">
<pre xml:space="preserve">
; Set a default uncaught exception handler
; to handle exceptions not caught in other threads.
(Thread/setDefaultUncaughtExceptionHandler
  (proxy [Thread$UncaughtExceptionHandler] []
    (uncaughtException [thread throwable]
      ; Just print the message in the exception.
      (println (.. throwable .getCause .getMessage)))))
</pre>
</div>
    <p>
      Now we're ready to exercise the functions defined above.
    </p>
    <div class="code">
<pre xml:space="preserve">
(let [a1 (open-account "Mark")
      a2 (open-account "Tami")
      thread (Thread. #(transfer a1 a2 50))]
  (try
    (deposit a1 100)
    (deposit a2 200)

    ; There are sufficient funds in Mark's account at this point
    ; to transfer $50 to Tami's account.
    (.start thread) ; will sleep in deposit function twice!

    ; Unfortunately, due to the time it takes to complete the transfer
    ; (simulated with sleep calls), the next call will complete first.
    (withdraw a1 75)

    ; Now there are insufficient funds in Mark's account
    ; to complete the transfer.

    (.join thread) ; wait for thread to finish
    (report a1 a2)
    (catch IllegalArgumentException e
      (println (.getMessage e) "in main thread"))))
</pre>
</div>
    <p>
      The output from the code above is:
    </p>
    <div class="code">
<pre xml:space="preserve">
depositing 100 to Mark
depositing 200 to Tami
transferring 50 from Mark to Tami
withdrawing 75 from Mark
transferring 50 from Mark to Tami (a retry)
insufficient balance for Mark to withdraw 50
balance for Mark is 25
balance for Tami is 200
</pre>
</div>

    <h3>Validation Functions</h3>
    <p>
      Before moving on to discuss the next reference type,
      here's an example of using a validation function
      to verify that all values assigned to a Ref are integers.
    </p>
    <div class="code">
<pre xml:space="preserve">
; Note the use of the :validator directive when creating the Ref
; to assign a validation function which is integer? in this case.
(def my-ref (ref 0 :validator integer?))

(try
  (dosync
    (ref-set my-ref 1) ; works

    ; The next line doesn't work, so the transaction is rolled back
    ; and the previous change isn't committed.
    (ref-set my-ref "foo"))
  (catch IllegalStateException e
    ; do nothing
    ))

(println "my-ref =" @my-ref) ; due to validation failure -&gt; 0
</pre>
</div>

    <h3><a name="Atoms">Atoms</a></h3>
    <p>
      Atoms provide a mechanism for updating a single value
      that is far simpler than the combination of Refs and STM.
      They are not affected by transactions.
    </p>
    <p>
      There are three functions that change the value of an Atom,
      <code>reset!</code>, <code>compare-and-set!</code>
      and <code>swap!</code>.
    </p>
    <p>
      The <code>reset!</code> function takes
      the Atom to be set and the new value.
      It sets the new value without considering the current value.
      For example:
    </p>
    <div class="code">
<pre xml:space="preserve">
(def my-atom (atom 1))
(reset! my-atom 2)
(println @my-atom) ; -&gt; 2
</pre>
</div>
    <p>
      The <code>compare-and-set!</code> function takes the Atom to be set,
      what is believed to be the current value, and the desired new value.
      If the current value matches the second argument
      then it is changed to the new value and <code>true</code> is returned.
      Otherwise the value remains unchanged
      and <code>false</code> is returned.
      This is useful to avoid changing the value if some other code has
      changed it since it was dereferenced at a particular point.
    </p>
    <p>
      The <code>compare-and-set!</code> function is typically used
      at the end of a section of code where
      the beginning is a binding that captures
      the dereferenced value of the Atom.
      The code in between can assume one of two outcomes.
      One outcome is that the value of the Atom
      will remain unchanged while this code executes and
      <code>compare-and-set!</code> will change it at the end.
      The other outcome is that some other code
      will change the value of the Atom while this code executes and
      <code>compare-and-set!</code> will not change it at the end,
      returning <code>false</code> instead.
      For example:
    </p>
    <div class="code">
<pre xml:space="preserve">
(def my-atom (atom 1))

(defn update-atom []
  (let [curr-val @my-atom]
    (println "update-atom: curr-val =" curr-val) ; -&gt; 1
    (Thread/sleep 50) ; give reset! time to run
    (println
      (compare-and-set! my-atom curr-val (inc curr-val))))) ; -&gt; false

(let [thread (Thread. #(update-atom))]
  (.start thread)
  (Thread/sleep 25) ; give thread time to call update-atom
  (reset! my-atom 3) ; happens after update-atom binds curr-val
  (.join thread)) ; wait for thread to finish

(println @my-atom) ; -&gt; 3
</pre>
</div>
    <p>
      Why is the output from this code 3?
      The <code>update-atom</code> function is called in a separate thread
      before the <code>reset!</code> function.
      It captures the current value of the Atom which is 1.
      Then it sleeps to give the <code>reset!</code> function time to run.
      After that, the value of the Atom is 3.
      When the <code>update-atom</code> function
      calls <code>compare-and-set!</code> to increment the value,
      it fails because the current value is no longer 1.
      This means the value of the Atom remains set to 3.
    </p>
    <p>
      The <code>swap!</code> function takes an Atom to be set,
      a function to compute the new value and any number of
      additional arguments to be passed to the function.
      The function is called with the current value of the Atom
      and the additional arguments, if any.
      It is essentially a wrapper around the use of
      <code>compare-and-set!</code> with one important difference.
      It begins by dereferencing the Atom to save its current value.
      Next, it calls the function to compute the new value.
      Finally, it calls <code>compare-and-set!</code>
      using the current value obtained at the beginning.
      If <code>compare-and-set!</code> returns <code>false</code>,
      meaning the current value of the Atom didn't match
      its value before the call to the function,
      <b>the function is called repeatedly until this check succeeds</b>.
      This is the important difference.
      The previous code can be written using <code>swap!</code>
      instead of <code>compare-and-set!</code> as follows:
    </p>
    <div class="code">
<pre xml:space="preserve">
(def my-atom (atom 1))

(defn update-atom [curr-val]
  (println "update-atom: curr-val =" curr-val)
  (Thread/sleep 50) ; give reset! time to run
  (inc curr-val))

(let [thread (Thread. #(swap! my-atom update-atom))]
  (.start thread)
  (Thread/sleep 25) ; give swap! time to call update-atom
  (reset! my-atom 3)
  (.join thread)) ; wait for thread to finish

(println @my-atom) ; -&gt; 4
</pre>
</div>
    <p>
      Why is the output from this code 4?
      The <code>swap!</code> function is called in a separate thread
      before the <code>reset!</code> function.
      When the <code>update-atom</code> function
      is called from <code>swap!</code>,
      the current value of the Atom is 1.
      However, due to the <code>sleep</code> call,
      it doesn't complete before <code>reset!</code> is run,
      which sets the value to 3.
      The <code>update-atom</code> function returns 2.
      Before <code>swap!</code> can set the Atom to 2
      it needs to verify that its current value is still 1.
      It isn't, so <code>swap!</code> calls <code>update-atom</code> again.
      This time the current value is 3,
      so it increments that and returns 4.
      The <code>swap!</code> function now successfully
      verifies that it knew the current value before
      the last call to <code>update-atom</code> and it sets the Atom to 4.
    </p>
      
    <h3><a name="Agents">Agents</a></h3>
    <p>
      Agents are used to run tasks in separate threads
      that typically don't require coordination.
      They are useful for modifying the state of a single object
      which is the value of the agent.
      This value is changed by running an "action" in a separate thread.
      An action is a function that takes the current value of the Agent
      as its first argument and optionally takes additional arguments.
      <b>Only one action at a time will be run on a given Agent.</b>
    </p>
    <p>
      The <code>agent</code> function creates a new Agent.
      For example:
    </p>
    <div class="code">
<pre xml:space="preserve">
(def my-agent (agent <i>initial-value</i>))
</pre>
</div>
    <p>
      The <code>send</code> function dispatches an action to an Agent
      and returns immediately instead of waiting for the action to complete.
      The action is executed in a thread from a supplied thread pool.
      When the action completes, its return value will be assigned to the Agent.
      The <code>send-off</code> function is similar,
      but uses threads from a different pool.
    </p>
    <p>
      The <code>send</code> function uses a "fixed thread pool"
      (see the
      <a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/Executors.html#newFixedThreadPool(int)">newFixedThreadPool</a>
      method in java.util.concurrent.Executors)
      where the number of threads is the number of processors plus two.
      If all of those threads are busy,
      the action doesn't run until one becomes available.
      The <code>send-off</code> function uses a "cached thread pool"
      (see the
      <a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/Executors.html#newCachedThreadPool()">newCachedThreadPool</a>
      method in java.util.concurrent.Executors)
      where existing threads in the pool are used if available
      and new threads are added otherwise.
    </p>
    <p>
      If the <code>send</code> or <code>send-off</code> functions
      are invoked from inside a transaction,
      the action isn't actually sent until the transaction commits.
      This is somewhat similar to calling
      the <code>commute</code> function on a Ref in the sense that
      the calls that determine the value to retain
      occur at the end of the transaction.
    </p>
    <p>
      Inside actions, the Agent on which they are operating
      is bound to the symbol <code>*agent*</code>.
    </p>
    <p>
      The <code>await</code> function takes any number of Agents
      and blocks the current thread until all actions
      that thread has dispatched to those Agents have completed.
      The <code>await-for</code> function is similar,
      but takes a timeout in milliseconds as its first argument.
      If the actions complete before the timeout occurs,
      it returns a non-<code>nil</code> value.
      Otherwise it returns <code>nil</code>.
      The <code>await</code> and <code>await-for</code> functions
      cannot be called inside a transaction.
    </p>
    <p>
      If an action throws an exception then dereferencing
      the Agent to which it was sent will also throw an exception.
      The exceptions thrown in all actions that have been sent to a given Agent
      can be retrieved by calling the <code>agent-errors</code> function.
      The <code>clear-agent-errors</code> function
      clears the collection of exceptions for a given Agent.
    </p>
    <p>
      The <code>shutdown-agents</code> function waits for the
      execution of all actions already sent to all Agents to complete.
      It then stops all the threads in the thread pools
      that are used by Agents.
      After this has been called, no new actions can be sent.
      Calling <code>shutdown-agents</code> is necessary to allow
      the JVM to exit in an orderly manner because
      the threads in the Agent thread pools are not daemon threads.
    </p>

    <h3>Watchers</h3>
    <p>
      WARNING: This section needs to be updated for changes made in
      Clojure 1.1. The <code>add-watcher</code> and <code>remove-watcher</code>
      function have been removed. The <code>add-watch</code> and
      <code>remove-watch</code> functions, that works differently,
      have been added.
    </p>
    <p>
      Agents can act as watchers of other reference type objects.
      After the value of a watched reference has changed,
      the Agent is notified by sending it an action.
      The type of the send, <code>send</code> or <code>send-off</code>,
      is specified when the watcher is registered with a reference object.
      The action function is passed the current value of the Agent
      (not the value of the reference object that changed)
      and the reference object whose state changed.
      The return value of the action function
      becomes the new value of the Agent.
    </p>
    <p>
      As stated earlier, functional programming emphasizes
      the use of "pure functions" which have no side effects
      such as changing global state.
      Clojure doesn't prevent functions from doing this,
      but it does make it easy to find the functions that do.
      One way is to search the source code for functions and macros
      that call any of the small set of functions that change global state
      (for example, <code>alter</code>).
      Another way is to use watchers to detect changes.
      A watcher could print a stack trace
      to identify the function that made the change.
    </p>
    <p>
      The example below registers a watcher Agent
      with a Var, a Ref and an Atom.
      The state of the watcher Agent is a map
      that is used to count the number of times
      each reference it is watching changes.
      The keys in this map are the reference objects
      and the values are change counts.
    </p>
    <div class="code">
<pre xml:space="preserve">
(def my-watcher (agent {}))

(defn my-watcher-action [current-value reference]
  (let [change-count-map current-value
        old-count (change-count-map reference)
        new-count (if old-count (inc old-count) 1)]
  ; Return an updated map of change counts
  ; that will become the new value of the Agent.
  (assoc change-count-map reference new-count)))

(def my-var "v1")
(def my-ref (ref "r1"))
(def my-atom (atom "a1"))

(add-watcher (var my-var) :send-off my-watcher my-watcher-action)
(add-watcher my-ref :send-off my-watcher my-watcher-action)
(add-watcher my-atom :send-off my-watcher my-watcher-action)

; Change the root binding of the Var in two ways.
(def my-var "v2")
(alter-var-root (var my-var) (fn [curr-val] "v3"))

; Change the Ref in two ways.
(dosync
  ; The next line only changes the in-transaction value
  ; so the watcher isn't notified.
  (ref-set my-ref "r2")
  ; When the transaction commits, the watcher is
  ; notified of one change this Ref ... the last one.
  (ref-set my-ref "r3"))
(dosync
  (alter my-ref (fn [_] "r4"))) ; And now one more.

; Change the Atom in two ways.
(reset! my-atom "a2")
(compare-and-set! my-atom @my-atom "a3")

; Wait for all the actions sent to the watcher Agent to complete.
(await my-watcher)

; Output the number of changes to
; each reference object that was watched.
(let [change-count-map @my-watcher]
  (println "my-var changes =" (change-count-map (var my-var))) ; -&gt; 2
  (println "my-ref changes =" (change-count-map my-ref)) ; -&gt; 2
  (println "my-atom changes =" (change-count-map my-atom))) ; -&gt; 2

(shutdown-agents)
</pre>
</div>

    <h2><a name="Compiling">Compiling</a></h2>
    <p>
      When Clojure source files are executed as scripts,
      they are compiled to Java bytecode at runtime.
      They can also be compiled to Java bytecode ahead of time (AOT).
      This improves the startup time of Clojure applications
      and produces .class files that can be used in Java applications.
      Recommended steps to do this are:
    </p>
    <ol>
      <li>
        Select a namespace for the source files to be compiled,
        for example, <code>com.ociweb.talk</code>.
      </li>
      <li>
        Create directories named "<code>src</code>" and
        "<code>classes</code>" in the same parent directory.
      </li>
      <li>
        Make one of the source files have the same name as the
        last part of the namespace. We'll call this the main source file.
        For example, <code>talk.clj</code>.
      </li>
      <li>
        Place the source files under the "<code>src</code>" directory
        in a directory structure patterned after the namespace.
        For example, the main source would be
        <code>src/com/ociweb/talk.clj</code>.
      </li>
      <li>
        Specify the namespace at the top of the main source file
        and include the <code>:gen-class</code> namespace directive.
        For example: <code>(ns com.ociweb.talk (:gen-class))</code>
      </li>
      <li>
        In the main source file, use the <code>load</code> function to
        load all the other source files in the same namespace
        with relative paths.
        For example, if the file <code>more.clj</code>
        is in a subdirectory of <code>src/com/ociweb</code>
        named "<code>talk</code>",
        use <code>(load "talk/more")</code>.
      </li>
      <li>
        In each of the other source files,
        use the <code>in-ns</code> function
        to set their namespace.
        For example, add <code>(in-ns 'com.ociweb.talk)</code>
        to the top of <code>more.clj</code>.
      </li>
      <li>
        Add the "<code>src</code>" and "<code>classes</code>" directories
        to the classpath used by the REPL.
        If a script is used to run the REPL, modify that script.
      </li>
      <li>Start a REPL.</li>
      <li>
        Use the <code>compile </code>function to compile
        all the source files in a given namespace by entering
        <code>(compile '<i>namespace</i>)</code>. For example:
        <code>(compile 'com.ociweb.talk)</code>.
      </li>
    </ol>
    <p>
      A separate .class file is produced for each function.
      They are written under the "<code>classes</code>" directory
      in a directory structure that corresponds to their namespace.
    </p>
    <p>
      If the compiled namespace has a function named <code>-main</code>,
      it can be run as a Java application.
      Command-line arguments are passed as arguments to that function.
      For example, if <code>talk.clj</code> contained
      a <code>-main</code> function, it could be run as follows:
    </p>
    <div class="code">
<pre xml:space="preserve">
java -classpath <i>path</i>/classes:<i>path</i>/clojure.jar com.ociweb.talk <i>args</i>
</pre>
</div>
    <h3>Java Calling Clojure</h3>
    <p>
      AOT compiled Clojure functions can be called from a Java application
      if they are marked as static.
      To do this, set the metadata key
      <code>:static</code> to <code>true</code> in the
      <code>:gen-class</code> <code>:methods</code> directive.
      The <code>:methods</code> directive also specifies the Java types
      for the parameters and return value.
      The syntax for this is:
    </p>
    <div class="code">
<pre xml:space="preserve">
(ns <i>namespace</i>
  (:gen-class
   :methods [^{:static true} [<i>function-name</i> [<i>param-types</i>] <i>return-type</i>]]))
</pre>
</div>
    <p>
      Let's walk through an example.
      Here's a Clojure source file named <code>Demo.clj</code>
      in the directory <code>src/com/ociweb/clj</code>.
    </p>
    <div class="code">
<pre xml:space="preserve">
(ns com.ociweb.clj.Demo
  (:gen-class
   :methods [^{:static true} [getMessage [String] String]]))

# Note the hyphen at the beginning of the function name!
(defn -getMessage [name]
  (str "Hello, " name "!"))
</pre>
</div>
    <p>
      Here's a Java source file named <code>Main.java</code>
      that is in the same directory as the
      <code>src</code> and <code>classes</code> directories.
    </p>
    <div class="code">
<pre xml:space="preserve">
import com.ociweb.clj.Demo; // class created by compiling Clojure source file

public class Main {

    public static void main(String[] args) {
        String message = Demo.getMessage("Mark");
        System.out.println(message);
    }
}
</pre>
</div>
    <p>
      Here are the steps to build and run it.
    </p>
    <ol>
      <li>cd to the directory containing the
        <code>src</code> and <code>classes</code> directories.</li>
      <li>Start a REPL by entering "<code>clj</code>".</li>
      <li>Enter "<code>(compile 'com.ociweb.clj.Demo)</code>".</li>
      <li>Exit the REPL (ctrl-d or ctrl-c).</li>
      <li>Enter "<code>javap -classpath classes com.ociweb.clj.Demo</code>"
        to see the methods in the generated class.</li>
      <li>Enter "<code>javac -cp classes Main.java</code>".</li>
      <li>Enter "<code>java -cp .:classes:<i>path</i>/clojure.jar Main.java</code>". Use semicolons instead of colons under Windows.</li>
      <li>The output should be "<code>Hello, Mark!</code>".</li>
    </ol>
    <p>
      There are many more advanced compiling features.
      For more detail, see the API documentation
      for the <code><a href="http://clojure.github.com/clojure/clojure.core-api.html#clojure.core/gen-class">gen-class</a></code>
      macro.
      Also see
      <a href="http://clojure.org/compilation">http://clojure.org/compilation/</a>.
    </p>
    
    <h2><a name="Testing">Automated Testing</a></h2>
    <p>
      The primary automated testing framework for Clojure is
      the test library included in Clojure core.
      The following code demonstrates its main features:
    </p>
    <div class="code">
<pre xml:space="preserve">
(use 'clojure.test)

; Tests can be written in separate functions.
(deftest add-test
  ; The "is" macro takes a predicate, arguments to it,
  ; and an optional message.
  (is (= 4 (+ 2 2)))
  (is (= 2 (+ 2 0)) "adding zero doesn't change value"))

(deftest reverse-test
  (is (= [3 2 1] (reverse [1 2 3]))))

; Tests can verify that a specific exception is thrown.
(deftest division-test
  (is (thrown? ArithmeticException (/ 3.0 0))))

; The with-test macro can be used to add tests
; to the functions they test as metadata.
(with-test
  (defn my-add [n1 n2] (+ n1 n2))
  (is (= 4 (my-add 2 2)))
  (is (= 2 (my-add 2 0)) "adding zero doesn't change value"))

; The "are" macro takes a predicate template and
; multiple sets of arguments to it, but no message.
; Each set of arguments are substituted one at a time
; into the predicate template and evaluated.
(deftest multiplication
  (are [n1 n2 result]
    (= (* n1 n2) result) ; a template
    1 1 1,
    1 2 2,
    2 3 6))

; Run all the tests in the current namespace.
; This includes tests that were added as function metadata using with-test.
; Other namespaces can be specified as quoted arguments.
(run-tests)
</pre>
</div>
    <p>
      To limit the depth of stack traces that are output
      when an exception is thrown from a test,
      bind the special symbol <code>*stack-trace-depth*</code>
      to an integer depth.
    </p>
    <p>
      When AOT compiling Clojure code to bytecode for production use,
      bind the <code>*load-tests*</code> symbol to <code>false</code>
      to avoid compiling test code.
    </p>
    <p>
      While not on the same level as automated testing,
      Clojure provides an <code>assert</code> macro.
      It takes an expression, evaluates it and
      throws an exception if it evaluates to false.
      This is useful for catching conditions that should never occur.
      For example:
    </p>
    <div class="code">
<pre xml:space="preserve">
(assert (&gt;= dow 7000))
</pre>
</div>
    <p>
      Another important feature of the test library is fixtures.
      They are code that wraps the execution of test methods.
      Fixtures come in two varieties,
      those that wrap the execution of each test method and
      those that wrap the execution of the entire run of test methods.
    </p>
    <p>
      To create a fixture, write a function that follows this pattern:
    </p>
    <div class="code">
<pre xml:space="preserve">
(defn fixture-name [test-function]
  ; Perform setup here.
  (test-function)
  ; Perform teardown here.
)
</pre>
</div>
    <p>
      The fixture function will be called once for each test function.
      The value of the <code>test-function</code> parameter
      will be the current function to be executed.
    </p>
    <p>
      To register fixtures to wrap each test method:
    </p>
    <div class="code">
<pre xml:space="preserve">
(use-fixtures :each fixture-1 fixture-2 ...)
</pre>
</div>
    <p>
      The order of execution will be:
    </p>
    <ol>
      <li>fixture-1 setup</li>
      <li>fixture-2 setup</li>
      <li>ONE test function</li>
      <li>fixture-2 teardown</li>
      <li>fixture-1 teardown</li>
    </ol>
    <p>
      To register fixtures to wrap the entire run:
    </p>
    <div class="code">
<pre xml:space="preserve">
(use-fixtures :once fixture-1 fixture-2 ...)
</pre>
</div>
    <p>
      The order of execution will be:
    </p>
    <ol>
      <li>fixture-1 setup</li>
      <li>fixture-2 setup</li>
      <li>ALL test functions</li>
      <li>fixture-2 teardown</li>
      <li>fixture-1 teardown</li>
    </ol>
    <p>
      Clojure ships with its own suite of tests
      in its <code>test</code> subdirectory.
      To run them, cd to the directory containing
      the Clojure <code>src</code> and <code>test</code> directories
      and enter "<code>ant test</code>".
    </p>
    
    <h2><a name="EditorsIDEs">Editors and IDEs</a></h2>
    <p>
      Clojure plugins for many editors and IDEs are available.
      For emacs there is clojure-mode and swank-clojure, both at
      <a href="https://github.com/technomancy/swank-clojure">https://github.com/technomancy/swank-clojure</a>.
      swank-clojure uses the Superior Lisp Interaction Mode for Emacs (Slime)
      described at <a href="http://common-lisp.net/project/slime/">http://common-lisp.net/project/slime/</a>.
      For Vim there is VimClojure at
      <a href="http://www.vim.org/scripts/script.php?script_id=2501">http://www.vim.org/scripts/script.php?script_id=2501</a>.
      For NetBeans there is enclojure at
      <a href="http://enclojure.org/">http://enclojure.org/</a>.
      For IDEA there a "La Clojure" at
      <a href="http://plugins.intellij.net/plugin/?id=4050">http://plugins.intellij.net/plugin/?id=4050</a>.
      For Eclipse there is Counter Clockwise at
      <a href="http://dev.clojure.org/display/doc/Getting+Started+with+Eclipse+and+Counterclockwise">http://dev.clojure.org/display/doc/Getting+Started+with+Eclipse+and+Counterclockwise</a>.
    </p>
    
    <h2><a name="DesktopApps">Desktop Applications</a></h2>
    <p>
      Clojure can be used to create Swing-based GUI applications.
      Here's a simple example that allows the user to enter their name,
      press a "Greet" button, and receive a greeting in a dialog.
      Note the use of the <code>proxy</code> macro to
      create a Java object that extends a given Java class
      (<code>JFrame</code> in this case)
      and/or implements any number of Java interfaces
      (only <code>ActionListener</code> in this case).
    </p>
    <p>
      <img src="images/Swing1.png" alt="Swing input frame"/>
      <img src="images/Swing2.png" alt="Swing output dialog"/>
    </p>
    <div class="code">
<pre xml:space="preserve">
(ns com.ociweb.swing
  (:import
    (java.awt BorderLayout)
    (java.awt.event ActionListener)
    (javax.swing JButton JFrame JLabel JOptionPane JPanel JTextField)))

(defn message
  "gets the message to display based on the current text in text-field"
  [text-field]
  (str "Hello, " (.getText text-field) "!"))

; Set the initial text in name-field to "World"
; and its visible width to 10.
(let [name-field (JTextField. "World" 10)
      greet-button (JButton. "Greet")
      panel (JPanel.)
      frame (proxy [JFrame ActionListener]
        [] ; superclass constructor arguments
        (actionPerformed [e] ; nil below is the parent component
          (JOptionPane/showMessageDialog nil (message name-field))))]
  (doto panel
    (.add (JLabel. "Name:"))
    (.add name-field))
  (doto frame
    (.add panel BorderLayout/CENTER)
    (.add greet-button BorderLayout/SOUTH)
    (.pack)
    (.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE)
    (.setVisible true))
  ; Register frame to listen for greet-button presses.
  (.addActionListener greet-button frame))
</pre>
</div>

    <h2><a name="WebApps">Web Applications</a></h2>
    <p>
      There are several Clojure libraries for creating web
      applications.
      A popular choice these days
      is <a href="http://webnoir.org/">Noir</a> by Chris Granger.
      A simple, convention-based MVC framework, that uses Christophe
      Grand's <a href="https://github.com/cgrand/enlive">Enlive</a>
      for view templates,
      is <a href="https://github.com/seancorfield/fw1-clj">Framework
      One</a> by Sean Corfield.
      Another popular choice is Compojure by James Reeves which can be downloaded from
      <a href="http://github.com/weavejester/compojure/tree/master">http://github.com/weavejester/compojure/tree/master</a>.
      All of these web frameworks are based
      on <a href="https://github.com/mmcgrana/ring">Ring</a> by Mark
      McGranahan and maintained by James Reeves.
      We're going to look at Compojure as an example.
      The latest version can be retrieved from a
      <a href="http://git-scm.com/">Git</a> repository
      as follows (assuming Git is already installed):
    </p>
    <div class="code">
<pre xml:space="preserve">
git clone git://github.com/weavejester/compojure.git
</pre>
</div>
    <p>
      This creates a directory named <code>compojure</code>
      in the current directory.
      Additional JARs must be downloaded from
      <a href="http://cloud.github.com/downloads/weavejester/compojure/deps.zip">http://cloud.github.com/downloads/weavejester/compojure/deps.zip</a>.
      Place <code>deps.zip</code> in the <code>compojure</code> directory
      and unzip it to create a <code>deps</code> subdirectory.
    </p>
    <p>
      To build <code>compojure.jar</code>,
      run <code>ant</code> from the compojure directory.
    </p>
    <p>
      To get updates to Compojure,
      cd to the <code>compojure</code> directory
      and run the following commands:
    </p>
    <div class="code">
<pre xml:space="preserve">
git pull
ant clean deps jar
</pre>
</div>
    <p>
      All the JAR files in the <code>deps</code> subdirectory
      must be in the classpath.
      One way to achieve this is to modify the
      <code>clj</code> script and use it to run the web application.
      Add "<code>-cp $CP</code>" to the <code>java</code> command
      used to run <code>clojure.main</code>
      and add the following lines (which are UNIX-specific)
      before that to set <code>CP</code>.
    </p>
    <div class="code">
<pre xml:space="preserve">
# Set CP to a path list that contains clojure.jar
# and possibly some Clojure contrib JAR files.
COMPOJURE_DIR=<i>path-to-compojure-dir</i>
COMPOJURE_JAR=$COMPOJURE_DIR/compojure.jar
CP=$CP:$COMPOJURE_JAR
for file in $COMPOJURE_DIR/deps/*.jar
do
  CP=$CP:$file
done
</pre>
</div>
    <p>
      Here's an example of a simple Compojure web application.
    </p>
    <p>
      <img src="images/Compojure1.png" alt="Compojure input page"/>
      <img src="images/Compojure2.png" alt="Compojure output page"/>
    </p>
    <div class="code">
<pre xml:space="preserve">
(ns com.ociweb.hello
  (:use compojure))

(def host "localhost")
(def port 8080)
(def in-path "/hello")
(def out-path "/hello-out")

(defn html-doc
  "generates well-formed HTML for a given title and body content"
  [title &amp; body]
  (html
    (doctype :html4)
    [:html
      [:head [:title title]]
      [:body body]]))

; Creates HTML for input form.
(def hello-in
  (html-doc "Hello In"
    (form-to [:post out-path]
      "Name: "
      (text-field {:size 10} :name "World")
      [:br]
      (reset-button "Reset")
      (submit-button "Greet"))))

; Creates HTML for result message.
(defn hello-out [name]
  (html-doc "Hello Out"
    [:h1 "Hello, " name "!"]))

(defroutes hello-service
  ; The following three lines map HTTP methods
  ; and URL patterns to response HTML.
  (GET in-path hello-in)
  (POST out-path (hello-out (params :name)))
  (ANY "*" (page-not-found))) ; displays ./public/404.html by default

(println (str "browse http://" host ":" port in-path))
; -&gt; browse http://localhost:8080/hello
(run-server {:port port} "/*" (servlet hello-service))
</pre>
</div>

    <h2><a name="Databases">Databases</a></h2>
    <p>
      The jdbc library in <a href="#Libraries">Clojure Contrib</a>
      simplifies accessing relational databases.
      It supports transactions with commit and rollback,
      prepared statements, creating/dropping tables,
      inserting/updating/deleting rows, and running queries.
      The following example connects to a Postgres database
      and runs a query.
      Values to use for a MySQL database are provided
      in comments after the Postgres values.
    </p>
    <div class="code">
<pre xml:space="preserve">
(use 'clojure.java.jdbc)

(let [db-host "localhost"
      db-port 5432 ; 3306
      db-name "HR"]

  ; The classname below must be in the classpath.
  (def db {:classname "org.postgresql.Driver" ; com.mysql.jdbc.Driver
           :subprotocol "postgresql" ; "mysql"
           :subname (str "//" db-host ":" db-port "/" db-name)
           ; Any additional map entries are passed to the driver
           ; as driver-specific properties.
           :user "mvolkmann"
           :password "cljfan"})

  (with-connection db ; closes connection when finished
    (with-query-results rs ["select * from Employee"] ; closes result set when finished
      ; rs will be a non-lazy sequence of maps,
      ; one for each record in the result set.
      ; The keys in each map are the column names retrieved and
      ; their values are the column values for that result set row.
      (doseq [row rs] (println (row :lastname))))))
</pre>
</div>
    <p>
      The <code>clj-record</code> library provides a persistence API
      that is inspired by the Ruby on Rails ActiveRecord library.
      For more information, browse
      <a href="http://github.com/duelinmarkers/clj-record/tree/master">http://github.com/duelinmarkers/clj-record/tree/master</a>.
    </p>

    <h2><a name="Libraries">Libraries</a></h2>
    <p>
      Many libraries of Clojure functions and macros
      that support capabilities beyond what is in Clojure proper
      have been contributed and are part of
      <a href="http://dev.clojure.org/display/doc/Clojure+Contrib">Clojure Contrib</a>.
      Some of these that were not discussed earlier are summarized below.
      In addition, many of the known libraries are described at
      <a href="http://clojure.org/libraries">http://clojure.org/libraries</a>.
    </p>
    <ul>
      <li>clojure.tools.cli - processes command-line arguments and outputs help</li>
      <li>clojure.data.xml - performs lazy parsing of XML</li>
      <li>clojure.algo.monads - provides commonly used
        <a href="http://en.wikipedia.org/wiki/Monad_(functional_programming)">monads</a>,
        monad transformers, and macros for defining and using monads</li>
      <li>clojure.java.shell - provides functions and macros for launching subprocesses
        and controlling their stdin/stdout</li>
      <li>clojure.stacktrace - provides functions that simplify stack trace output
        by focusing on Clojure-specific content</li>
      <li>clojure.string - provides functions for working with
        strings and regular expressions</li>
      <li>clojure.tools.trace - provides tracing output for all
        calls to a given function and returns from it</li>
    </ul>
    <p>
      Here's a brief example of using clojure.java.shell
      to obtain the "print working directory".
    </p>
    <div class="code">
<pre xml:space="preserve">
(use 'clojure.java.shell)
(def directory (sh "pwd"))
</pre>
</div>
    
    <h2><a name="Conclusion">Conclusion</a></h2>
    <p>
      This article has covered a lot of ground.
      If you're hungry for more, a great source is the book
      "<a href="http://pragprog.com/book/shcloj2/programming-clojure">Programming Clojure</a>"
      written by
      <a href="http://www.nofluffjuststuff.com/speaker_view.jsp?speakerId=6">Stuart Halloway</a>.
    </p>
    <p>
      This article focuses on the features of Clojure 1.0 and will be
      updated by various community members over time.
      For a review of the changes in Clojure 1.1 and beyond, see
      <a href="http://www.fogus.me/static/preso/clj1.1+/">http://www.fogus.me/static/preso/clj1.1+/</a>.
    </p>
    <p>
      Here are some key questions to ask yourself
      that will help in deciding whether you should give Clojure a try.
    </p>
    <ul>
      <li>Are you looking for a way to make concurrent programming easier?</li>
      <li>Are you open to branching outside the world of
        object-oriented programming to try functional programming?</li>
      <li>Is it important for the applications you write to
        run on the JVM in order to take advantage of
        existing Java libraries, portability and other benefits?</li>
      <li>Do you prefer dynamically-typed languages
        over statically-typed ones?</li>
      <li>Do you find the minimal, consistent syntax
        of Lisp dialects appealing?</li>
     </ul>
    <p>
      If you answered "yes" to some of these questions then you should
      consider using Clojure as your next programming language.
    </p>
    
    <h2><a name="References">References</a></h2>
    <ul>
      <li>my Clojure site -
      <a href="http://www.ociweb.com/mark/clojure/">http://www.ociweb.com/mark/clojure/</a></li>
      <li>my STM site - <a href="http://www.ociweb.com/mark/stm/">http://www.ociweb.com/mark/stm/</a></li>
      <li>Clojure main site - <a href="http://clojure.org/">http://clojure.org/</a></li>
      <li>Clojure API -
      <a href="http://clojure.github.com/api-index.html">http://clojure.github.com/api-index.html</a></li>
      <li>ClojureDocs - <a href="http://clojuredocs.org/">http://clojuredocs.org/</a></li>
      <li>Clojure Atlas -
      <a href="http://www.clojureatlas.com/">http://www.clojureatlas.com/</a></li>
      <li>Clojure class diagram -
      <a href="http://github.com/Chouser/clojure-classes/tree/master/graph-w-legend.png">http://github.com/Chouser/clojure-classes/tree/master/graph-w-legend.png</a></li>
      <li>Wikibooks Clojure Programming - <a href="http://en.wikibooks.org/wiki/Clojure_Programming">http://en.wikibooks.org/wiki/Clojure_Programming</a></li>
      <li>Wikibooks Learning Clojure - <a href="http://en.wikibooks.org/wiki/Learning_Clojure">http://en.wikibooks.org/wiki/Learning_Clojure</a></li>
      <li>Wikibooks Clojure API Examples - <a href="http://en.wikibooks.org/wiki/Clojure_Programming/Examples/API_Examples">http://en.wikibooks.org/wiki/Clojure_Programming/Examples/API_Examples</a></li>
      <li>Project Euler Clojure code - <a href="http://clojure-euler.wikispaces.com/">http://clojure-euler.wikispaces.com/</a></li>
      <li>Modular contrib documentation - <a href="http://dev.clojure.org/display/design/Where+Did+Clojure.Contrib+Go">http://dev.clojure.org/display/design/Where+Did+Clojure.Contrib+Go</a></li>
      <li>Clojure Snake Game - <a href="http://www.ociweb.com/mark/programming/ClojureSnake.html">http://www.ociweb.com/mark/programming/ClojureSnake.html</a></li>
    </ul>
    <hr />
    <!--#include virtual="/jnb/services.html"-->
    <hr />
    <!--#include virtual="/jnb/footer.html"-->
  </body>
</html>
Something went wrong with that request. Please try again.