# Filter a list of integers by parity

Exercise 2.20

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)


I wrote the following:

(define (same-parity n . l)
(define (even? n) (= (remainder n 2) 0))
(define (odd? n) (not (even? n)))
(define (rec n . l)
(define (include-and-go)
(cons (car l) (apply rec (cons n (cdr l)))))
(define (exclude-and-go)
(apply rec (cons n (cdr l))))
(if (null? l) null
(if (or (and (even? (car l))
(even? n))
(and (odd? (car l))
(odd? n)))
(include-and-go)
(exclude-and-go))))
(cons n (apply rec (cons n l))))


Is there a better way?

If one were to abstract out the filter function (named filt here), it would greatly simplify writing same-parity:

(define (filt test? lis)
(cond
((null? lis) lis)
((test? (car lis)) (cons (car lis) (filt test? (cdr lis))))
(else (filt test? (cdr lis)))))

(define (same-parity n . lis)
(filt (if (odd? n) odd? even?) lis))


The filter function is common enough that it is part of the Scheme standard and is appropriately named filter.

You should write a filter, its a standard part of the toolkit. its not to hard. Adeel's is good. It can also be written from fold if you'd like to.

Once you have filter, do the following.

(define (parity-match n . l)
(if (odd? n)
(filter odd? l)
(filter even? l)))