home—info—lectures—exams—archive
lect04c
mutual recursion
A couple of notes:
- We may want to refer to the same sub-expression multiple times: E.g. in my draw-fire:
I started with
(define (draw-fire f scene)
(place-image (fire-intensity->img (fire-intensity f))
(fire-x f)
WORLD-HEIGHT
scene))
|
(Actually, I first had a field 'fire-y', but from my test cases,
I realized it never changed; use WORLD-HEIGHT instead.)
But this drew them below the screen, so:
(define (draw-fire f scene)
(place-image (fire-intensity->img (fire-intensity f))
(fire-x f)
(- WORLD-HEIGHT (image-height (fire-intensity->img (fire-intensity f))))
scene))
|
Still, this drew the fire's *center* (its pinhole) at the bottom of the screen.
(define (draw-fire f scene)
(place-image (fire-intensity->img (fire-intensity f))
(fire-x f)
(- WORLD-HEIGHT (- (image-height (fire-intensity->img (fire-intensity f)))
(pinhole-y (fire-intensity->img (fire-intensity f)))))
scene))
|
Whew!
How to avoid all this?
- Solution 1: write a helper function
(define (draw-fire f scene)
(draw-fire-helper f scene (fire-intensity->img (fire-intensity f)))
(define (draw-fire-helper f scene img)
(place-image img
(fire-x f)
(- WORLD-HEIGHT (- (image-height img)
(pinhole-y img)))
scene))
|
- Solution 2: looking at hw02soln, that code used 'let':
(define (draw-fire f scene)
(let ([img (fire-intensity->img (fire-intensity f))])
(place-image img
(fire-x f)
(- WORLD-HEIGHT (- (image-height img)
(pinhole-y img)))
scene)))
|
Q:
Suppose our language didn't have let.
How would we add it?
What if we wrote:
(define (draw-fire f scene)
(let ([f (make-fire 20 0.2)])
(place-image img
(fire-x f)
(- WORLD-HEIGHT (- (image-height img)
(pinhole-y img)))
scene)))
|
home—info—lectures—exams—archive