6

尝试使用 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。

4

2 回答 2

11

试试这个:

 (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))))

我手边没有 REPL,但看起来像你想要的。

于 2009-01-18T14:20:16.280 回答
6

基本上,您写的内容可以重新格式化为:

(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) ; (= exp 0) => res
10   ;yep
user=> (fast-it-exp 2 2 2)  ; base => (- exp 1)
1     ;no...
user=> (fast-it-exp 1 1 1)  ; (odd? exp) => fast-it-exp
#<user$fast_it_exp__59 user$fast_it_exp__59@138c63>    ;huh?!
于 2009-01-20T11:01:07.320 回答