; CSE 341, lecture 21: delayed evaluation, thunks, streams ; Returns x^2. Has a side effect (printing) ; so you can tell when it has been called. (define (square x) (display "squaring ") (display x) (newline) (* x x)) ; Original version of foo that computes both e1 and e2. ; example call: (foo (< 2 3) (square 4) (square 7)) (define (foo b e1 e2) (if b (+ e1 e1 e1) ; true case (* e2 e2))) ; false case ; Second version of foo that accepts two 'thunks' ; (parameterless procedures) to avoid calling one or the other. ; example call: (foo (< 2 3) (lambda () (square 4)) (lambda () (square 7))) (define (foo2 b th1 th2) (if b (+ (th1) (th1) (th1)) ; true case (* (th2) (th2)))) ; false case ; Best version of foo that accepts two 'promise' values ; and computes only the one that is necessary. ; example call: (foo (< 2 3) (delay (square 4)) (delay (square 7))) (define (foo3 b pr1 pr2) (if b (+ (force pr1) (force pr1) (force pr1)) ; true case (* (force pr2) (force pr2)))) ; false case ; ------- STREAMS ------- ; A stream (infinite list) containing an endless list of 1s: 1, 1, 1, ... (define ones (lambda () (cons 1 ones))) ; A stream of all natural numbers: 1, 2, 3, 4, ... (define (nat-nums) (define (helper x) (cons x (lambda () (helper (+ x 1))))) (helper 1)) ; A stream of all powers of two: 1, 2, 4, 8, 16, ... (define (powers-of-two) (define (helper x) (cons x (lambda () (helper (* x 2))))) (helper 1)) ; Returns the first k elements of the given stream. (define (stream-slice stream k) (if (<= k 0) '() (let ((strpair (stream))) (cons (car strpair) (stream-slice (cdr strpair) (- k 1)))))) ; A stream for the harmonic series: 1, 1/2, 1/3, 1/4, ... (define (harmonic) (define (helper x) (cons (/ 1 x) (lambda () (helper (+ x 1))))) (helper 1))