评估部分Clojure cond

时间:2009-01-18 14:08:10

标签: clojure functional-programming

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

2 个答案:

答案 0 :(得分: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,但看起来像你想要的。

答案 1 :(得分: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?!
相关问题