July 20, 2012
Stream provides functions to create and manipulate infinite lists. It is defined as:
data Stream a = Cons a (Stream a)
It is now available on Fedora. Install it using:
$ sudo yum install ghc-Stream-devel
The fromList function converts an infinite list to a stream. For example:
Prelude> import qualified Data.Stream as S
Prelude Data.Stream> let numbers = S.fromList [1..]
Prelude Data.Stream> S.head numbers
1
There are numerous functions available for building, transforming, extracting, sublisting, indexing streams. Most of them are analogous to the functions in Data.List. Few examples:
The map function applies a function uniformly over all the elements of a stream.
Prelude Data.Stream> S.take 5 $ S.map (*3) numbers
[3,6,9,12,15]
The cycle function can return an infinite repetition of a given list.
Prelude Data.Stream> S.take 10 $ S.cycle [1,2,3]
[1,2,3,1,2,3,1,2,3,1]
The take function extracts a sublist of n elements from the stream.
Prelude Data.Stream> S.take 10 numbers
[1,2,3,4,5,6,7,8,9,10]
We can use the (!!) function to return an element at an index n in the stream.
~~~~ {.haskell} Prelude Data.Stream> numbers S.!! 5 6 ~~~~