我正在嘗試撰寫一個執行以下操作的方案函式(取自 SICP):
練習 1.3。定義一個將三個數字作為引數并回傳兩個較大數字的平方和的程序。
這是我的嘗試:
(define (square-sum-larger a b c)
(cond ((and (< a b) (< a c))) ( (* b b) (* c c)))
(cond ((and (< b c) (< b a))) ( (* a a) (* c c)))
(cond ((and (< c a) (< c b))) ( (* b b) (* a a)))
)
當我將它輸入到 biwa 方案解釋??器中時,我得到以下資訊:
(square-sum-larger 4 5 6)
16
由于4小于5and ,不應該評估第一個條件,這意味著應該回傳and6的平方5和?6
uj5u.com熱心網友回復:
(define (square-sum-larger a b c)
(cond ((and (< a b) (< a c))) ( (* b b) (* c c))) ;; this is thrown away
(cond ((and (< b c) (< b a))) ( (* a a) (* c c))) ;; this is thrown away
(cond ((and (< c a) (< c b))) ( (* b b) (* a a)))
)
只有三個cond中的最后一個有用。前面的cond運算式沒有任何副作用,因為它們只執行計算,而不使用它們的值。Scheme 編譯器可以完全消除這些死代碼。
您可能想將所有子句組合成一個條件:
(define (square-sum-larger a b c)
(cond ((and (< a b) (< a c))) ( (* b b) (* c c))
((and (< b c) (< b a))) ( (* a a) (* c c))
((and (< c a) (< c b))) ( (* b b) (* a a))))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/470295.html
