Exercise 2.20 introduces Scheme's dotted-tail notation, which allows procedures like
listto take arbitrary numbers of arguments. This is known as a variadic function and is supported in many programming languages with different syntax. In Scheme, a parameter list that has a dot before the last parameter name indicates that when the procedure is called, the initial parameters will be treated as normal, but the final parameter's value will be a list of any remaining arguments.
The following examples are given:
(define (f x y . z) <body>)
(define (g . w) <body>)
fcan be called with two or more arguments. The body of the
fprocedure will refer to its first two parameters as x and y, and any remaining parameters passed to the procedure will be accessible through the list named z. The procedure
gcan be called with zero or more parameters. Any parameters will be in the list w.
This exercise asks us to use dotted-tail notation to write a procedure
same-paritythat takes one or more integer parameters 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)
We'll design a solution that uses an iterative helper procedure similar to the second
lengthexample given in section 2.2.1. The helper function will take as its parameters the list of items to iterate through and a variable to store the answer in as we iterate.
(define (same-parity a . z)
(define (iter items answer)
(if (null? items)
(iter (cdr items)
(if (= (remainder (car items) 2)
(remainder a 2))
(append answer (list (car items)))
(iter z (list a)))
same-parityprocedure takes a first parameter a, and any remaining parameters are accessed through the list z. Processing the list is delegated to the helper procedure
iter. The first thing
iterdoes is check the list to see if it's null. If so we just return the answer. If there are items left to process in the list,
iteris called again with the
cdrof the list as its first parameter and the answer as its second parameter. If the
carof the list has the same even-odd parity as the first argument to
same-parity, then it's appended to the answer.
> (same-parity 1 2 3 4 5 6 7)
(1 3 5 7)
> (same-parity 2 3 4 5 6 7)
(2 4 6)
For links to all of the SICP lecture notes and exercises that I've done so far, see The SICP Challenge.