;; Some examples of programs using the from-to (or for) loop abstraction
(load-from-lib "from-to.ss")
;; compare - Program 9.5, pg. 272 -
(define vector-stretch-from-to
; 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)))
((from-to 0 (sub1 (vector-length res)))
(lambda (i)
(if (< i size)
(vector-set! res i (vector-ref vec i))
(vector-set! res i '()))))
res)))
;; compare - Program 9.7, pg. 272 -
(define vector-update-from-to
; 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)))
((from-to 0 (sub1 size))
(lambda (i)
(if (= i k)
(vector-set! res i val)
(vector-set! res i (vector-ref vec i)))
(set! i (add1 i))))
res))))
;; Basic question: do you see how these were derived from the original
;; programs? Do you see how they relate to the while versions?
;; How does this compare with vector-generator?
;; Can you write vector-genearator using from-to?
;; More examples can be had by writing from-to versions of:
; - Program 9.9, pg. 273 -
; - Program 9.11, pg. 274 -
; - Program 9.13, pg. 275 -
;; What use can you get from the following?
;; How does it compare with vector-generator?
;; Are there things you can do with it that you can't do with vector-generator?
(define vector-for-each
; TYPE: (-> ((vector T) (-> (number) void))
; void)
(lambda (vec what-to-do-for-i)
((from-to 0 (sub1 (vector-length vec)))
what-to-do-for-i)))