% Copyright The Numerical Algorithms Group Limited 1992-94. All rights reserved. % !! DO NOT MODIFY THIS FILE BY HAND !! Created by ht.awk. \newcommand{\StreamXmpTitle}{Stream} \newcommand{\StreamXmpNumber}{9.76} % % ===================================================================== \begin{page}{StreamXmpPage}{9.76 Stream} % ===================================================================== \beginscroll A \spadtype{Stream} object is represented as a list whose last element contains the wherewithal to create the next element, should it ever be required. \xtc{ Let \spad{ints} be the infinite stream of non-negative integers. }{ \spadpaste{ints := [i for i in 0..] \bound{ints}} } By default, ten stream elements are calculated. This number may be changed to something else by the system command \spadcmd{)set streams calculate}. %-% \HDsyscmdindex{set streams calculate}{StreamXmpPage}{9.76}{Stream} For the display purposes of this book, we have chosen a smaller value. \xtc{ More generally, you can construct a stream by specifying its initial value and a function which, when given an element, creates the next element. }{ \spadpaste{f : List INT -> List INT \bound{fdec}} } \xtc{ }{ \spadpaste{f x == [x.1 + x.2, x.1] \bound{f}\free{fdec}} } \xtc{ }{ \spadpaste{fibs := [i.2 for i in [generate(f,[1,1])]] \bound{fibs}\free{f}} } \xtc{ 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. }{ \spadpaste{[i for i in ints | odd? i] \free{ints}} } \xtc{ }{ \spadpaste{odds := [2*i+1 for i in ints]\bound{odds}\free{ints}} } \xtc{ You can accumulate the initial segments of a stream using the \spadfunFrom{scan}{StreamFunctions2} operation. }{ \spadpaste{scan(0,+,odds) \free{odds}} } \xtc{ The corresponding elements of two or more streams can be combined in this way. }{ \spadpaste{[i*j for i in ints for j in odds]\free{ints} \free{odds}} } \xtc{ }{ \spadpaste{map(*,ints,odds)\free{ints odds}} } \xtc{ Many operations similar to those applicable to lists are available for streams. }{ \spadpaste{first ints \free{ints}} } \xtc{ }{ \spadpaste{rest ints \free{ints}} } \xtc{ }{ \spadpaste{fibs 20 \free{fibs}} } The packages \spadtype{StreamFunctions1}, %-% \HDexptypeindex{StreamFunctions1}{StreamXmpPage}{9.76}{Stream} \spadtype{StreamFunctions2} and %-% \HDexptypeindex{StreamFunctions2}{StreamXmpPage}{9.76}{Stream} \spadtype{StreamFunctions3} export some useful stream manipulation operations. %-% \HDexptypeindex{StreamFunctions3}{StreamXmpPage}{9.76}{Stream} For more information, see \downlink{``\ugLangItsTitle''}{ugLangItsPage} in Section \ugLangItsNumber\ignore{ugLangIts}, \downlink{``\ugProblemSeriesTitle''}{ugProblemSeriesPage} in Section \ugProblemSeriesNumber\ignore{ugProblemSeries}, \downlink{`ContinuedFraction'}{ContinuedFractionXmpPage}\ignore{ContinuedFraction}, and \downlink{`List'}{ListXmpPage}\ignore{List}. % \showBlurb{Stream} \endscroll \autobuttons \end{page} %