Your code
Here's a refactoring proposal, keeping with your basic structure:
(define (same-parity g . w)
(define filter-predicate? (if (odd? g) odd? even?))
(define (iter-parity items)
(if (null? items)
'()
(if (filter-predicate? (car items))
(cons (car items) (iter-parity (cdr items)))
(iter-parity (cdr items)))))
(cons g (iter-parity w)))
Note that it is more idiomatic
- to use the procedures
odd?
andeven?
rather thanremainder
- to have as a base case when the list is empty, not when it has only one item (in your code this clearly avoids repetition as a positive effect).
Also, since there is a built-in filter
procedure in Scheme, you could express it as follows:
(define (same-parity g . w)
(cons g (filter (if (odd? g) odd? even?) w)))
Your question
As for your question regarding (same-parity (list 1 2 3 4))
: you need either (as described in your specification) use your procedure like so
(same-parity 1 2 3 4)
or to use apply
here:
> (apply same-parity (list 1 2 3 4))
'(1 3)
because apply
will transform (same-parity (list 1 2 3 4))
(1 parameter, a list) into (same-parity 1 2 3 4)
(4 parameters).