9.76 Stream

A Stream object is represented as a list whose last element contains the wherewithal to create the next element, should it ever be required.

Let ints be the infinite stream of non-negative integers.

ints := [i for i in 0..]
\[\]
[0,1,2,3,4,5,6,7,8,9,…]

Type: Stream NonNegativeInteger

By default, ten stream elements are calculated. This number may be changed to something else by the system command )set streams calculate. For the display purposes of this book, we have chosen a smaller value.

More generally, you can construct a stream by specifying its initial value and a function which, when given an element, creates the next element.

f : List INT -> List INT

Void

f x == [x.1 + x.2, x.1]

Void

fibs := [i.2 for i in [generate(f,[1,1])]]
Compiling function f with type List Integer -> List Integer
\[\]
[1,1,2,3,5,8,13,21,34,55,…]

Type: Stream Integer

You can create the stream of odd non-negative integers by either filtering them from the integers, or by evaluating an expression for each integer.

[i for i in ints | odd? i]
\[\]
[1,3,5,7,9,11,13,15,17,19,…]

Type: Stream NonNegativeInteger

odds := [2*i+1 for i in ints]
\[\]
[1,3,5,7,9,11,13,15,17,19,…]

Type: Stream NonNegativeInteger

You can accumulate the initial segments of a stream using the scanscanStreamFunctions2 operation.

scan(0,+,odds)
\[\]
[1,4,9,16,25,36,49,64,81,100,…]

Type: Stream NonNegativeInteger

The corresponding elements of two or more streams can be combined in this way.

[i*j for i in ints for j in odds]
\[\]
[0,3,10,21,36,55,78,105,136,171,…]

Type: Stream NonNegativeInteger

map(*,ints,odds)
\[\]
[0,3,10,21,36,55,78,105,136,171,…]

Type: Stream NonNegativeInteger

Many operations similar to those applicable to lists are available for streams.

first ints
\[\]
0

Type: NonNegativeInteger

rest ints
\[\]
[1,2,3,4,5,6,7,8,9,10,…]

Type: Stream NonNegativeInteger

fibs 20
\[\]
6765

Type: PositiveInteger

The packages StreamFunctions1, StreamFunctions2 and StreamFunctions3 export some useful stream manipulation operations. For more information, see ugLangItsPage in Section ugLangItsNumber , ugProblemSeriesPage in Section ugProblemSeriesNumber , ContinuedFractionXmpPage , and ListXmpPage .