;=======================================================
;9.2
Here is a constructor that can be used to make arithmetic sequences
that start at a given point,
go up by a certain amount, and have a certain number of elements.
Once we've written that, we can
use it to create sequence-from-to (where the sequence
is one of consecutive numbers) and
sequence-from-to-with, where the sequence has a specified start,
stop, and length.
(define sequence-with-from-by (lambda (length start jump) (lambda (op) (cond ((equal? op 'empty-sequence?) (= length 0)) ((equal? op 'head) start) ((equal? op 'tail) (sequence-with-from-by (- length 1) (+ start jump) jump)) ((equal? op 'sequence-length) length) ((equal? op 'sequence-ref) (lambda (n) (+ start (* n jump)))) (else (error "illegal sequence operation" op))))))
> (sequence->list (sequence-with-from-by 5 17 3)) (17 20 23 26 29)
(define sequence-from-to (lambda (start stop) (sequence-with-from-by (+ 1 (- stop start)) start 1)))
> (sequence->list (sequence-from-to 17 39)) (17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39)
(define sequence-from-to-with (lambda (start stop length) (sequence-with-from-by length start (/ (- stop start)) (- length 1)))))
> (sequence->list (sequence-from-to-with 17 19 4)) (17 53/3 55/3 19) ;================================================= ;9.6The following constructor acts like the map procedure does for lists, except that
(define sequence-map (lambda (f seq) (lambda (op) (cond ((equal? op 'empty-sequence?) (empty-sequence? seq)) ((equal? op 'head) (f (head seq))) ((equal? op 'tail) (sequence-map f (tail seq))) ((equal? op 'sequence-length) (sequence-length seq)) ((equal? op 'sequence-ref) (lambda (n) (f (sequence-ref seq n)))) (else (error "illegal sequence operation" op))))))
> (sequence->list (sequence-map (lambda (x) (* x x)) (sequence-from-to 1 5))) (1 4 9 16 25);=================================================
(define family-name-last (lambda (names) ;assumes names is non-empty list of symbols (add-to-end (car names) (cdr names)))) (define creator (lambda (x) (cond ((movie? x)(movie-director (contents x))) ((book? x) (family-name-last (book-author (contents x)))) ((cd? x) (family-name-last (cd-artist (contents x)))) (else "unknown object in creator" x)))) ;===================================== ;9.21Assuming that sets are represented as predicates, here is the one selector we need for sets, and two new constructors.
(define element-of-set? (lambda (element set) (set element))) (define add-to-set (lambda (element set) (lambda (x) (or (equal? x element) (element-of-set? x set))))) (define union-set (lambda (s1 s2) (lambda (x) (or (element-of-set? x s1) (element-of-set? x s2)))))