2011-09-27

SICP Exercise 2.20: Parity Lists

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)
(1 3 5 7)
> (same-parity 2 3 4 5 6 7)
(2 4 6)

Okay, so if we our definition of same-parity takes the following form:
(define (same-parity i . l) <body>)
...then this allows us to implement a procedure in the following manner:
  1. Figure out whether i is even or odd.
  2. Recurse through l and filter it to those elements with the same parity as i.
  3. Finally, use cons to prepend i onto the head of the filtered list.
The second step here is the most complex. We can implement this as an internal recursive procedure that takes an indication of the parity to filter for and the remainder of the list to filter and has three cases:
  1. If the list is empty then return an empty list.
  2. If the head of the list has the parity we're looking for then we cons the head onto the results of filtering the tail of the list via a recursive call and return that.
  3. Otherwise we want to filter the head of the list, so we just return the results of filtering the tail of the list via a recursive call and return that.
Here's my implementation:
(define (same-parity i . l)
  (define (filter-list filter-to-even ll)
    (cond ((null? ll) nil)
          ((equal? filter-to-even (even? (car ll)))
              (cons (car ll) (filter-list filter-to-even (cdr ll))))
          (else (filter-list filter-to-even (cdr ll)))))
  (cons i (filter-list (even? i) l)))
...and here's the results of running it:
> (same-parity 1 2 3 4 5 6 7)
(1 3 5 7)
> (same-parity 2 3 4 5 6 7)
(2 4 6)

No comments:

Post a Comment