Search code examples
schemelispsicp

Why is (not? (pair? x) [...]) beneficial over ((pair? x) [...])?


Throughout chapter 2 of SICP and particularly section 2.2. and its corresponding solutions on the Scheme wiki, I am regularly seeing the same pattern when dealing with tree structures:

(cond ((null? tree) nil) 
      ((not (pair? tree)) (foo tree)) 
      (else (cons (bar (car tree)) 
                  (bar (cdr tree)))))

The second line of these structures are a frequent source of confusion for me. In any other language, I'd expect to see the final two branches swapped as follows:

(cond ((null? tree) nil)  
      ((pair? tree) (cons (bar (car tree)) 
                          (bar (cdr tree))))
      (else (foo tree))) 

So why am I not seeing that in Scheme? Is there some benefit to preferring (not? (pair? x) [...]) over swapping the branches and removing the not?.


Solution

  • Cases usually start with the smallest or most special case and and end with the largest or most general.

    With a tree, that would be

    1. Empty
    2. Leaf
    3. All other trees