評價

2009-01-18 158 views
6

試圖用Clojure的「計算機程序的結構與解釋:」做運動1.16(快速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 [email protected]> ;huh?! 

似乎cond表達式的「奇怪」部分返回一個函數,而不是評估。爲什麼? 我試過在謂詞後面放置括號,但這似乎是不正確的語法,這是我已經能夠想出最好的。 我正在使用Clojure的1146版。

+0

如果你想申請一個功能,那麼它很可能得有一個左括號到左本身。並且在你的最後一行沒有`(``fast-it-exp`前面,不僅在最後一行...... – 2015-03-05 19:13:49

回答

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方便,但看起來像你想要什麼。

+0

到底什麼,我認爲我嘗試了所有可能的圓括號排列,但似乎我錯過了右邊一個。這工作,非常感謝Philip。:) – 2009-01-18 14:27:12

+0

Ahum。爲什麼放置括號?如果你想在Lisp中調用一個函數,它必須是列表中的第一個元素;這就是Lisp語法的工作原理。 – Svante 2009-01-18 19:23:48

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 [email protected]> ;huh?!