Streams Contract is the same as pairs... (head (pair-stream x str)) = x (tail (pair-stream x str)) = str ...but order of evaluation is different (pair-stream x str) evaluates x immediately, delays evaluation of str (tail str) forces evaluation of the tail
26
Embed
Streams Contract is the same as pairs... (head (pair-stream x str)) = x
Streams Contract is the same as pairs... (head (pair-stream x str)) = x (tail (pair-stream x str)) = str ...but order of evaluation is different (pair-stream x str) evaluates x immediately, delays evaluation of str (tail str) forces evaluation of the tail. - PowerPoint PPT Presentation
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Streams
Contract is the same as pairs...
(head (pair-stream x str)) = x (tail (pair-stream x str)) = str
...but order of evaluation is different
(pair-stream x str) evaluates x immediately, delays evaluation of str
(tail str) forces evaluation of the tail
Lazy Evaluation
compute values only when neededimplement with special form delay
(delay expr) make a promise to evaluate expr when forced to
Print 0, force the tail (integers-from (inc 0)) evaluate (inc 0) ==> 1 evaluate integers-from ==> (1 . {proc () (integers-from (inc 1))})Print 1, force the tail... (2 . {promise (integers-from (inc 2))})Print 2, force the tail... (3 . {promise (integers-from (inc 3))})Print 3, force the tail...
Sieve of Eratosthenes (300 BC)
• 2 is prime• a number n > 2 is prime iff
it is not divisible by any smaller prime
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40 41 42 43 44
45 46 47 48 49 50 ...
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40 41 42 43 44
45 46 47 48 49 50 ...
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40 41 42 43 44
45 46 47 48 49 50 ...
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40 41 42 43 44
45 46 47 48 49 50 ...
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40 41 42 43 44
45 46 47 48 49 50 ...
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40 41 42 43 44
45 46 47 48 49 50 ...
(define (sieve <function>) (method ((s <stream>)) (bind ((next-prime (head s))) ;head is prime (pair-stream next-prime (sieve ;recursively sieve tail after (filter ;removing all multiples of head (method ((x <integer>)) (not (divisible? x next-prime))) (tail s)))))))
(define (add-streams <function>) (method ((a <stream>) (b <stream>)) (cond ((empty-stream? a) b) ((empty-stream? b) a) (else: (pair-stream (+ (head a) (head b)) (add-streams (tail a) (tail b)))))))