1 6.001 SICP Infinite streams – using lazy evaluation Beyond Scheme – designing language variants: Streams – an alternative programming style!

Slides:



Advertisements
Similar presentations
1 Programming Languages (CS 550) Lecture Summary Functional Programming and Operational Semantics for Scheme Jeremy R. Johnson.
Advertisements

1 Programming Languages (CS 550) Operational Semantics of Scheme using Substitution and the Lambda Calculus Jeremy R. Johnson TexPoint fonts used in EMF.
1 Programming Languages (CS 550) Lecture 7 Summary Operational Semantics of Scheme using Substitution Jeremy R. Johnson TexPoint fonts used in EMF. Read.
מבוא מורחב למדעי המחשב תרגול 13 Lazy Evaluation. Lazy Evaluation Implementation Two types of values – Delayed Values – Actual Values Introduce two functions.
Cs7100(Prasad)L11Clos1 Closures and Streams. Contemporary Interest in Closures The concept of closures was developed in the 1960s and was first fully.
מבוא מורחב - שיעור 15 1 Lecture 15 Streams. מבוא מורחב - שיעור 15 2 Streams: Motivation (define (sum-primes a b) (define (iter count accum) (cond ((>
6.001 SICP 1 Normal (Lazy) Order Evaluation Memoization Streams.
Types of the past exam questions I. Write/Complete Code II. Evaluate Expressions III. Analyze Complexity IV. Meta-circular Evaluator.
Chapter 15 Functional Programming Languages. Copyright © 2007 Addison-Wesley. All rights reserved. 1–2 Introduction Design of imperative languages is.
מבוא מורחב למדעי המחשב בשפת Scheme תרגול 13. Streams 3.5, pages definitions file on web 2.
SICP Interpretation part 1 Parts of an interpreter Arithmetic calculator Names Conditionals and if Store procedures in the environment.
מבוא מורחב - שיעור 81 Lecture 8 Lists and list operations (continue).
Functional programming: LISP Originally developed for symbolic computing First interactive, interpreted language Dynamic typing: values have types, variables.
Cs776 (Prasad)L15strm1 Reasoning with Functional Programs Optimization by source to source transformation Well-founded induction Streams : Infinite lists.
SICP Variations on a Scheme (2) Beyond Scheme – designing language variants: Lazy evaluation Complete conversion – normal order evaluator Upward.
Closures and Streams More on Evaluations CS784(pm)1.
1 Lecture OO, the notion of inheritance 3 Stacks in OO style (define (make-stack) (let ((top-ptr '())) (define (empty?) (null? top-ptr)) (define.
CS220 Programming Principles 프로그래밍의 이해 2002 가을학기 Class 13: Streams 한 태숙.
SICP Interpretation Parts of an interpreter Arithmetic calculator Names Conditionals and if Storing procedures in the environment Environment as.
1 The Evaluator. 2 Compiler vs. Interpreter Command Processing Unit The Computer Program in Low Level Machine Language Program in High Level Language.
1 Lecture 20 Lazy Evaluation Continued (4.2.1, 4.2.2) MC-eval examples from exams (Time permitting)
1 Read-Eval-Print Loop (define (driver-loop) (prompt-for-input input-prompt) (let ((input (read))) (let ((output (eval input the-global-env))) (announce-output.
6.001 SICP 1/ SICP Object Oriented Programming Data Abstraction using Procedures with State Message-Passing Object Oriented Modeling Class diagrams.
1 Programming Languages (CS 550) Lecture 4 Summary Functional Programming and Operational Semantics for Scheme Jeremy R. Johnson.
SICP Object Oriented Programming Data Abstraction using Procedures with State Message-Passing Object Oriented Modeling Class diagrams Instance.
1 Lecture 19 Dynamic Scoping Lazy Evaluation (4.2.1, 4.2.2)
1 מבוא מורחב למדעי המחשב בשפת Scheme תרגול Outline Mutable list structure RPN calculator Vectors and sorting.
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,
6.037 Lecture 7B Scheme Variants Normal Order Lazy Evaluation Streams Edited by Mike Phillips & Ben Vandiver Original Material by Eric Grimson & Duane.
CSE 341 Lecture 21 delayed evaluation; thunks; streams slides created by Marty Stepp
(Thunking about Thunks)
Operational Semantics of Scheme
Lecture #5 מבוא מורחב.
Lecture 4: Metacircles Eval Apply David Evans
Lecture 16 Streams continue Infinite Streams מבוא מורחב - שיעור 16.
6.001 SICP Variations on a Scheme
6.001 SICP Object Oriented Programming
PPL Lazy Lists.
The role of abstractions
September 4, 1997 Programming Languages (CS 550) Lecture 6 Summary Operational Semantics of Scheme using Substitution Jeremy R. Johnson TexPoint fonts.
Closures and Streams cs784(Prasad) L11Clos
Nondeterministic Evaluation
6.001 SICP Data abstractions
Streams Sections 3.5.1,3.5.2 Pages
Lecture #5 מבוא מורחב.
The Metacircular Evaluator
Lecture 18 Infinite Streams and
Lecture 18.
Dynamic Scoping Lazy Evaluation
The Metacircular Evaluator
Lecture #8 מבוא מורחב.
Lecture 16: Tables and OOP
6.001 SICP Streams – the lazy way
The Metacircular Evaluator (Continued)
Lecture 26: The Metacircular Evaluator Eval Apply
6.001 SICP Further Variations on a Scheme
Streams, Delayed Evaluation and a Normal Order Interpreter
Streams and Lazy Evaluation in Lisp and Scheme
6.001 SICP Variations on a Scheme
List and list operations (continue).
Closures and Streams cs7100(Prasad) L11Clos
6.001 SICP Interpretation Parts of an interpreter
Lecture # , , , , מבוא מורחב.
Assignments and Procs w/Params
Introduction to the Lab
topics interpreters meta-linguistic abstraction eval and apply
Rehearsal: Lazy Evaluation Infinite Streams in our lazy evaluator
Defining Macros in Scheme
Lecture 25: The Metacircular Evaluator Eval Apply
Presentation transcript:

SICP Infinite streams – using lazy evaluation Beyond Scheme – designing language variants: Streams – an alternative programming style!

2 Streams – a different way of structuring computation Imagine simulating the motion of an object Use state variables, clock, equations of motion to update State of the simulation captured in instantaneous values of state variables position: velocity: Ball: position: elasticity: Wall: time: clock:

3 Streams – a different way of structuring computation OR – have each object output a continuous stream of information State of the simulation captured in the history (or stream) of values x t y t

4 Remember our Lazy Language? Normal (Lazy) Order Evaluation: go ahead and apply operator with unevaluated argument subexpressions evaluate a subexpression only when value is needed –to print –by primitive procedure (that is, primitive procedures are "strict" in their arguments) Memoization -- keep track of value after expression is evaluated Compromise approach: give programmer control between normal and applicative order.

5 Variable Declarations: lazy and lazy-memo Handle lazy and lazy-memo extensions in an upward- compatible fashion.; (lambda (a (b lazy) c (d lazy-memo))...) "a", "c" are normal variables (evaluated before procedure application "b" is lazy; it gets (re)-evaluated each time its value is actually needed "d" is lazy-memo; it gets evaluated the first time its value is needed, and then that value is returned again any other time it is needed again.

6 How do we use this new lazy evaluation? Our users could implement a stream abstraction: (define (cons-stream x (y lazy-memo)) (lambda (msg) (cond ((eq? msg 'stream-car) x) ((eq? msg 'stream-cdr) y) (else (error "unknown stream msg" msg))))) (define (stream-car s) (s 'stream-car)) (define (stream-cdr s) (s 'stream-cdr)) OR (define (cons-stream x (y lazy-memo)) (cons x y)) (define stream-car car) (define stream-cdr cdr)

7 Stream Object A pair-like object, except the cdr part is lazy (not evaluated until needed): a thunk-memo a value stream-car cons-stream stream-cdr Example (define x (cons-stream 99 (/ 1 0))) (stream-car x) => 99 (stream-cdr x) => error – divide by zero

8 Decoupling computation from description Can separate order of events in computer from apparent order of events in procedure description (list-ref (filter (lambda (x) (prime? x)) (enumerate-interval )) 100) (define (stream-interval a b) (if (> a b) the-empty-stream (cons-stream a (stream-interval (+ a 1) b)))) (stream-ref (stream-filter (lambda (x) (prime? x)) (stream-interval )) 100)

9 Some details on stream procedures (define (stream-filter pred str) (if (pred (stream-car str)) (cons-stream (stream-car str) (stream-filter pred (stream-cdr str))) (stream-filter pred (stream-cdr str))))

10 Decoupling order of evaluation (stream-filter prime? (str-in )) (st-in ) 1 (stream-filter prime? ) (st-in ) (stream-filter prime? ) (st-in ) 2 (stream-filter prime? (stream-cdr 2

11 Result: Infinite Data Structures! Some very interesting behavior (define ones (cons-stream 1 ones)) (stream-car (stream-cdr ones)) => 1 1 ones The infinite stream of 1's! ones: Compare : (define ones (cons 1 ones)) => error, ones undefined

12 Finite list procs turn into infinite stream procs (define (add-streams s1 s2) (cond ((null? s1) '()) ((null? s2) '()) (else (cons-stream (+ (stream-car s1) (stream-car s2)) (add-streams (stream-cdr s1) (stream-cdr s2)))))) (define ints (cons-stream 1 (add-streams ones ints))) ones: add-streams (str-cdr ones) (str-cdr ints) 3... add-streams ones ints 2ints: 1

13 Finding all the primes

14 Remember our sieve? (define (sieve str) (cons-stream (stream-car str) (sieve (stream-filter (lambda (x) (not (divisible? X (stream-car str)))) (stream-cdr str))))) (define primes (sieve (stream-cdr ints))) ( 2 sieve (filter ints 2) ) (2 3 sieve (filter sieve (filter ints 2) 3))

15 Streams Programming Signal processing: x[n]y[n]Delay G + Streams model: add- streams stream- scale xy stream- cdr G

16 Integration as an example (define (integral integrand init dt) (define int (cons-stream init (add-streams (stream-scale dt integrand) int))) int) (integral ones 0 2) => Ones: Scale

17 An example: power series g(x) = g(0) + x g’(0) + x 2 /2 g’’(0) + x 3 /3! g’’’(0) + … For example: cos(x) = 1 – x 2 /2 + x 4 /24 - … sin(x) = x – x 3 /6 + x 5 /120 - …

18 An example: power series Think about this in stages, as a stream of values (define (powers x) (cons-stream 1 (scale-stream x (powers x))))  1 x x 2 x 3 … (define facts (cons-stream 1 (mult-streams (stream-cdr ints) facts))) => …

19 An example: power series (define (series-approx coeffs) (lambda (x) (mult-streams (div-streams (powers x) (cons-stream 1 facts)) coeffs))) (define (stream-accum str) (cons-stream (stream-car str) (add-streams (stream-accum str) (stream-cdr str))))  g(0)  g(0) + x g’(0)  g(0) + x g’(0) + x 2 /2 g’’(0)  g(0) + x g’(0) + x 2 /2 g’’(0) + x 3 /3! g’’’(0)

20 An example: power series (define (power-series g) (lambda (x) (stream-accum ((series-approx g) x)))) (define (sine-approx x) ((power-series sine-coeffs) x)) (define (cos-approx x) ((power-series cos-coeffs) x)) (define sine-coeffs (cons-stream 0 (cons-stream 1 (cons-stream 0 (cons-stream –1 sine-coeffs))))) (define cos-coeffs (stream-cdr sine-coeffs))

21 A real world example Suppose you wanted to build an automatic note taker, so you could catch up on your sleep! syllables words sentences phones Sound waves 10 interps/phone, 5 phones/word, 100 words/utterance  possible sentences of which only 1 or 2 make sense

22 A real world example Processing the normal way will generate huge numbers of trials, virtually all of which will be filtered out By decoupling the order of computation from the order of description (I.e. using streams) we can dramatically improve performance

23 Summary Lazy evaluation – control over evaluation models Convert entire language to normal order Upward compatible extension –lazy & lazy-memo parameter declarations Streams programming: a powerful way to structure and think about computation