Chapter 2, Building Abstractions with Data
Section - 2.2 - Hierarchical Data and the Closure Property
Exercise 2.20
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#lang sicp
(define (same-parity x . rem-list)
(define (collect rem rs l)
(cond ((null? l)
(reverse rs)
)
((= (remainder (car l) 2) rem)
(collect rem (cons (car l) rs) (cdr l))
)
(else
(collect rem rs (cdr l))
)
)
)
(collect (remainder x 2) (list x) rem-list)
)
Note that we need to reverse the list in end to get the required result.
Here is another implementation which will not require reversing the list:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#lang sicp
(#%require (only racket/base error))
(define (same-parity x . rem-list)
(define (collect rem l)
(cond ((null? l)
nil
)
((= (remainder (car l) 2) rem)
(cons (car l) (collect rem (cdr l)))
)
(else
(collect rem (cdr l))
)
)
)
(cons x (collect (remainder x 2) rem-list))
)
Note that in first implementation collect
is iterative but in latter it is recursive.