notes13s -...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
CS61A Notes 13 – My Body’s Floating Down The Muddy Stream [Solutions v1.0] Streaming Along 1. Define a procedure  (ones)  that, when run with no arguments, returns a  cons  pair whose  car  is  1 and whose  cdr  is a procedure that, when run, does the same thing. (define (ones) (cons 1 (lambda() (ones)))), or, just (define (ones) (cons 1 ones)) 2. Define a procedure  (integers-starting n)  that takes in a number  n  and, when run, returns a  cons  pair whose  car  is  n , and whose  cdr  is a procedure that, when run with no arguments, does  the same thing for  n +1. (define (integers-starting n) (cons n (lambda() (integers-starting (+ n 1))))) Constructing Streams Directly Describe what the following expressions define: 1. (define s1 (add-stream (stream-map (lambda(x) (* x 2)) s1) s1)) infinite loop! We didn’t specify a first element. Even the define statement will go into infinite loop. 2. (define s2 (cons-stream 1 (add-stream (stream-map (lambda(x) (* x 2)) s2) s2))) this is: 1 2 6 18 . .. + 1 3 9 ... =============== 1 3 9 27 . .. So powers of 3. 3. (define s3 (cons-stream 1 (stream-filter (lambda(x) (not (= x 1))) s3))) Remember: (define (stream-filter pred? s) (cond ((stream-null? s) the-empty-stream) ((pred? (stream-car s)) (cons-stream (stream-car s) (stream-filter pred? (stream-cdr s)))) (else (stream-filter pred? (stream-cdr s))))) Infinite loop! stream-filter will keep trying to look for a number that’s not 1. Or, more specifically, stream-filter, failing to find a non-1 element in stream-car, will call stream-filter again, which will call stream-filter again, and so on. Chung Wu; CS61A, Fall 2003
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
4. (define s4 (cons-stream 1 (cons-stream 2 (stream-filter (lambda(x) (not (= x 1))) s4)))) (1 2 2 2 2. ..) Rather counter-intuitive, but. .. well, we know that it starts with 1 and 2, since we said so. Then, the stream-cddr will be a stream that is produced by the stream-filter. stream-filter returns a stream whose first element is the first non-1 element of s4 (namely, 2), and whose promise is (stream-filter pred? (stream-cdr s)), where pred? is the
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 5

notes13s -...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online