假设您只有带有 '* 和 '+ 作为运算符的二进制表达式,那么使用要简化的表达式的递归下降来编码代数的基本规则就很容易了。如此:
(define (simplify exp)
(cond ((number? exp) exp)
((symbol? exp) exp)
((list? exp)
(assert (= 3 (length exp)))
(let ((operator (list-ref exp 0))
(operand-1 (simplify (list-ref exp 1))) ; recurse
(operand-2 (simplify (list-ref exp 2)))) ; recurse
(case operator
((+)
(cond ((and (number? operand-1) (= 0 operand-1)) operand-2)
((and (number? operand-2) (= 0 operand-2)) operand-1)
((and (number? operand-1) (number? operand-2))
(+ operand-1 operand-2))
(else `(,operator ,operand-1 ,operand-2))))
((*)
(cond ((and (number? operand-1) (= 0 operand-1)) 0)
((and (number? operand-2) (= 0 operand-2)) 0)
((and (number? operand-1) (= 1 operand-1)) operand-2)
((and (number? operand-2) (= 1 operand-2)) operand-1)
((and (number? operand-1) (number? operand-2))
(* operand-1 operand-2))
(else `(,operator ,operand-1 ,operand-2))))
(else 'unknown-operator))))
(else 'unknown-expression)))
这仅对表达式执行一次传递。通常,您希望执行通行证,直到结果不变。