6.001 Recitation – April 11,
2003
RI: Konrad
Tollmar
• Eval / Apply revisit
• Lazy evaluation
1. Break
Implement a special-form break that allow you to stop your code and inspect the environment
2. Derived expressions
Make cond a derived expression of the special form if, i.e. convert the cond expression to an if expression and evalute it as such.
(cond (<pred1> <actions-1>)
(<pred2> <actions-2>)
...
(<predn> <actions-n>)
(else <actions))
rewritten
to
(if <pred1>
(begin <actions-1>)
(if <pred2>
(begin <actions-2>)
...
(if <predn>
(begin <actions-n>)
(begin <actions>))))
Complete
the procedures below, including cond->if, that converts a cond expression into an if expression.
(define (conditional? exp) (tagged-list? exp <<2A>> ))
(define (cond-clauses conditional) (cdr conditional))
(define (cond-no-clauses? clauses) (null? clauses))
(define (cond-first-clause clauses) (car clauses))
(define (cond-rest-clause clauses) (cdr clauses))
(define (cond-else-clause? clause) (eq? (cond-predicate clause) 'else))
(define (cond-predicate clause) (car clause)
(define (cond-actions clause) (cdr clause))
(define (cond->if cond-exp)
(define (expand clauses)
(cond ((cond-else-clause? (cond-first-clause clauses))
(if (cond-no-clauses? (cond-rest-clauses clauses))
(sequence->begin
( << 2B >> )
(error "ELSE clause isn't last")))
(else
(make-if ( << 2C >> )
(sequence->begin
( << 2D >> ))
(expand ( << 2E >> )))))))
(expand (cond-clauses cond-exp)))
3. Normal vers
Applicative Order
What
happen if we evaluate:
(define (try a b)
(if
(= a 0) 1 b))
(try
0 (/ 1 0))
(try 0 (pi-to-this-many-digits 10000000))
In Normal vers Applicative Order
?
4. Normal order side-effects
(define count 0)
(define p
( (begin
(set! count (+ count 1))
(* x 3)) lazy-memo))
(define x 5)
3. Test Normal vers Applicative Order
Write a function normal-order? That returns #t if the language is normal order and #f if the language is applicative order.
4. Lazy Lists
What will happen when we evaluate the following?
(define ones (cons 1 ones))
How can we use this to produce sequences of number?
5. Create Infinite
Streams
Show how we could create a stream of integers in an alternative way, given the stream ones (1 1 1 1 ….) and the procedure add-streams.
(define
ones (cons-streams 1 ones))
(define
(add-streams s1 s2)
(cons-stream (+ (stream-car s1) (stream-car
s2))
(add-streams (stream-cdr s1)
(stream-cdr s2)))))
6. Define Fibonacci
numbers with stream.
Write a procedure, (fibs), that returns a stream of Fibonacci numbers. The Fibonacci series goes
(1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 ...)
It starts with two 1's, then each successive value is the sum of the previous two.