2.20 Exercise 2.20
I found it easiest to define same-parity iteratively, using an iterative inner
procedure taking the first argument, the results list, and the rest of the numbers
to check as arguments.
(define (same-parity x . xs) | (define (is-same-parity? x y) | (= (remainder x 2) (remainder y 2))) | (define (same-parity-iter x l xs) | (cond ((null? xs) l) | ((is-same-parity? x (car xs)) | (same-parity-iter x (append l (list (car xs))) (cdr xs))) | (else | (same-parity-iter x l (cdr xs))))) | (same-parity-iter x nil xs)) |
|
One of the reasons I chose to do it this way is that same-parity expects
its arguments to be individual, rather than in the form of a list. I could
alternatively have used apply to get around this:
(define (same-parity x . xs) | (define (is-same-parity? x y) | (= (remainder x 2) (remainder y 2))) | (cond ((null? xs) nil) | ((is-same-parity? x (car xs)) | (cons (car xs) (apply same-parity (cons x (cdr xs))))) | (else | (apply same-parity (cons x (cdr xs)))))) |
|
However, although I have used it before, we technically don’t know apply
at this point in the book.