instead of modifying what a VARIABLE stands for, we can also change the contents of a record
(define a-rec (make-phone 'Bumpy 555666)) > (phone-number a-rec) 5556666 > (phone-number a-rec) 5556666 > (set-phone-number! a-rec 5557777) > (phone-number a-rec) 5557777
We can define programs now that modify a record on a list:
;; update : symbol number phone-list -> phone-list ;; Purpose: produce a list like a-pl, but with the ;; first record for a-name replaced with ;; (make-phone a-name a-number) (define (update a-name a-number a-pl) (cond ((empty? a-pl) (void)) (else (cond ((eq? (phone-name (first a-pl)) a-name) (cons (make-phone (phone-name (first a-pl)) a-number) (rest a-pl))) (else (cons (first a-pl) (update a-name a-number (rest a-pl)))))))) |
;; update! : symbol number phone-list -> void ;; Effect: modify the first record in phone-list ;; whose name is a-name so that it now contains ;; a-number (define (update! a-name a-number a-pl) (cond ((empty? a-pl) (void)) (else (cond ((eq? (phone-name (first a-pl)) a-name) (set-phone-number! (first a-pl) a-number)) (else (update! a-name a-number (rest a-pl))))))) |
Some expressions have an effect only. Similar to routines that draw stuff on the screen. Since we might want to combine those in a sequence, e.g. do do do do, we introduce a new construct:
We can now also define functions that modify several records on a list:
;; update : symbol number phone-list -> phone-list ;; Purpose: produce a list like a-pl, but with all ;; records for a-name replaced with ;; (make-phone a-name a-number) (define (update a-name a-number a-pl) (cond ((empty? a-pl) (void)) (else (cond ((eq? (phone-name (first a-pl)) a-name) (cons (make-phone (phone-name (first a-pl)) a-number) (update a-name a-number (rest a-pl)))) (else (cons (first a-pl) (update a-name a-number (rest a-pl)))))))) |
;; update! : symbol number phone-list -> void ;; Effect: modify the first record in phone-list ;; whose name is a-name so that it now contains ;; a-number (define (update! a-name a-number a-pl) (cond ((empty? a-pl) (void)) (else (cond ((eq? (phone-name (first a-pl)) a-name) (begin (set-phone-number! (first a-pl) a-number) (update! a-name a-number (rest a-pl)))) (else (update! a-name a-number (rest a-pl))))))) |
We could have used local for the left (functional) version and begin in a different manner for the right (destructive) one so that the natural recursions are not repeated textually.
Matthias Felleisen | This page was generated on Fri Apr 9 09:17:38 CDT 1999. |