Evaluation of the Clojure cond part

Trying to complete exercise 1.16 (iterative version of fast-exp) in "Structure and interpretation of computer programs" using Clojure I came up with the following:

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

Attempt:

 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?! 

It seems that the "odd" part of the cond expression returns a function instead of an evaluation. What for? I tried putting parentheses around the expressions after the predicates, but this seems to be the wrong syntax, this is the best I could come up with. I am using rev 1146 from Clojure.

+6
functional-programming clojure
source share
2 answers

Try the following:

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

I do not have REPL, but it looks the way you want.

+11
source share

Basically, what you wrote can be reformatted as:

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

So:

 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?! 
+6
source share

All Articles