SICP: Structure and Interpretation of Computer Programs (24)

20 Name: #!/usr/bin/anonymous : 2008-06-19 03:46 ID:Heaven

Looking at the scheme solution with the helper function which does the body of the work, I think I figured out my problem. The dotted-tail notation takes whatever arguments follow the preceding fixed arguments and makes a list out of them. If one were to throw a list at it, it would make a list out of that.

(define (f a . b) b)
(f 1 2 3)→(2 3)
(f 1 '(2 3))→((2 3))

and when one has lists of lists, car and cdr do weird things. i suppose this makes recursion with functions using dotted-tail notation problematic without a helper function.

Also, thank you for catching that I was returning empty lists rather than the list containing the first value. God only knows how long it would have taken me to figure out what was going wrong there on my own.

I finally came up with this. It probably isn't very idiomatic, but it seems to work.

; Exercise 2.20
(define (same-parity first-value . other-values)
(let ((match-parity (lambda (a b) (equal? (even? a) (even? b)))))
(letrec ((same-parity-helper (lambda (values)
(if (null? values) '()
(if (match-parity first-value (car values))
(cons (car values) (same-parity-helper (cdr values)))
(same-parity-helper (cdr values)))))))
(cons first-value (same-parity-helper other-values)))))
This thread has been closed. You cannot post in this thread any longer.