Skip to content

Foreach

Christopher Ross-Gill edited this page Aug 1, 2016 · 1 revision

The FOREACH function now allows you to access the series, not just the values of the series. In other words, it blends the best of FORALL and FOREACH.

This change also affects REMOVE-EACH and the new MAP function.

To refer to the series itself, you use a set word in the variables block. This becomes a series reference. (The set-word notation is consistent with that used in the parse dialect for a similar purpose.)

For example:

>> data: [1 2 3 4]
>> foreach [where: value] data [change where value + 1]
>> data
== [2 3 4 5]

Here the WHERE: variable refers to the series, so the CHANGE modifies the actual series block.

Note that the series reference does not advance the series index.

So, this is an infinite loop, because the index is never changed:

foreach [where:] data [change where 1]

But, this can be useful. The "non advancing" behavior of a series reference allows you to use functions that may modify the series in other ways. For example, the MAP function when used with TAKE:

>> map [where:] [1 2 3 4 5 6] [take/part where 2]
== [[1 2] [3 4] [5 6]]

If the WHERE: reference advanced the series index, then this expression would not be as friendly.

Compare this with:

>> map [where: val] [1 2 3 4 5 6] [take/part where 2]
== [[1 2] [4 5]]

Here the index is advanced (by the VAL variable), so the results are different.

Also: The set-word can appear anywhere in the variables block, and it will be relative to that position.

And finally: you must be very careful modifying a series in FOREACH, REMOVE-EACH, and MAP, because you are relying on the internal behavior of those functions regarding how they handle the series. It is best to keep your usage very simple and clean.

Clone this wiki locally