假設你剛剛有二元表達式「*和」 +爲運營商來說,很容易編碼代數的基本規則,並簡化表達式的遞歸下降。像這樣:
(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)))
這僅執行一個傳過來的表達。通常你會想要執行通過,直到結果沒有改變。
是否應該是?x? – leppie 2013-03-28 13:49:33
這取決於上下文。我從源代碼中逐字引用,有時它們使用'?s','?n'等作爲變量名,而不是'?x' – 2013-03-28 13:52:26