Quick Practical Clojure macro question
Hi everyone, I'm working my way through Practical Clojure's macro chapter, and I'd like to check my understanding about one of the examples. The book discusses writing a macro to randomly evaluate a form out of a list of forms--essentially a cond that randomly selects which branch to evaluate. The book's version looks like this: (defmacro rand-expr-multi [ exprs] `(let [ct# ~(count exprs)] (case (rand-int ct#) ~@(interleave (range (count exprs)) exprs My version looks like this: (defmacro rand-expr-mulit [ exprs] (let [n (rand-int (count exprs))] (nth exprs n))) Is there any difference between the two? I'm a little shaky on macro expansion-time vs run-time, hygiene, etc. -- You received this message because you are subscribed to the Google Groups Clojure group. To post to this group, send email to clojure@googlegroups.com Note that posts from new members are moderated - please be patient with your first post. To unsubscribe from this group, send email to clojure+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/clojure?hl=en
SICP sqrt function generates unexpected NullPointerException
Hi everyone, I've encountered an unexpected NullPointerException while translating some early SICP code into Clojure 1.3.0. In particular, I'm implementing the iterative sqrt procedure from section 1.1.7. Here's my code: (defn square [x] (* x x)) (defn abs [x] (cond ( x 0) (- x) :else x)) (defn average [x y] (/ (+ x y) 2)) (defn sqrt ([x] (sqrt 1.0 x)) ([guess x] (letfn [(good-enough? [guess] ( (abs (- (square guess) x)) 0.001)) (improve [guess] (average guess (/ x guess)))] (if (good-enough? guess) guess (recur (improve guess) x) Rather mysteriously, this works correctly for inputs less than roughly (square 2718.259...); anything larger throws a NullPointerException clojure.lang.Numbers.lt (Numbers.java:3693). Any ideas? -- You received this message because you are subscribed to the Google Groups Clojure group. To post to this group, send email to clojure@googlegroups.com Note that posts from new members are moderated - please be patient with your first post. To unsubscribe from this group, send email to clojure+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/clojure?hl=en
Re: SICP sqrt function generates unexpected NullPointerException
Armando, I get the same behavior as you with Clojure 1.2.1. But if I lein dep Clojure 1.3.0, I'm back to NullPointerExceptions. -- You received this message because you are subscribed to the Google Groups Clojure group. To post to this group, send email to clojure@googlegroups.com Note that posts from new members are moderated - please be patient with your first post. To unsubscribe from this group, send email to clojure+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/clojure?hl=en