Note: this wiki is now retired and will no longer be updated!

The static final versions of the pages are left as a convenience for readers. Note that meta-pages such as "discussion," "history," etc., will not work.

SICP exercise 2.20

From Drewiki
Jump to: navigation, search

Problem

The procedures +, *, and list take arbitrary numbers of arguments. One way to define such procedures is to use define with dotted-tail notation. In a procedure definition, a parameter list that has a dot before the last parameter name indicates that, when the procedure is called, the initial parameters (if any) will have as values the initial arguments, as usual, but the final parameter's value will be a list of any remaining arguments. For instance, given the definition

(define (f x y . z) <body>)

the procedure f can be called with two or more arguments. If we evaluate

(f 1 2 3 4 5 6)

then in the body of f, x will be 1, y will be 2, and z will be the list (3 4 5 6). Given the definition

(define (g . w) <body>)

the procedure g can be called with zero or more arguments. If we evaluate

(g 1 2 3 4 5 6)

then in the body of g, w will be the list (1 2 3 4 5 6).

Use this notation to write a procedure same-parity that takes one or more integers and returns a list of all the arguments that have the same even-odd parity as the first argument. For example,

(same-parity 1 2 3 4 5 6 7)

Output:

(1 3 5 7)
(same-parity 2 3 4 5 6 7)

Output:

(2 4 6)


Solution

Here's one implementation:

(define nil (quote ()))
 
(define (even? n)
  (= (remainder n 2) 0))
 
(define (same-parity first . rest)
  (let ((first-is-even (even? first)))
    (define (same-parity-as-first? n)
      (let ((n-is-even (even? n)))
        (or (and first-is-even n-is-even)
            (and (not first-is-even) (not n-is-even)))))
    (define (build-list rest)
      (cond ((null? rest) nil)
            ((same-parity-as-first? (car rest))
             (cons (car rest) (build-list (cdr rest))))
            (else (build-list (cdr rest)))))
    (cons first (build-list rest))))

(Note that Scheme provides primitives that make the implementation much simpler, but the text hasn't introduced those primitives yet where this exercise occurs, so this solution doesn't use them.)

Test:

(same-parity 1)

Output:

(1)
(same-parity 2)

Output:

(2)
(same-parity 1 2 3 4 5 6 7)

Output:

(1 3 5 7)
(same-parity 2 3 4 5 6 7)

Output:

(2 4 6)
Personal tools