尝试使用 Clojure 在“计算机程序的结构和解释”中做练习 1.16(fast-exp 的迭代版本)我想出了这个:
(defn fast-it-exp [base exp res]
(cond (= exp 0) res
(odd? exp) fast-it-exp base (- exp 1) (* base res)
:else fast-it-exp base (/ exp 2) (* base base res)))
尝试一下:
user=> (fast-it-exp 0 0 10)
10 ;yep
user=> (fast-it-exp 2 2 2)
1 ;no...
user=> (fast-it-exp 1 1 1)
#<user$fast_it_exp__59 user$fast_it_exp__59@138c63> ;huh?!
似乎 cond 表达式的“奇数”部分返回一个函数而不是评估。为什么?我试过在谓词后面的表达式周围加上括号,但这似乎是不正确的语法,这是我能想到的最好的。我正在使用 Clojure 的 rev 1146。