Recall that in Chapter 6 we used an infinite list to simulate a mathematical sequence used in the calculation or the perimeter of an ellipse. When a list is used in a context where it will always he infinite, it is commonly called a stream, Many problems can be elegantly, concisely, and efficiently expressed using streams, which we will explore in this chapter. With the power of streams there are also inherent dangers, which we will also explore. In the next chapter we will use streams in a central way in the implementation of a language for expressing reactive animations.
Lazy Evaluation
Because streams are never finite, it would seem natural to define a special polymorphic data type for them, such as:
data Stream a = a : Stream a
Although we could certainly do this, it is more convenient to use Haskell lists to “simulate” streams by just never using the empty list constructor []. The main advantage of this approach is that we can then reuse many polymorphic functions already defined on lists rather than redefining them on a new data type.
In Chapter 6 we used list comprehensions to create the infinite list [2, 2.], but is there a more fundamental way to create this list? Here is one way:
twos = 2 : twos
Let's compute this value by calculation:
twos
⇒ 2 : twos
⇒ 2 : 2 : twos
⇒ 2 : 2 : 2 : twos
…
There is, of course, no end to this calculation, An important distinction exists, however, between this calculation and ones that we have labeled as “infinite loops” and given the value ⊥ in previous chapters: this calculation is producing useful information, namely the successive elements of a list. Its value is an infinite list, or stream, A stream contains an infinite amount of information, whereas ⊥ contains no information whatsoever.
DETAILS
Try running this example, in Hugs, if you type twos to the evaluation prompt, it will go into an infinite loop printing 2's.
Now consider the expression head twos.
Review the options below to login to check your access.
Log in with your Cambridge Aspire website account to check access.
If you believe you should have access to this content, please contact your institutional librarian or consult our FAQ page for further information about accessing our content.