[Next] [Prev] [Right] [Left] [Up] [Index] [Root]
Recursion, Reduction, and Iteration

Recursion, Reduction, and Iteration

Subsections

Recursion

It is often very useful to be able to refer to a sequence currently under construction, for example to define the sequence recursively. For this purpose the Self operator is available.

Self(n) : RngIntElt -> Elt
Self() : RngIntElt -> SeqEnum
This operator enables the user to refer to an already defined previous entry s[n] of the enumerated sequence s inside the sequence constructor, or the sequence s itself.

Example Seq_Self (H8E5)

The example below shows how the sequence of the first 100 Fibonacci numbers can be created recursively, using Self. Next it is shown how to use reduction on these 100 integers.

> s := [ i gt 2 select Self(i-2)+Self(i-1) else 1 : i in [1..100] ];
> &+s;
927372692193078999175

Reduction

Instead of using a loop to apply the same binary associative operator to all elements of a complete enumerated sequence, it is possible to use the reduction operator &.

& o S : Op, SeqEnum -> Elt
Given a complete enumerated sequence S = [ a_1, a_2, ..., a_n ] of elements belonging to an algebraic structure U, and an (associative) operator o : U x U -> U, form the element a_1 o a_2 o a_3 o ... o a_n.

Currently, the following operators may be used to reduce sequences: +, *, and, or, join, meet, cat. An error will occur if the operator is not defined on U.

If S contains a single element a, then the value returned is a. If S is the null sequence (empty and no universe specified), then reduction over S leads to an error; if S is empty with universe U in which the operation is defined, then the result (or error) depends on the operation and upon U. The following table defines the return value:

EMPTY NULL &+ U!0 error &* U!1 error &and true true &or false false &join empty null &meet error error &cat empty null

[Next] [Prev] [Right] [Left] [Up] [Index] [Root]