Control structures, argument-binding, and return 2013-03-04 12:04:35
Control structures, argument-binding, and return
Two syntaxes were added for binding arguments: ?() and function(). This gives Cadre a more natural function definition syntax. However, ?() is also very useful in some new control structures:

First, an example of the new function definition code:

y = function(x) 1/x;
y(0.5); // returns 2

This supplements the previous syntax:

y = function 1/_args[0];
y(0.5); // returns 2

Parameters can also be captured using the ?() primitive, which does the same thing and can appear at the start of a line:

y = function ?(x) 1/x;
y(0.5); // returns 2

This is more useful in contexts where the "function" keyword is implicit, such as each, sieve, and reduce.

Four new control structures were implemented: map, filter, fold, and for. for is standard C, except with the peculiarity that commas are used to separate the arguments, not semicolons:

var j = 0;
for(var i = 0, i < 10, i++) j += i;

map, filter, and fold work like their Haskell equivalents—they take a function as their first argument, and take a list as their second (although map takes an arbitrary number of lists), and apply that function to the list, producing various results:

functionblock versionpurpose
map(f, a, ...)each(a, ...) ?(x, ...) f(x, ...);Returns an array of the same length with all elements modified by f.
filter(f, a)sieve(a) ?(x) f(x);Returns an array of the same or shorter length, only keeping elements if f is true for them.
fold(f, a)reduce(a) ?(x, y) f(x, y);Returns a single value created by applying the same operation to the list elements until the list is exhausted. The first element of the list is assumed to be the base case.

All of these have an x version (e.g. mapx) which retains the indices of the input array (in mapx/eachx's case, only of the first sequence). The map family of functions will fail if not all lists are the same length. If you ask for additional parameters, you'll start getting the indices—e.g. map(f, l1, l2) provides four parameters to f in total (data1, data2, index1, index2).

Note that since, in all cases (even the block cases), a stack frame is created, return cannot be used from within these structures to break out of the parent function. This is a problem also faced by Ruby in certain circumstances. In Octavia, it is solved with the answer keyword, which is essentially a return-then-break. To maintain good style it should not be used outside of one of these block statements.
Cadre News comment · 6 years ago