SPL Programming - 5.4 [Sequence as a whole] Iterative function*

 

We can also use more basic iterative function to complete the calculation of e without using a temporary variable.

Iterative function A.iterate@a(x,a) of sequence A has two parameters x and a. We’ll neglect the @a here for the moment, simply think that @a is a part of the function name, i.e., the function name is iterate@a. We’ll talk about this @ soon.

As a loop function, A.iterate@a(x,a) will calculate x for each member of A, ~ and # can be used in expression x to represent the current member and sequence number of A in the loop, which is the same as other loop functions. The difference is that the symbol ~~ is also provided in the iterative function, which is used to represent the x calculated in the previous cycle. When the loop starts, the initial value of ~~ is the parameter a. After all members loop, return the sequence of ~~, which has the same length as A.

The function A.iterate (x,a) without @a is defined as the last member of A.iterate@a(x,a), that is, the intermediate process is no longer integrated into the sequence, only retain the last ~~.


Let’s go through a few examples:

1. A.iterate(~~+~,0)

The initial ~~ is 0, the current member ~ will be added to ~~ in each round of the loop, and finally we’ll get the sum of all members, namely A.sum().

2. A.iterate@a(~~+~,0)

@a retains the results of each round of calculation, that is, the cumulative value from the beginning to the current member, which is equivalent to A.([:0].sum()).

3. A.iterate(if(~~<~,~,~~),-inf())

inf()is infinity, -inf() is negative infinity, which is the minimum number. In each cycle, if the current member ~ is larger than ~~, ~~ is replaced by ~, and the final result is A.max().

4. A.iterate(if(~~>~,~,~~),inf())

This is similar to the previous one, and will get A.min().

5. A.iterate(if(~,~~+1,~~),0)

After analysis, we can see that it will be calculated as A.count().


It seems that the iterative function is the “parent function” of these aggregate functions, which can be defined by the iterative function. It is easy to define an operation of successive multiplication of sequence members with iterative function: A.iterate(~~*~,1). Factorial operation is a special case: n.iterate(~~*~,1).

In fact, A.(x) can also be interpreted as A.iterate(~~|[x],[]) or A.iterate@a(x,null). Iterative function is indeed the “parent function” of other loop functions.

Now we can calculate e in one line:

=1+20.iterate@a(~~*~,1).sum(1/~)

The iterative function in the middle will also be calculated as a sequence of factorial values.


SPL Programming - Preface
SPL Programming - 5.3 [Sequence as a whole] Loop functions: advanced
SPL Programming - 5.5 [Sequence as a whole] Positioning and selection