[racket] sicp exercise 2.20

From: David Van Horn (dvanhorn at ccs.neu.edu)
Date: Tue Jul 20 10:00:25 EDT 2010

On 7/20/10 9:54 AM, Matthias Felleisen wrote:
>
>
> Do you mean this?
>
> #lang racket
>
> (require rackunit)
>
> ;; Nat Nat *-> [Listof Nat]
> ;; which of the
> (define (same-parity x . xs)
> (cons x (filter (λ (o) (or (and (even? x) (even? o)) (and (odd? x) (odd?
> o)))) xs)))
>
> (check-equal? (same-parity 1 2 3 4 5 6 7) '(1 3 5 7))
> (check-equal? (same-parity 2 3 4 5 6 7) '(2 4 6))

A little more succinct and efficient:

(define (same-parity x . xs)
   (cons x (filter (if (even? x) even? odd?) xs)))

David


Posted on the users mailing list.