SICP: Structure and Interpretation of Computer Programs (24)

21 Name: #!/usr/bin/anonymous : 2008-06-19 04:39 ID:Heaven

>>20
It's kinda ugly.
The key here is not to write it in pure scheme with a helper function.
The key is to find the pattern, and factor the code.
What you want to do is keep all the elements of a sequence that satisfy a condition.

It's easy to write this as:

(define (filter cond lst)
(define (filter-help old new)
(if (null? old) new
(filter-help (cdr old) (if (cond (car old)) (cons (car old) new) new))))
(reverse (filter-help lst '())))

some examples:

(filter (lambda (x) x) '(1 2 () 3 () 4 5)) ==> (1 2 3 4 5)
(filter (lambda (x) (odd? x)) '(1 2 3 4 5)) ==> (1 3 5)
(filter (lambda (x) (not (null? x))) '( () () (1 2 3) () (4 5))) ==> ((1 2 3) (4 5)

then it's easy to write same-parity as

(define (same-parity fst . rest)
(cons fst (filter (if (odd? fst) odd? even?) rest)))

A lot of SICP's beginning exercises are easy to write with common lisp. That's because common lisp provides the functions to do it. Because scheme is used in the book, there isn't an obvious function to use, so the book expects you to find the patterns and write the appropriate function.
That's how experts write maintainable and portable code, and that's how they design protocols. By finding the key patterns.
Imagine patterns as the stairway to the new level of abstraction.
Have you ever played pokemon? Remember that fucking house in blue/red that you get the masterball? Remember how frustrating it was to take the wrong stairway?
That's how it feels when you spot the wrong pattern, so you better find them right patterns.

This thread has been closed. You cannot post in this thread any longer.