为什么 (not? (pair? x) [...]) 比 ((pair? x) [...]) 更有利?

问题描述

在 SICP 的第 2 章,特别是 section 2.2. 及其在 Scheme wiki 上的相应解决方案中,我在处理树结构时经常看到相同的模式:

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

这些结构的第二行经常让我感到困惑。在任何其他语言中,我希望看到最后两个分支交换如下:

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

那为什么我在 Scheme 中没有看到呢?与交换分支和删除 (not? (pair? x) [...]) 相比,更喜欢 not? 有什么好处。

解决方法

案例通常以最小或最特殊的案例开始,以最大或最一般的案例结束。

如果有一棵树,那就是

  1. 叶子
  2. 所有其他树