[racket] sicp exercise 2.20

From: Jos Koot (jos.koot at telefonica.net)
Date: Tue Jul 20 10:17:55 EDT 2010

Argument x is in the list anyway, so write (cons x ...) 

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

(define (my-filter pred? lst) 
 (cond 
   (null? lst) ...) 
   (pred? lst) ...) 
   (else ...))) 

If you already know function filter, you wont need my-filter. E,g: 

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

and so on, and so on. 

Jos 

> -----Original Message----- 
> From: users-bounces at racket-lang.org 
> [ <mailto:users-bounces at racket-lang.org>
mailto:users-bounces at racket-lang.org] On Behalf Of Matthias Felleisen 
> Sent: 20 July 2010 15:54 
> To: Martin DeMello 
> Cc: Racket Users 
> Subject: Re: [racket] sicp exercise 2.20 
> 
> 
> 
> 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)) 
> 
> 
> 
> 
> On Jul 20, 2010, at 9:36 AM, Martin DeMello wrote: 
> 
> > By way of a puzzle, I've been trying to solve SICP exercise 2.20 
> > ---------------------------- 
> > Using the (define (f x . args)) notation, 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) 
> > ---------------------------- 
> > using "straight recursion", that is, without using any `let` or 
> > `define` constructs. Still not managed to find the trick that will 
> > tack on the first argument as the head of the list. Anyone have a 
> > hint? 
> > 
> > martin 
> > _________________________________________________ 
> >  For list-related administrative tasks: 
> >   <http://lists.racket-lang.org/listinfo/users>
http://lists.racket-lang.org/listinfo/users 
> 
> _________________________________________________ 
>   For list-related administrative tasks: 
>    <http://lists.racket-lang.org/listinfo/users>
http://lists.racket-lang.org/listinfo/users 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.racket-lang.org/users/archive/attachments/20100720/49722f8a/attachment.html>

Posted on the users mailing list.