60 likes | 146 Views
Dive into the concept of streams in programming, how they differ from lists, and how to efficiently work with infinite data sequences without storing everything in memory. Learn through examples and theory discussions in Scheme.
E N D
Streams Review A Review of Streams Mark Boady
What Are Steams? • Delayed lists • We pretend that the stream is a list • In reality we only know the next value, but we know how to compute the rest • When the user asks for a value, compute exactly what is needed • L = [ CurrentValueFunctionToComputeNext]
Theory Example • We want a stream with every prime number • Finding every prime number is obviously impossible • Assume we have the function • NextPrime(n) returns the first prime found after n • The stream object starts with • Prime-stream ={ 2, NextPrime} • When the user asks for the cdr of the stream, we use NextPrime to find it.
Theory Example • prime-stream ={ 2, NextPrime} • Car prime-stream would return 2 • Cdr of prime-stream is {NextPrime(2), NextPrime} • Which is {3, NextPrime} • Applying cdr again repeats the process • Cdr of cdr of primestream is {NextPrime(3), NextPrime}
The point • We can use list operations on a huge or infinite list without needing to actually store the list in memory • In scheme, the following special commands are used • stream-cons creates a stream • stream-car gets the current first element • stream-cdr get the tail of the stream • Homework Assignment • ( stream-seq f rlist )
Scheme Example (define (integers-starting-from n) (cons-stream n (integers-starting-from (+ n 1)))) (define integers (integers-starting-from 1)) (stream-car integers) (stream-car (stream-cdr integers)) (stream-car (stream-cdr (stream-cdr integers)))