This is the end of the preview. Sign up
to
access the rest of the document.

Unformatted text preview: S TREAMS 20 GEORGE WANG gswang.cs61a@gmail.com Department of Electrical Engineering and Computer Sciences University of California, Berkeley July 27, 2010 1 Motivation Streams are an abstract data type, not so different from rational numbers, in that we have constructors and selectors for them. But we use a clever trick to achieve tremendously magical results. As we talk about the mechanics of streams, there are three big ideas to keep in mind: Efficiency: Decouple order of evaluation from the form of the program. Infinite data sets. Functional representation of time-varying information (versus OOP). Youll understand what these all mean after we look at some examples. How do we tell if a number n is prime? Never mind computers, how would you express this idea as a mathematician? Something like this: N is prime if it has no factors in the range 2 f &lt; n. So, to implement this on a computer, we should : Get all the numbers in the range [2 ,n- 1] . See which of those are factors of n. See if the result is empty. ;;;;; In file cs61a/lectures/3.5/prime1.scm (define (prime? n) (null? (filter (lambda (x) (= (remainder n x) 0)) (range 2 (- n 1))))) But we dont usually program it that way. Instead, we write a loop: ;;;;; In file cs61a/lectures/3.5/prime0.scm (define (prime? n) 1 (define (iter factor) (cond ((= factor n) #t) ((= (remainder n factor) 0) #f) (else (iter (+ factor 1))))) (iter 2)) (Never mind that we can make small optimizations like only checking for factors up to n . Lets keep it simple.) Why dont we write it the way we expressed the problem in words? The problem is one of efficiency. Lets say we want to know if 1000 is prime. We end up constructing a list of 998 numbers and testing all of them as possible factors of 1000, when testing the first possible factor would have given us a false result quickly. 2 Overview The idea of streams is to let us have our cake and eat it too. Well write a program that looks like the first version, but runs like the second one. All we do is change the second version to use the stream ADT instead of the list ADT: ;;;;; In file cs61a/lectures/3.5/prime2.scm (define (prime? n) (stream-null? (stream-filter (lambda (x) (= (remainder n x) 0)) (stream-range 2 (- n 1))))) The only changes are stream-range instead of range , stream-null? instead of null? , and stream-filter instead of filter . How does it work? A list is implemented as a pair whose car is the first element and whose cdr is the rest of the elements. A stream is almost the same: Its a pair whoseis the rest of the elements....
View Full
Document