;; Program 9.21, vector-generator is an imperative program. ;; This makes all the examples below a bit superfluous, as the imperative ;; programming has been done once and for all. Still, when you have to ;; write imperative programs in other languages, you won't be so lucky... ;; Program 9.23, list->vector is an imperative program. ;; (It could be called list->vector-imp.) ;; compare - Program 9.5, pg. 272 - (define vector-stretch-imp ; TYPE: vector, integer -> vector (lambda (vec new-size) ; ENSURES: result is a new copy of vec ; but having size new-size, ; result filled with () if bigger (let ((size (vector-length vec)) (res (make-vector new-size))) (letrec ((copy! ; TYPE: natural -> void (lambda (i) ; REQUIRES: i <= new-size ; MODIFIES: res ; EFFECT: make the elements of res starting at i ; be the elements of vec, padding extra with () (if (< i new-size) (begin (if (< i size) (vector-set! res i (vector-ref vec i)) (vector-set! res i '())) (copy! (add1 i))))))) (copy! 0) res)))) ;; compare - Program 9.7, pg. 272 - (define vector-update-imp ; TYPE: vector, integer, datum -> vector (lambda (vec k val) ; ENSURES: result is a new vector that ; has the same elements as vec, but ; with the the kth element replaced by ; val (let ((size (vector-length vec))) (let ((res (make-vector size))) (letrec ((update! ; TYPE: natural -> void (lambda (i) ; REQUIRES: i <= size ; MODIFIES: res ; EFFECT: make the elements of res starting at i ; have the same elements as vec, but ; with the the kth element replaced by val (if (< i size) (begin (if (= i k) (vector-set! res i val) (vector-set! res i (vector-ref vec i))) (update! (add1 i))))))) (update! 0) res))))) ;; Basic question: do you see how these were derived from the original ;; programs? ;; Can you see the advantage of letting vector-generator do the looping ;; for you? ;; More examples can be had by writing imperative versions of: ; - Program 9.9, pg. 273 - ; - Program 9.11, pg. 274 - ; - Program 9.13, pg. 275 -