Collection – Creating Lists and Streams with Iterators

All of the loop expressions which do not use the repeat leave or iterate words can be used to create lists and streams. For example:

This creates a simple list of the integers from 1 to 10:

list := [i for i in 1..10]
 [1,2,3,4,5,6,7,8,9,10]
                    Type: List PositiveInteger

Create a stream of the integers greater than or equal to 1:

stream := [i for i in 1..]
 [1,2,3,4,5,6,7,...]
                    Type: Stream PositiveInteger

This is a list of the prime numbers between 1 and 10, inclusive:

[i for i in 1..10 | prime? i]
 [2,3,5,7]
                    Type: List PositiveInteger

This is a stream of the prime integers greater than or equal to 1:

[i for i in 1.. | prime? i]
 [2,3,5,7,11,13,17,...]
                    Type: Stream PositiveInteger

This is a list of the integers between 1 and 10, inclusive, whose squares are less than 700:

[i for i in 1..10 while i*i < 700]
 [1,2,3,4,5,6,7,8,9,10]
                    Type: List PositiveInteger

This is a stream of the integers greater than or equal to 1 whose squares are less than 700:

[i for i in 1.. while i*i < 700]
 [1,2,3,4,5,6,7,...]
                    Type: Stream PositiveInteger

The general syntax of a collection is

[ collectExpression iterator1 iterator2 ... iteratorN ]

where each iterator is either a for or a while clause. The loop terminates immedidately when the end test of any iterator succeeds or when a return expression is evaluated in collectExpression. The value returned by the collection is either a list or a stream of elements, one for each iteration of the collectExpression.

Be careful when you use while to create a stream. By default FriCAS tries to compute and display the first ten elements of a stream. If the while condition is not satisfied quickly, FriCAS can spend a long (potentially infinite) time trying to compute the elements. Use

)set streams calculate

to change the defaults to something else. This also affects the number of terms computed and displayed for power series. For the purposes of these examples we have use this system command to display fewer than ten terms.

Table Of Contents

This Page