Skip to main content Accessibility help
Internet Explorer 11 is being discontinued by Microsoft in August 2021. If you have difficulties viewing the site on Internet Explorer 11 we recommend using a different browser such as Microsoft Edge, Google Chrome, Apple Safari or Mozilla Firefox.

Chapter 14: Programming With Streams

Chapter 14: Programming With Streams

pp. 187-207

Authors

, Yale University, Connecticut
  • Add bookmark
  • Cite
  • Share

Summary

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.

About the book

Access options

Review the options below to login to check your access.

Purchase options

eTextbook
US$79.00
Hardback
US$182.00
Paperback
US$79.00

Have an access code?

To redeem an access code, please log in with your personal login.

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.

Also available to purchase from these educational ebook suppliers