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
|
/*
FALCON - The Falcon Programming Language.
FILE: functional_ext.cpp
Functional programming support
-------------------------------------------------------------------
Author: Giancarlo Niccolai
Begin: Thu, 14 Aug 2008 02:10:57 +0200
-------------------------------------------------------------------
(C) Copyright 2008: the FALCON developers (see list in AUTHORS file)
See LICENSE file for licensing details.
*/
#include "core_module.h"
/*#
@beginmodule core
*/
namespace Falcon {
namespace core {
/*#
@funset functional_support Functional programming support
@brief ETA functions and functional constructs.
Falcon provides some special functional programming constructs that are known
to the VM to have special significance. The vast majority of them starts a
"functional evaluation" chain on their parameters before their value is evaluated.
A functional evaluation is a recursive evaluation (reduction) of list structures into
atoms. At the moment, the only list structure that can be evaluated this way is the array.
Evaluating a parameter in functional context means that the given parameter will be
recursively scanned for callable arrays or symbols that can be reduced to atoms. A callable
array is reduced by calling the function and substituting it with its return value.
When all the contents of the list are reduced, the higher level is evaluated.
Consider this example:
@code
function func0( p0, p1 ): ...
function func1( p0 ): ...
list = [func0, [func1, param1], param2]
@endcode
Calling @b list as a callable array, func0 will be called with the array [func1, param1] as
the first parameter, and param2 as the second parameter. On the other hand, evaluating
the above list in a functional context, first func1 will be called with param1, then
func0 will be called with the return value of the previous evaluation as the first parameter,
and with param2 as the second parameter.
The functions in this section are considered "special constructs" as the VM knows them and
treats them specially. Their definition overrides the definition of a functional evaluation,
so that when the VM finds a special construct in its evaluation process, it ceases using the
default evaluation algorithm and passes evaluation control to the construct.
For example, the iff construct selects one of its branches to be evaluated only if the first
parameter evaluates to true:
@code
list = [iff, someValueIsTrue, [func0, [func1, param1]], [func1, param2] ]
@endcode
If this list had to be evaluated in a functional context, then before iff had a chance to
decide what to do, the two arrays [func0, ...] and [func1,...] would have been evaluated.
As iff is a special construct, the VM doesn't evaluate its parameters and lets iff perform
its operations as it prefer. In the case of iff, it first evaluates the first parameter,
then evaluates in functional context the second on the third parameter,
leaving unevaluated the other one.
Not all constructs evaluates everything it is passed to them in a functional context. Some of
them are meant exactly to treat even a callable array (or anything else that should be reduced)
as-is, stopping the evaluation process as the VM meets them. The description of each construct
explains its working principles, and whether if its parameters are evaluated or not.
Please, notice that "callable" doesn't necessarily mean "evaluable". To evaluate in functional
context a callable symbol without parameter, it must be transformed into a single-element array.
For example:
@code
function func0(): ...
result = [iff, shouldEval, [func0], func0]
@endcode
This places in result the value returned by func0 if shouldEval is true, while it returns exactly
the function object func0 as-is if shouldEval is false.
A more formal definition of the functional programming support in Falcon is provided in the
Survival Guide.
*/
static bool core_any_next( ::Falcon::VMachine *vm )
{
// was the elaboration succesful?
if ( vm->regA().isTrue() )
{
vm->regA().setBoolean( true );
return false;
}
// repeat checks.
CoreArray *arr = vm->param(0)->asArray();
uint32 count = (uint32) vm->local(0)->asInteger();
while( count < arr->length() )
{
Item *itm = &arr->at(count);
*vm->local(0) = (int64) count+1;
if ( vm->functionalEval( *itm ) )
{
return true;
}
else if ( vm->regA().isTrue() ) {
vm->regA().setBoolean( true );
return false;
}
count++;
}
vm->regA().setBoolean( false );
return false;
}
/*#
@function any
@inset functional_support
@brief Returns true if any of the items in a given collection evaluate to true.
@param sequence A sequence of arbitrary items.
@return true at least one item in the collection is true, false otherwise.
Items in @b sequence are evaluated in functional context for truth value. This means that,
if they are sigmas, they get sigma-reduced and their return value is evaluated,
otherwise they are evaluated directly.
Truth value is determined using the standard Falcon truth
check (nil is false, numerics are true if not zero, strings and collections are true if not
empty, object and classes are always true).
The check is short circuited. This means that elements are evaluated until
an element considered to be true (or sigma-reduced to a true value) is found.
If the collection is empty, this function returns false.
*/
FALCON_FUNC core_any ( ::Falcon::VMachine *vm )
{
Item *i_param = vm->param(0);
if( i_param == 0 || !i_param->isArray() )
{
throw new ParamError( ErrorParam( e_inv_params )
.origin(e_orig_runtime)
.extra( "A" ) );
}
CoreArray *arr = i_param->asArray();
uint32 count = arr->length();
vm->returnHandler( &core_any_next );
vm->addLocals(1);
for( uint32 i = 0; i < count; i ++ )
{
Item *itm = &arr->at(i);
*vm->local(0) = (int64) i+1;
if ( vm->functionalEval( *itm ) )
{
return;
}
else if ( vm->regA().isTrue() ) {
vm->returnHandler( 0 );
vm->regA().setBoolean( true );
return;
}
}
vm->returnHandler( 0 );
vm->regA().setBoolean( false );
}
static bool core_all_next( ::Falcon::VMachine *vm )
{
// was the elaboration succesfull?
if ( ! vm->regA().isTrue() )
{
vm->regA().setBoolean( false );
return false;
}
// repeat checks.
CoreArray *arr = vm->param(0)->asArray();
uint32 count = (uint32) vm->local(0)->asInteger();
while( count < arr->length() )
{
Item *itm = &arr->at(count);
*vm->local(0) = (int64) count+1;
if ( vm->functionalEval( *itm ) )
{
return true;
}
else if ( ! vm->regA().isTrue() ) {
vm->regA().setBoolean( false );
return false;
}
count++;
}
vm->regA().setBoolean( true );
return false;
}
/*#
@function all
@inset functional_support
@brief Returns true if all the items in a given collection evaluate to true.
@param sequence A sequence of arbitrary items.
@return true if all the items are true, false otherwise
Items in @b sequence are evaluated in functional context for truth value. This means that,
if they are sigmas, they get sigma-reduced and their return value is evaluated,
otherwise they are evaluated directly.
Truth value is determined using the standard Falcon truth
check (nil is false, numerics are true if not zero, strings and collections are true if not
empty, object and classes are always true).
The check is short circuited. This means that the processing of parameters
is interrupted as an element is evaluated into false.
If the collection is empty, this function returns false.
*/
FALCON_FUNC core_all ( ::Falcon::VMachine *vm )
{
Item *i_param = vm->param(0);
if( i_param == 0 || !i_param->isArray() )
{
throw new ParamError( ErrorParam( e_inv_params )
.origin(e_orig_runtime)
.extra( "A" ) );
}
CoreArray *arr = i_param->asArray();
uint32 count = arr->length();
if ( count == 0 )
{
vm->regA().setBoolean( false );
return;
}
vm->returnHandler( &core_all_next );
vm->addLocals(1);
for( uint32 i = 0; i < count; i ++ )
{
Item *itm = &arr->at(i);
*vm->local(0) = (int64) i+1;
if ( vm->functionalEval( *itm ) )
{
return;
}
else if ( ! vm->regA().isTrue() ) {
vm->returnHandler( 0 );
vm->regA().setBoolean( false );
return;
}
}
vm->returnHandler( 0 );
vm->regA().setBoolean( true );
}
static bool core_anyp_next( ::Falcon::VMachine *vm )
{
// was the elaboration succesfull?
if ( vm->regA().isTrue() )
{
vm->regA().setBoolean( true );
return false;
}
// repeat checks.
int32 count = (uint32) vm->local(0)->asInteger();
while( count < vm->paramCount() )
{
Item *itm = vm->param( count );
*vm->local(0) = (int64) count+1;
if ( vm->functionalEval( *itm ) )
{
return true;
}
else if ( vm->regA().isTrue() ) {
vm->regA().setBoolean( true );
return false;
}
count++;
}
vm->regA().setBoolean( false );
return false;
}
/*#
@function anyp
@inset functional_support
@brief Returns true if any one of the parameters evaluate to true.
@param ... A list of arbitrary items.
@return true at least one parameter is true, false otherwise.
This function works like @a any, but the sequence may be specified directly
in the parameters rather being given in a separate array. This make easier to write
anyp in callable arrays. For example, one may write
@code
[anyp, 1, k, n ...]
@endcode
while using any one should write
@code
[any, [1, k, n ...]]
@endcode
Parameters are evaluated in functional context. This means that,
if they are sigmas, they get sigma-reduced and their return value is evaluated,
otherwise they are evaluated directly.
Truth value is determined using the standard Falcon truth
check (nil is false, numerics are true if not zero, strings and collections are true if not
empty, object and classes are always true).
If called without parameters, this function returns false.
*/
FALCON_FUNC core_anyp ( ::Falcon::VMachine *vm )
{
uint32 count = vm->paramCount();
vm->returnHandler( &core_anyp_next );
vm->addLocals(1);
for( uint32 i = 0; i < count; i ++ )
{
Item *itm = vm->param(i);
*vm->local(0) = (int64) i+1;
if ( vm->functionalEval( *itm ) )
{
return;
}
else if ( vm->regA().isTrue() ) {
vm->returnHandler( 0 );
vm->regA().setBoolean( true );
return;
}
}
vm->returnHandler( 0 );
vm->regA().setBoolean( false );
}
static bool core_allp_next( ::Falcon::VMachine *vm )
{
// was the elaboration succesfull?
if ( ! vm->regA().isTrue() )
{
vm->regA().setBoolean( false );
return false;
}
// repeat checks.
int32 count = (uint32) vm->local(0)->asInteger();
while( count < vm->paramCount() )
{
Item *itm = vm->param(count);
*vm->local(0) = (int64) count+1;
if ( vm->functionalEval( *itm ) )
{
return true;
}
else if ( ! vm->regA().isTrue() ) {
vm->regA().setBoolean( false );
return false;
}
count++;
}
vm->regA().setBoolean( true );
return false;
}
/*#
@function allp
@inset functional_support
@brief Returns true if all the parameters evaluate to true.
@param ... An arbitrary list of items.
@return true if all the items are true, false otherwise
This function works like @a all, but the collection may be specified directly
in the parameters rather being given in a separate array. This make easier to
write allp in callable arrays. For example, one may write
@code
[allp, 1, k, n ...]
@endcode
while using all one should write
@code
[all, [1, k, n ...]]
@endcode
Parameters are evaluated in functional context. This means that,
if they are sigmas, they get sigma-reduced and their return value is evaluated,
otherwise they are evaluated directly.
Truth value is determined using the standard Falcon truth
check (nil is false, numerics are true if not zero, strings and collections are true if not
empty, object and classes are always true).
If called without parameters, this function returns false.
*/
FALCON_FUNC core_allp ( ::Falcon::VMachine *vm )
{
uint32 count = vm->paramCount();
vm->returnHandler( &core_allp_next );
vm->addLocals(1);
if ( count == 0 )
{
vm->retval(0);
return;
}
for( uint32 i = 0; i < count; i ++ )
{
Item *itm = vm->param(i);
*vm->local(0) = (int64) i+1;
if ( vm->functionalEval( *itm ) )
{
return;
}
else if ( ! vm->regA().isTrue() ) {
vm->returnHandler( 0 );
vm->regA().setBoolean( false );
return;
}
}
vm->returnHandler( 0 );
vm->retval( 1 );
}
/*#
@function eval
@inset functional_support
@brief Evaluates a sequence in functional context.
@param sequence A sequence to be evaluated.
@return The sigma-reduction (evaluation) result.
The parameter is evaluated in functional context; this means that if the parameter
is a sequence starting with a callable item, that item gets called with the rest of the
sequence passed as parameters, and the result it returns is considered the
"evaluation result". This is performed recursively, inner-to-outer, on every element
of the sequence before the call to the first element is actually performed.
The description of the functional evaluation algorithm is included in the heading
of this section.
*/
FALCON_FUNC core_eval ( ::Falcon::VMachine *vm )
{
Item *i_param = vm->param(0);
if( i_param == 0 )
{
throw new ParamError( ErrorParam( e_inv_params )
.origin(e_orig_runtime)
.extra( "X" ) );
}
uint32 pcount = vm->paramCount() - 1;
for ( uint32 i = pcount; i > 0; i-- )
{
vm->pushParameter( *vm->param(i) );
}
vm->functionalEval( *i_param, pcount );
}
/*#
@function valof
@inset functional_support
@brief Calls callable items or returns non callable ones.
@param item The item to be checked.
@return The item if it is not callable, or the call return value.
The name function is a short for @i extended @i value. It is meant
to determine if the passed item is a non-callable value or if it
should be called to determine a value. Performing this check at
script level time consuming and often clumsy, and this function
is easily used in functional sequences.
*/
FALCON_FUNC core_valof ( ::Falcon::VMachine *vm )
{
if ( vm->paramCount() == 0 )
{
vm->retnil();
return;
}
Item *elem = vm->param( 0 );
if( elem->isCallable() )
vm->callFrame( *elem, 0 );
else
vm->retval( *elem );
}
/*#
@function min
@inset functional_support
@brief Picks the minimal value among its parameters.
@param ... The items to be checked.
@return The smallest item in the sequence.
This function performs a lexicographic minority check
on each element passed as a parameter, returning the
smallest of them.
A standard VM comparison is performed, so the standard
ordering rules apply. This also means that objects overloading
the @a BOM.compare method may provide specialized ordering
rules.
If more than one item is found equal and lesser than
all the others, the first one is returned.
If the function is called without parameters, it returns @b nil.
*/
FALCON_FUNC core_min ( ::Falcon::VMachine *vm )
{
if ( vm->paramCount() == 0 )
{
vm->retnil();
return;
}
Item *elem = vm->param( 0 );
for ( int32 i = 1; i < vm->paramCount(); i++)
{
if ( *vm->param(i) < *elem )
{
elem = vm->param(i);
}
}
vm->retval( *elem );
}
/*#
@function max
@inset functional_support
@brief Picks the maximum value among its parameters.
@param ... The items to be checked.
@return The greatest item in the sequence.
This function performs a lexicographic majority check
on each element passed as a parameter, returning the
greater of them.
A standard VM comparison is performed, so the standard
ordering rules apply. This also means that objects overloading
the @a BOM.compare method may provide specialized ordering
rules.
If more than one item is found equal and greater than
all the others, the first one is returned.
If the function is called without parameters, it returns @b nil.
*/
FALCON_FUNC core_max ( ::Falcon::VMachine *vm )
{
if ( vm->paramCount() == 0 )
{
vm->retnil();
return;
}
Item *elem = vm->param( 0 );
int32 count = vm->paramCount();
for ( int32 i = 1; i < count; i++)
{
if ( *vm->param(i) > *elem )
{
elem = vm->param(i);
}
}
vm->retval( *elem );
}
/*#
@function map
@inset functional_support
@brief Creates a new vector of items transforming each item in the original array through the mapping function.
@param mfunc A function or sigma used to map the array.
@param sequence A sequence of arbitrary items.
@return The parameter unevaluated.
mfunc is called iteratively for every item in the collection; its return value is added to the
mapped array. In this way it is possible to apply an uniform transformation to all the item
in a collection.
If mfunc returns an out of band nil item, map skips the given position in the target array,
actually acting also as a filter function.
For example:
@code
function mapper( item )
if item < 0: return oob(nil) // discard negative items
return item ** 0.5 // perform square root
end
inspect( map( mapper, [ 100, 4, -12, 9 ]) ) // returns [10, 2, 3]
@endcode
@see oob
*/
static bool core_map_next( ::Falcon::VMachine *vm )
{
// callable in first item
CoreArray *origin = vm->param(1)->asArray();
uint32 count = (uint32) vm->local(0)->asInteger();
CoreArray *mapped = vm->local(1)->asArray();
if ( ! vm->regA().isOob() )
mapped->append( vm->regA() );
if ( count < origin->length() )
{
*vm->local(0) = (int64) count + 1;
vm->pushParameter( origin->at(count) );
vm->callFrame( *vm->param(0), 1 );
return true;
}
vm->retval( mapped );
return false;
}
FALCON_FUNC core_map ( ::Falcon::VMachine *vm )
{
Item *callable = vm->param(0);
Item *i_origin = vm->param(1);
if( callable == 0 || !callable->isCallable() ||
i_origin == 0 || !i_origin->isArray()
)
{
throw new ParamError( ErrorParam( e_inv_params )
.origin(e_orig_runtime)
.extra( "C,A" ) );
}
CoreArray *origin = i_origin->asArray();
CoreArray *mapped = new CoreArray( origin->length() );
if ( origin->length() > 0 )
{
vm->returnHandler( &core_map_next );
vm->addLocals( 2 );
*vm->local(0) = (int64)1;
*vm->local(1) = mapped;
vm->pushParameter( origin->at(0) );
// do not use pre-fetched pointer
vm->callFrame( *vm->param(0), 1 );
return;
}
vm->retval( mapped );
}
static bool core_dolist_next ( ::Falcon::VMachine *vm )
{
CoreArray *origin = vm->param(1)->asArray();
uint32 count = (uint32) vm->local(0)->asInteger();
// done -- let A stay as is.
if ( count >= origin->length() )
return false;
//if we called
if ( vm->local(1)->asInteger() == 1 )
{
// not true? -- exit
if ( vm->regA().isOob() && vm->regA().isNil() )
{
return false;
}
// prepare for next loop
*vm->local(1) = (int64)0;
if ( vm->functionalEval( origin->at(count) ) )
{
return true;
}
}
*vm->local(0) = (int64) count + 1;
*vm->local(1) = (int64) 1;
vm->pushParameter( vm->regA() );
vm->callFrame( *vm->param(0), 1 );
return true;
}
/*#
@function dolist
@inset functional_support
@brief Repeats an operation on a list of parameters.
@param processor A callable item that will receive data coming from the sequence.
@param sequence A list of items that will be fed in the processor one at a time.
@optparam ... Optional parameters to be passed to the first callable item.
@return The return value of the last callable item.
Every item in @b sequence is passed as parameter to the processor, which must be a callable
item. Items are also functionally evaluated, one by one, but the parameter @b sequence is not
functionally evaluated as a whole; to do that, use the explicit evaluation:
@code
dolist( processor, eval(array) )
@endcode
This method is equivalent to @a xmap, but it has the advantage that it doesn't create an array
of evaluated results. So, when it is not necessary to transform a sequence in another through a
mapping function, but just to run repeatedly over a collection, this function is to be preferred.
*/
FALCON_FUNC core_dolist ( ::Falcon::VMachine *vm )
{
Item *callable = vm->param(0);
Item *i_origin = vm->param(1);
if( callable == 0 || !callable->isCallable() ||
i_origin == 0 || !i_origin->isArray()
)
{
throw new ParamError( ErrorParam( e_inv_params )
.origin(e_orig_runtime)
.extra( "C,A" ) );
}
CoreArray *origin = i_origin->asArray();
if ( origin->length() != 0 )
{
vm->returnHandler( &core_dolist_next );
vm->addLocals( 2 );
// count
*vm->local(0) = (int64) 0;
//exiting from an eval or from a call frame? -- 0 eval
*vm->local(1) = (int64) 0;
if ( vm->functionalEval( origin->at(0) ) )
{
return;
}
// count
*vm->local(0) = (int64) 1;
//exiting from an eval or from a call frame? -- 1 callframe
*vm->local(1) = (int64) 1;
vm->pushParameter( vm->regA() );
vm->callFrame( *vm->param(0), 1 );
}
}
static bool core_times_next_( ::Falcon::VMachine *vm )
{
int64 end = vm->local(0)->asInteger();
int64 step = vm->local(1)->asInteger();
int64 start = vm->local(2)->asInteger();
while ( (step > 0 && start >= end)
|| (step < 0 && start < end )
|| ( vm->regA().isOob() && vm->regA().isInteger() && vm->regA().asInteger() == 0 )
)
{
vm->retval( start );
return false;
}
vm->pushParameter( start );
*vm->local(2) = start + step;
Item *i_sequence = vm->local(3);
if( i_sequence->isArray() )
{
vm->functionalEval( *i_sequence, 1, false );
}
else
{
vm->callFrame( *i_sequence, 1 );
}
return true;
}
/*#
@function times
@inset functional_support
@brief Repeats a sequence a determined number of times.
@param count Count of times to be repeated or non-open range.
@param sequence A function or a Sigma sequence.
@return Last index processed.
This function is very similar to a functional for/in loop. It repeats a sequence
of callable items in the @b sequence parameter a determined number of
times. If the @b sequence parameter is a sequence, parametric evaluation is
performed and the **&1** late binding is filled with the value of the index; if
it's a function, then it is called with the counter value added as the last parameter.
If the evaluated parameter is a sequence, full deep sigma evaluation is performed
at each loop.
The loop index count will be given values from 0 to the required index-1 if @b count is numeric,
or it will act as the for/in loop if @b count is a range.
For example:
@code
function printParam( var )
> "Parameter is... ", var
end
// the followings are equivalent
times( 10, [printParam, &1] )
times( 10, printParam )
@endcode
The following example prints a list of pair numbers between 2 and 10:
@code
times( [2:11:2], // range 2 to 10+1, with step 2
.[ printl "Index is now..." &1 ]
)
@endcode
Exactly like @a floop, the flow of calls in @b times can be altered by the functions in sequence returning
an out-of-band 0 or 1. If any function in the sequence returns an out-of-band 0, @b times terminates and
return immediately (performing an operation similar to "break"). If a function returns an out-of-band 1,
the rest of the items in @b sequence are ignored, and the loop is restarted with the index updated; this
is equivalent to a functional "continue". For example:
@code
times( 10,
// skip numbers less than 5
.[ .[(function(x); if x < 5: return oob(1); end) &1]
.[printl &1] // print the others
]
)
@endcode
The @b times function return the last generated value for the index. A natural termination of @b times
can be detected thanks to the fact that the index is equal to the upper bound of the range, while
an anticipated termination causes @b times to return a different index. For example, if @b count is
10, the generated index (possibly received by the items in @b sequence) will range from 0 to 9 included,
and if the function terminates correctly, it will return 10. If a function in @b sequence returns an
out-of-band 0, causing a premature termination of the loop, the value returned by times will be the loop
index at which the out-of-band 0 was returned.
@note Ranges [m:n] where m > n (down-ranges) terminate at n included; in that case, a succesful
completion of @b times return one-past n.
*/
/*#
@method times Integer
@brief repeats a sequence a given number of times.
@param sequence Function or sequence to be repeated.
@return Last index processed.
This method works exactly as the @b times function when
the first parameter is a number.
@see times
*/
/*#
@method times Range
@brief repeats a sequence a given number of times.
@param sequence Function or sequence to be repeated.
@return Last index processed.
This method works exactly as the @b times function when
the first parameter is a range.
@see times
*/
FALCON_FUNC core_times ( ::Falcon::VMachine *vm )
{
Item *i_count;
Item *i_sequence;
if ( vm->self().isMethodic() )
{
i_count = &vm->self();
i_sequence = vm->param(0);
}
else
{
i_count = vm->param(0);
i_sequence = vm->param(1);
}
if( i_count == 0 || ! ( i_count->isRange() || i_count->isOrdinal() ) ||
i_sequence == 0 || ! ( i_sequence->isArray() || i_sequence->isCallable() )
)
{
throw new ParamError( ErrorParam( e_inv_params )
.origin(e_orig_runtime)
.extra( "N|R, A|C" ) );
}
int64 start, end, step;
if( i_count->isRange() )
{
if ( i_count->asRangeIsOpen() )
{
throw new ParamError( ErrorParam( e_inv_params )
.origin(e_orig_runtime)
.extra( "open range" ) );
}
start = i_count->asRangeStart();
end = i_count->asRangeEnd();
step = i_count->asRangeStep();
if ( step == 0 ) step = start > end ? -1 : 1;
}
else {
start = 0;
end = i_count->forceInteger();
step = end < 0 ? -1 : 1;
}
// check ranges and steps.
if ( start == end ||
( start < end && ( step < 0 || start + step > end ) ) ||
( start > end && ( step > 0 || start + step < end ) )
)
{
// no loop to be done.
vm->retval( start );
return;
}
// ok, we must do at least a loop
vm->returnHandler( &core_times_next_ );
// 0: shifting range
// 1: position in the sequence calls.
// 2: should evaluate ? 0 = no 1 = yes, 2 = already evaluating.
vm->addLocals( 4 );
// count
*vm->local(0) = end;
*vm->local(1) = step;
*vm->local(2) = start;
*vm->local(3) = *vm->param( vm->self().isMethodic()? 0 : 1 );
// prevent dirty A to mess our break/continue system.
vm->regA().setNil();
// start the loop
core_times_next_(vm);
}
/*#
@method upto Integer
@brief Repeats a function or a sequence until the upper limit is reached.
@param llimit The upper limit of the loop.
@param sequence The sequence or function to be repeated.
@return The last index processed.
This method repeats a loop from this integer down to the limit value included.
If the limit is less than this integer, the function returns immediately.
If the sequence is a function, then it is called iteratively with the current
index value as last parameter. If it is a sequence, it is functionally evaluated
and the &1 parametric binding is set to the index.
@code
2.upto( 5, printl )
2.downto(5, .[printl "Value number " &1])
@endcode
In both cases, returning an oob(0) will cause the loop to terminate, while
returning an oob(1) from any evaluation in the sequence makes the rest of
the evaluation to be skipped and the loop to be restarted.
*/
FALCON_FUNC core_upto ( ::Falcon::VMachine *vm )
{
Item* i_count = vm->param(0);
Item* i_sequence = vm->param(1);
if( i_count == 0 || ! i_count->isOrdinal() ||
i_sequence == 0 || ! ( i_sequence->isArray() || i_sequence->isCallable() )
)
{
throw new ParamError( ErrorParam( e_inv_params )
.origin(e_orig_runtime)
.extra( "N|R, A|C" ) );
}
int64 start = vm->self().asInteger();
int64 end = i_count->forceInteger();
// check ranges and steps.
if ( start > end )
{
// no loop to be done.
vm->retval( start );
return;
}
// ok, we must do at least a loop
vm->returnHandler( &core_times_next_ );
// 0: shifting range
// 1: position in the sequence calls.
// 2: should evaluate ? 0 = no 1 = yes, 2 = already evaluating.
vm->addLocals( 4 );
// count
*vm->local(0) = end+1;
*vm->local(1) = (int64) 1;
*vm->local(2) = start;
*vm->local(3) = *vm->param( 1 );
// prevent dirty A to mess our break/continue system.
vm->regA().setNil();
// start the loop
core_times_next_(vm);
}
/*#
@method downto Integer
@brief Repeats a function or a sequence until the lower limit is reached.
@param llimit The lower limit of the loop.
@param sequence The sequence or function to be repeated.
@return The last index processed.
This method repeats a loop from this integer down to the limit value included.
If the limit is greater than this integer, the function returns immediately.
If the sequence is a function, then it is called iteratively with the current
index value as last parameter. If it is a sequence, it is functionally evaluated
and the &1 parametric binding is set to the index.
@code
5.downto( 2, printl )
3.downto(0, .[printl "Value number " &1])
@endcode
In both cases, returning an oob(0) will cause the loop to terminate, while
returning an oob(1) from any evaluation in the sequence makes the rest of
the evaluation to be skipped and the loop to be restarted.
*/
FALCON_FUNC core_downto ( ::Falcon::VMachine *vm )
{
Item* i_count = vm->param(0);
Item* i_sequence = vm->param(1);
if( i_count == 0 || ! i_count->isOrdinal() ||
i_sequence == 0 || ! ( i_sequence->isArray() || i_sequence->isCallable() )
)
{
throw new ParamError( ErrorParam( e_inv_params )
.origin(e_orig_runtime)
.extra( "N|R, A|C" ) );
}
int64 start = vm->self().asInteger();
int64 end = i_count->forceInteger();
// check ranges and steps.
if ( start <= end )
{
// no loop to be done.
vm->retval( start );
return;
}
// ok, we must do at least a loop
vm->returnHandler( &core_times_next_ );
// 0: shifting range
// 1: position in the sequence calls.
// 2: should evaluate ? 0 = no 1 = yes, 2 = already evaluating.
vm->addLocals( 4 );
// count
*vm->local(0) = end;
*vm->local(1) = (int64) -1;
*vm->local(2) = start;
*vm->local(3) = *vm->param( 1 );
// prevent dirty A to mess our break/continue system.
vm->regA().setNil();
// start the loop
core_times_next_(vm);
}
static bool core_xmap_next( ::Falcon::VMachine *vm )
{
// in vm->param(0) there is "callable".
CoreArray *origin = vm->param(1)->asArray();
uint32 count = (uint32) vm->local(0)->asInteger();
CoreArray *mapped = vm->local(1)->asArray();
if ( count < origin->length() )
{
if ( vm->local(2)->asInteger() == 1 )
{
if ( ! vm->regA().isOob() )
mapped->append( vm->regA() );
// prepare for next loop
*vm->local(0) = (int64) count + 1;
*vm->local(2) = (int64) 0;
if ( vm->functionalEval( origin->at(count) ) )
{
return true;
}
}
*vm->local(2) = (int64) 1;
vm->pushParameter( vm->regA() );
vm->callFrame( *vm->param(0), 1 );
return true;
}
else {
if ( ! vm->regA().isOob() )
mapped->append( vm->regA() );
}
vm->retval( mapped );
return false;
}
/*#
@function xmap
@inset functional_support
@brief Creates a new vector of items transforming each item in the original array through the mapping function, applying also filtering on undesired items.
@param mfunc A function or sigma used to map the array.
@param sequence A sequence to be mapped.
@return The mapped sequence.
@b mfunc is called iteratively for every item in the collection; its return value is added to
the mapped array. Moreover, each item in the collection is functionally evaluated before
being passed to mfunc.
The filter function may return an out of band nil item to signal that the current item should
not be added to the final collection.
For example:
@code
mapper = { item => item < 0 ? oob(nil) : item ** 0.5 }
add = { a, b => a+b } // a block that will be evaluated
inspect( xmap( mapper, [ [add, 99, 1], 4, -12, 9 ]) ) // returns [10, 2, 3]
@endcode
@see oob
@see dolist
*/
FALCON_FUNC core_xmap ( ::Falcon::VMachine *vm )
{
Item *callable = vm->param(0);
Item *i_origin = vm->param(1);
if( callable == 0 || !callable->isCallable() ||
i_origin == 0 || !i_origin->isArray()
)
{
throw new ParamError( ErrorParam( e_inv_params )
.origin(e_orig_runtime)
.extra( "C,A" ) );
}
CoreArray *origin = i_origin->asArray();
CoreArray *mapped = new CoreArray( origin->length() );
if ( origin->length() > 0 )
{
vm->returnHandler( &core_xmap_next );
vm->addLocals( 3 );
*vm->local(0) = (int64)1;
*vm->local(1) = mapped;
*vm->local(2) = (int64) 0;
if ( vm->functionalEval( origin->at(0) ) )
{
return;
}
*vm->local(2) = (int64) 1;
vm->pushParameter( vm->regA() );
vm->callFrame( *vm->param(0), 1 );
return;
}
vm->retval( mapped );
}
static bool core_filter_next ( ::Falcon::VMachine *vm )
{
CoreArray *origin = vm->param(1)->asArray();
CoreArray *mapped = vm->local(0)->asArray();
uint32 count = (uint32) vm->local(1)->asInteger();
if ( vm->regA().isTrue() )
mapped->append( origin->at(count -1) );
if( count == origin->length() )
{
vm->retval( mapped );
return false;
}
*vm->local(1) = (int64) count+1;
vm->pushParameter( origin->at(count) );
vm->callFrame( *vm->param(0), 1 );
return true;
}
/*#
@function filter
@inset functional_support
@brief Filters sequence using a filter function.
@param ffunc A callable item used to filter the array.
@param sequence A sequence of arbitrary items.
@return The filtered sequence.
ffunc is called iteratively for every item in the collection, which is passed as a parameter to it.
If the call returns true, the item is added to the returned array; if it returns false,
the item is not added.
Items in the collection are treated literally (not evaluated).
*/
FALCON_FUNC core_filter ( ::Falcon::VMachine *vm )
{
Item *callable = vm->param(0);
Item *i_origin = vm->param(1);
if( callable == 0 || !callable->isCallable() ||
i_origin == 0 || !i_origin->isArray()
)
{
throw new ParamError( ErrorParam( e_inv_params )
.origin(e_orig_runtime)
.extra( "C,A" ) );
}
CoreArray *origin = i_origin->asArray();
CoreArray *mapped = new CoreArray( origin->length() / 2 );
if( origin->length() > 0 )
{
vm->returnHandler( &core_filter_next );
vm->addLocals(2);
*vm->local(0) = mapped;
*vm->local(1) = (int64) 1;
vm->pushParameter( origin->at(0) );
vm->callFrame( *vm->param(0), 1 );
return;
}
vm->retval( mapped );
}
static bool core_reduce_next ( ::Falcon::VMachine *vm )
{
// Callable in param 0
CoreArray *origin = vm->param(1)->asArray();
// if we had enough calls, return (the return value of the last call frame is
// already what we want to return).
uint32 count = (uint32) vm->local(0)->asInteger();
if( count >= origin->length() )
return false;
// increment count for next call
vm->local(0)->setInteger( count + 1 );
// call next item
vm->pushParameter( vm->regA() ); // last returned value
vm->pushParameter( origin->at(count) ); // next element
vm->callFrame( *vm->param(0), 2 );
return true;
}
/*#
@function reduce
@inset functional_support
@brief Uses the values in a given sequence and iteratively calls a reductor function to extract a single result.
@param reductor A function or Sigma to reduce the array.
@param sequence A sequence of arbitrary items.
@optparam initial_value Optional startup value for the reduction.
@return The reduced result.
The reductor is a function receiving two values as parameters. The first value is the
previous value returned by the reductor, while the second one is an item iteratively
taken from the origin array. If a startup value is given, the first time the reductor
is called that value is provided as its first parameter, otherwise the first two items
from the array are used in the first call. If the collection is empty, the initial_value
is returned instead, and if is not given, nil is returned. If a startup value is not given
and the collection contains only one element, that element is returned.
Some examples:
@code
> reduce( {a,b=> a+b}, [1,2,3,4]) // sums 1 + 2 + 3 + 4 = 10
> reduce( {a,b=> a+b}, [1,2,3,4], -1 ) // sums -1 + 1 + 2 + 3 + 4 = 9
> reduce( {a,b=> a+b}, [1] ) // never calls lambda, returns 1
> reduce( {a,b=> a+b}, [], 0 ) // never calls lambda, returns 0
> reduce( {a,b=> a+b}, [] ) // never calls lambda, returns Nil
@endcode
Items in the collection are treated literally (not evaluated).
*/
FALCON_FUNC core_reduce ( ::Falcon::VMachine *vm )
{
Item *callable = vm->param(0);
Item *i_origin = vm->param(1);
Item *init = vm->param(2);
if( callable == 0 || !callable->isCallable()||
i_origin == 0 || !i_origin->isArray()
)
{
throw new ParamError( ErrorParam( e_inv_params )
.origin(e_orig_runtime)
.extra( "C,A,[X]" ) );
}
CoreArray *origin = i_origin->asArray();
vm->addLocals(1);
// local 0: array position
if ( init != 0 )
{
if( origin->length() == 0 )
{
vm->retval( *init );
return;
}
vm->returnHandler( &core_reduce_next );
vm->pushParameter( *init );
vm->pushParameter( origin->at(0) );
*vm->local(0) = (int64) 1;
//WARNING: never use pre-cached item pointers after stack changes.
vm->callFrame( *vm->param(0), 2 );
return;
}
// if init == 0; if there is only one element in the array, return it.
if ( origin->length() == 0 )
vm->retnil();
else if ( origin->length() == 1 )
vm->retval( origin->at(0) );
else
{
vm->returnHandler( core_reduce_next );
*vm->local(0) = (int64) 2; // we'll start from 2
// the first call is between the first and the second elements in the array.
vm->pushParameter( origin->at(0) );
vm->pushParameter( origin->at(1) );
//WARNING: never use pre-cached item pointers after stack changes.
vm->callFrame( *vm->param(0), 2 );
}
}
static bool core_iff_next( ::Falcon::VMachine *vm )
{
// anyhow, we don't want to be called anymore
vm->returnHandler( 0 );
if ( vm->regA().isTrue() )
{
if ( vm->functionalEval( *vm->param(1) ) )
return true;
}
else
{
Item *i_ifFalse = vm->param(2);
if ( i_ifFalse != 0 )
{
if ( vm->functionalEval( *i_ifFalse ) )
return true;
}
else
vm->retnil();
}
return false;
}
/*#
@function iff
@inset functional_support
@brief Performs a functional if; if the first parameter evaluates to true, the second parameter is evaluated and then returned, else the third one is evaluated and returned.
@param cfr A condition or a callable item.
@param whenTrue Value to be called and/or returned in case cfr evaluates to true.
@optparam whenFalse Value to be called and/or returned in case cfr evaluates to false.
@return The evaluation result of one of the two branches (or nil).
Basically, this function is meant to return the second parameter or the third (or nil if not given),
depending on the value of the first parameter; however, every item is evaluated in a functional
context. This means that cfr may be a callable item, in which case its return value will be evaluated
for truthfulness, and also the other parameters may. For example:
@code
> iff( 0, "was true", "was false" ) // will print "was false"
iff( [{a=>a*2}, 1] , [printl, "ok!"] ) // will print "ok!" and return nil
@endcode
In the last example, we are not interested in the return value (printl returns nil), but in executing
that item only in case the first item is true. The first item is a callable item too, so iff will first
execute the given block, finding a result of 2 (true), and then will decide which element to pick, and
eventually execute. Notice that:
@code
iff( 1 , printl( "ok!" ), printl( "no" ) )
@endcode
This would have forced Falcon to execute the two printl calls before entering the iff function;
still, iff would have returned printl return values (which is nil in both cases).
*/
FALCON_FUNC core_iff ( ::Falcon::VMachine *vm )
{
Item *i_cond = vm->param(0);
Item *i_ifTrue = vm->param(1);
Item *i_ifFalse = vm->param(2);
if( i_cond == 0 || i_ifTrue == 0 )
{
throw new ParamError( ErrorParam( e_inv_params )
.origin(e_orig_runtime)
.extra( "X,X,[X]" ) );
}
// we can use pre-fetched values as we have stack unchanged on
// paths where we use item pointers.
vm->returnHandler( &core_iff_next );
if ( vm->functionalEval( *i_cond ) )
{
return;
}
vm->returnHandler( 0 );
if ( vm->regA().isTrue() )
{
vm->functionalEval( *i_ifTrue );
}
else {
if ( i_ifFalse != 0 )
vm->functionalEval( *i_ifFalse );
else
vm->retnil();
}
}
static bool core_choice_next( ::Falcon::VMachine *vm )
{
if ( vm->regA().isTrue() )
{
vm->retval( *vm->param(1) );
}
else {
Item *i_ifFalse = vm->param(2);
if ( i_ifFalse != 0 )
vm->retval( *i_ifFalse );
else
vm->retnil();
}
return false;
}
/*#
@function choice
@inset functional_support
@brief Selects one of two alternatives depending on the evaluation of the first parameter.
@param selector The item to be evaluated.
@param whenTrue The item to return if selector evaluates to true.
@optparam whenFalse The item to be returned if selector evaluates to false
@optparam ... Optional parameters to be passed to the first callable item.
@return The return value of the last callable item.
The selector parameter is evaluated in functional context. If it's a true atom or if it's a
callable array which returns a true value, the ifTrue parameter is returned as-is, else the
ifFalse parameter is returned. If the ifFalse parameter is not given and the selector evaluates
to false, nil is returned.
The choice function is equivalent to iff where each branch is passed through the @a lit function:
@code
choice( selector, a, b ) == iff( selector, [lit, a], [lit, b] )
@endcode
In case a literal value is needed, choice is more efficient than using iff and applying lit on
the parameters.
*/
FALCON_FUNC core_choice ( ::Falcon::VMachine *vm )
{
Item *i_cond = vm->param(0);
Item *i_ifTrue = vm->param(1);
Item *i_ifFalse = vm->param(2);
if( i_cond == 0 || i_ifTrue == 0 )
{
throw new ParamError( ErrorParam( e_inv_params ).
extra( "X,X,[X]" ) );
}
vm->returnHandler( &core_choice_next );
if ( vm->functionalEval( *i_cond ) )
{
return;
}
vm->returnHandler( 0 );
if ( vm->regA().isTrue() )
{
vm->retval( *i_ifTrue );
}
else {
if ( i_ifFalse != 0 )
vm->retval( *i_ifFalse );
else
vm->retnil();
}
}
/*#
@function lit
@inset functional_support
@brief Return its parameter as-is
@param item A condition or a callable item.
@return The parameter unevaluated.
This function is meant to interrupt functional evaluation of lists. It has
the same meaning of the single quote literal ' operator of the LISP language.
For example, the following code will return either a callable instance of printl,
which prints a "prompt" before the parameter, or a callable instance of inspect:
@code
iff( a > 0, [lit, [printl, "val: "] ], inspect)( param )
@endcode
as inspect is a callable token, but not an evaluable one, it is already returned literally;
however, [printl, "val:"] would be considered an evaluable item. To take its literal
value and prevent evaluation in functional context, the lit construct must be used.
*/
FALCON_FUNC core_lit ( ::Falcon::VMachine *vm )
{
Item *i_cond = vm->param(0);
if( i_cond == 0 )
{
throw new ParamError( ErrorParam( e_inv_params )
.origin(e_orig_runtime)
.extra( "X" ) );
}
vm->regA() = *i_cond;
// result already in A.
}
static bool core_cascade_next ( ::Falcon::VMachine *vm )
{
// Param 0: callables array
// local 0: counter (position)
// local 1: last accepted result
CoreArray *callables = vm->param(0)->asArray();
uint32 count = (uint32) vm->local(0)->asInteger();
// Done?
if ( count >= callables->length() )
{
// if the last result is not accepted, return last accepted
if ( vm->regA().isOob() )
{
// reset OOB, that may be set on first unaccepted parameter.
vm->local(1)->resetOob();
vm->retval( *vm->local(1) );
}
// else, just keep
return false;
}
uint32 pc;
// still some loop to do
// accept result?
if ( vm->regA().isOob() )
{
// not accepted.
// has at least one parameter been accepted?
if ( vm->local(1)->isOob() )
{
// no? -- replay initial params
pc = vm->paramCount();
for ( uint32 pi = 1; pi < pc; pi++ )
{
vm->pushParameter( *vm->param(pi) );
}
pc--; //first param is our callable
}
else {
// yes? -- reuse last accepted parameter
pc = 1;
vm->pushParameter( *vm->local(1) );
}
}
else {
*vm->local(1) = vm->regA();
pc = 1;
vm->pushParameter( vm->regA() );
}
// prepare next call
vm->local(0)->setInteger( count + 1 );
// perform call
vm->callFrame( callables->at(count), pc ); // will throw noncallable in case of noncallable item.
//throw new ParamError( ErrorParam( e_non_callable ).origin(e_orig_runtime) );
return true;
}
/*#
@function cascade
@inset functional_support
@brief Concatenate a set of callable items so to form a single execution unit.
@param callList Sequence of callable items.
@optparam ... Optional parameters to be passed to the first callable item.
@return The return value of the last callable item.
This function executes a set of callable items passing the parameters it receives
beyond the first one to the first item in the list; from there on, the return value
of the previous call is fed as the sole parameter of the next call. In other words,
@code
cascade( [F1, F2, ..., FN], p1, p2, ..., pn )
@endcode
is equivalent to
@code
FN( ... F2( F1( p1, p2, ..., pn ) ) ... )
@endcode
A function may declare itself "uninterested" to insert its value in the cascade
by returning an out-of-band item. In that case, the return value is ignored and the same parameter
it received is passed on to the next calls and eventually returned.
Notice that the call list is not evaluated in functional context; it is just a list
of callable items. To evaluate the list, or part of it, in functional context, use
the eval() function.
A simple example usage is the following:
@code
function square( a )
return a * a
end
function sqrt( a )
return a ** 0.5
end
cascade_abs = [cascade, [square, sqrt] ]
> cascade_abs( 2 ) // 2
> cascade_abs( -4 ) // 4
@endcode
Thanks to the possibility to prevent insertion of the return value in the function call sequence,
it is possible to program "interceptors" that will catch the progress of the sequence without
interfering:
@code
function showprog( v )
> "Result currently ", v
return oob(nil)
end
// define sqrt and square as before...
cascade_abs = [cascade, [square, showprog, sqrt, showprog] ]
> "First process: ", cascade_abs( 2 )
> "Second process: ", cascade_abs( -4 )
@endcode
If the first function of the list declines processing by returning an oob item, the initial parameters
are all passed to the second function, and so on till the last call.
For example:
@code
function whichparams( a, b )
> "Called with ", a, " and ", b
return oob(nil)
end
csq = [cascade, [ whichparams, {a,b=> a*b} ]
> csq( 3, 4 )
@endcode
Here, the first function in the list intercepts the parameters but, as it doesn't
accepts them, they are both passed to the second in the list.
@see oob
*/
FALCON_FUNC core_cascade ( ::Falcon::VMachine *vm )
{
Item *i_callables = vm->param(0);
if( i_callables == 0 || !i_callables->isArray() )
{
throw new ParamError( ErrorParam( e_inv_params )
.origin(e_orig_runtime)
.extra( "A,..." ) );
}
// for the first callable...
CoreArray *callables = i_callables->asArray();
if( callables->length() == 0 )
{
vm->retnil();
return;
}
// we have at least one callable.
// Prepare the local space
// 0: array counter
// 1: saved previous value
// saved previous value is initialized to oob until
// someone accepts the first parameters.
vm->addLocals(2);
vm->local(0)->setInteger( 1 ); // we'll start from 1
vm->local(1)->setOob();
// echo the parameters to the first call
uint32 pcount = vm->paramCount();
for ( uint32 pi = 1; pi < pcount; pi++ )
{
vm->pushParameter( *vm->param(pi) );
}
pcount--;
// install the handler
vm->returnHandler( &core_cascade_next );
// perform the real call
vm->callFrame( callables->at(0), pcount );
//throw new ParamError( ErrorParam( e_non_callable ).origin(e_orig_runtime) );
}
static bool core_floop_next ( ::Falcon::VMachine *vm )
{
// Param 0: callables array
CoreArray *callables = vm->param(0)->asArray();
// local 0: counter (position)
uint32 count = (uint32) vm->local(0)->asInteger();
// next item.
++count;
// still some loop to do
if ( vm->regA().isInteger() && vm->regA().isOob() )
{
if ( vm->regA().asInteger() == 0 )
{
// we're done.
vm->returnHandler( 0 ); // ensure we're not called after first loop
vm->retnil();
return false;
}
else if ( vm->regA().asInteger() == 1 )
{
// continue
count = 0;
}
}
if ( count >= callables->length() )
{
count = 0;
}
// save the count
*vm->local(0) = (int64) count;
// find a callable in the array
if ( (*callables)[count].isCallable() )
{
vm->callFrame( (*callables)[count], 0 );
}
else
{
// set the item as A and recall ourself for evaluation
vm->regA() = (*callables)[count];
vm->recallFrame();
return true;
}
// else, just return true
return true;
}
/*#
@function floop
@inset functional_support
@brief Repeats indefinitely a list of operations.
@param sequence A sequence of callable items that gets called one after another.
Every item in @b sequence gets executed, one after another. When the last element is executed,
the first one is called again, looping indefinitely.
Any function in the sequence may interrupt the loop by returning an out-of-band 0;
if a function returns an out of band 1, all the remaining items in the list are ignored
and the loop starts again from the first item.
Items in the array are not functionally evaluated.
*/
FALCON_FUNC core_floop ( ::Falcon::VMachine *vm )
{
Item *i_callables = vm->param(0);
if( i_callables == 0 || !i_callables->isArray() )
{
throw new ParamError( ErrorParam( e_inv_params )
.origin(e_orig_runtime)
.extra( "A" ) );
return;
}
// for the first callable...
CoreArray *callables = i_callables->asArray();
if( callables->length() == 0 )
{
return;
}
// we have at least one callable.
// Prepare the local space
// 0: array counter
vm->addLocals(1);
vm->local(0)->setInteger( callables->length() ); // we'll start from 0 from the first loop
// install the handler
vm->returnHandler( &core_floop_next );
// call it directly
vm->regA().setNil(); // zero to avoid false signals to next handler
vm->callFrameNow( &core_floop_next );
}
/*#
@function firstOf
@inset functional_support
@brief Returns the first non-false of its parameters.
@param ... Any number of arbitrary parameters.
@return The first non-false item.
This function scans the paraters one at a time. Sigma evaluation is stopped,
or in other words, every parameters is considered as-is, as if @a lit was used on each of them.
The function returns the first parameter being non-false in a standard Falcon truth check.
Nonzero numeric values, non empty strings, arrays and dictionaries and any object is considered true.
If none of the parameters is true, of is none of the parameter is given, the function returns nil
(which is considered false).
*/
FALCON_FUNC core_firstof ( ::Falcon::VMachine *vm )
{
int count = 0;
Item *i_elem = vm->param(0);
while( i_elem != 0 )
{
if ( i_elem->isTrue() )
{
vm->retval( *i_elem );
return;
}
i_elem = vm->param( ++count );
}
vm->retnil();
}
/*#
@function lbind
@inset functional_support
@brief Creates a dynamic late binding symbol.
@param name A string representing a late binding name.
@optparam value A future binding value.
@return A newly created late binding name.
This function create a late binding item which can be used
in functional sequences as if the parameter was written in
the source code prefixed with the amper '&' operator.
The following lines are equivalent:
@code
bound = lbind( "count" )
ctx = &count
@endcode
The return value of this function, both used directly or pre-cached,
can be seamlessly merged with the & operator in functional sequences.
For example, it is possible to write the following loop:
@code
eval( .[
.[ times 10 &count .[
.[eval .[ printl 'Counting...' .[lbind 'count'] ] ]
]
]] )
@endcode
It is also possible cache the value and use it afterwards:
@code
x = lbind( 'count' )
eval( .[
.[ times 10 &count .[
.[ printl 'Counting...' x]
]
]] )
@endcode
The @b value parameter initializes a future (forward) binding.
Future bindings are bindings with a potential value, which is applied
during function calls and symbol resolution to pre-existing symbolic
entities. In practice, they allow calling fucntions with named parameters.
When mixing forward bindings and normal parameters, forward bindings are as
placed directly at the position of the parameter they refer to, and they
doesn't count during parameter expansion of non-named parameters. Also,
they always overwrite the positional parameters, as they are considered
after all the positional parameters have been placed on their spots.
@code
function test( par1, par2, par3 )
>> "Par1: ", par1
>> ", Par2: ", par2
> ", Par3: ", par3
end
x = lbind( "par2", "Hello" )
test( x ) // nil->par1, "Hello"->par2, nil->par3
test( x, "Yo!" ) // "Yo!"->par1, "Hello"->par2, nil->par3
test( "Yo!", x ) // as above
test( "Yo!", "Yo! again", x ) // "Hello" overwrites "Yo again"
test( x, "Yo!", "Yo! again", "end" ) // "Yo!"->par1, "Hello"->par2, "end"->par3
@endcode
@note lbind is @b not an ETA function.
*/
FALCON_FUNC core_lbind ( ::Falcon::VMachine *vm )
{
Item *i_name = vm->param(0);
Item *i_value = vm->param(1);
if( i_name == 0 || !i_name->isString() )
{
throw new ParamError( ErrorParam( e_inv_params )
.origin(e_orig_runtime)
.extra( "S" ) );
}
GarbageItem *itm = i_value == 0 ? 0 : new GarbageItem( *i_value );
vm->regA().setLBind( new CoreString( *i_name->asString() ), itm );
}
static bool core_let_next( ::Falcon::VMachine *vm )
{
*vm->param(0) = vm->regA();
return false;
}
/*#
@function let
@inset functional_support
@brief Assigns a value to another in a functional context.
@param dest Destination value (passed by reference).
@param source Source value.
@return The assigned (source) value.
This function assigns a literal value given in @b source into @b dest,
provided dest is a late binding or is passed by referece.
This function is an ETA and prevents evaluation of its first parameter. In other
words, the first parameter is treadted as if passed through @a lit.
*/
FALCON_FUNC core_let ( ::Falcon::VMachine *vm )
{
Item *i_dest = vm->param(0);
Item *i_source = vm->param(1);
if( i_dest == 0 || ! vm->isParamByRef( 0 ) || i_source == 0 )
{
throw new ParamError( ErrorParam( e_inv_params )
.origin(e_orig_runtime)
.extra( "$X,X" ) );
}
vm->returnHandler( &core_let_next );
if ( vm->functionalEval( *i_source ) )
{
return;
}
vm->returnHandler( 0 );
*vm->param(0) = *vm->param(1);
vm->regA() = *vm->param(0);
}
static bool core_brigade_next( ::Falcon::VMachine *vm )
{
int64 next = vm->local(0)->asInteger();
// Has the previous call returned something interesting?
if ( vm->regA().isOob() )
{
if( vm->regA().isInteger() )
{
// break request?
if( vm->regA().asInteger() == 0 )
{
vm->retnil();
return false;
}
else if( vm->regA().asInteger() == 1 )
{
// loop from start
next = 0;
}
}
else if ( vm->regA().isArray() )
{
CoreArray* newParams = vm->regA().asArray();
*vm->local(1) = newParams;
// add a space for the calls
newParams->prepend( Item() );
}
}
CoreArray* list = vm->param(0)->asArray();
// are we done?
if( next >= list->length() )
return false;
// prepare the local call
vm->local(0)->setInteger( next + 1 );
// anyhow, prepare the call
//-- have we changed parameters?
if ( vm->local(1)->isArray() )
{
CoreArray* callarr = vm->local(1)->asArray();
callarr->at(0) = list->at((int32)next);
vm->callFrame( callarr, 0 );
}
else
{
// no? -- use our original paramters.
for( int32 i = 1; i < vm->paramCount(); ++i )
{
vm->pushParameter( *vm->param(i) );
}
vm->callFrame( list->at((int32)next), vm->paramCount()-1 );
}
return true; // call me again
}
/*#
@function brigade
@inset functional_support
@brief Process a list of functions passing the same parameters to them.
@param fl The sequence of callable items to be called.
@param ... Arbitrary parameters used by the brigade functions.
@return The return value of the last function in fl.
This function process a sequence of functions passing them the
same set of parameters. The idea is that of a "brigate" of functions
operating all on the same parameters so that it is possible to put
common code into separate functions.
Items in the list are not functionally evaluated; they are simply called,
passing to them the same parameters that the brigade group receives. Brigate
is an ETA funcion, and this means that ongoing functional evaluation is
interrupted as soon as a brigade is encountered.
@code
function mean( array )
value = 0
for elem in array: value += elem
return value / len( array )
end
function dbl( array )
for i in [0:len(array)]: array[i] *= 2
end
doubleMean = .[ brigade .[
dbl
mean
]]
> "Mean: ", mean( [1,2,3] )
> "Double mean: ", doubleMean( [1,2,3] )
@endcode
The above example brigades a "prefix" function to double the values in
an array that must be processed by the main function.
Using out of band return values, the functions in the sequence can also
control the parameters that the following functions will receive, terminate
immediately the evaluation or restart it, forming a sort of iterative
functional loop. An oob 0 causes the sequence to be interrutped (and return oob(0) itself),
an out of band 1 will cause the first element of the sequence to be called again, and
an out of band array will permanently change the parameters as seen by the functions.
The following brigate performs a first step using the given parameters, and another one
using modified ones:
@code
looper = .[brigade .[
{ val, text => printl( text, ": ", val ) } // do things
{ val, text => oob( [val+1, "Changed"] ) } // change params
{ val, text => val >= 10 ? oob(0) : oob(1)} // loop control
]]
looper( 1, "Original" )
@endcode
*/
FALCON_FUNC core_brigade ( ::Falcon::VMachine *vm )
{
Item *i_fl = vm->param(0);
if( i_fl == 0 || ! i_fl->isArray() )
{
throw new ParamError( ErrorParam( e_inv_params, __LINE__ )
.origin(e_orig_runtime)
.extra( "A" ) );
}
// nothing to do?
if ( i_fl->asArray()->length() == 0 )
{
vm->retnil();
return;
}
vm->returnHandler( &core_brigade_next );
vm->addLocals(2);
vm->local(0)->setInteger(1);
vm->local(1)->setNil();
// anyhow, prepare the call
for( int32 i = 1; i < vm->paramCount(); ++i )
{
vm->pushParameter( *vm->param(i) );
}
vm->callFrame( vm->param(0)->asArray()->at(0), vm->paramCount()-1 );
//throw new ParamError( ErrorParam( e_non_callable,__LINE__ ).origin(e_orig_runtime) );
}
}
}
/* end of functional_ext.cpp */
|