Yes, definitely. Your version selects which form to evaluated once, at
compile time; the original selects a form every time the expansion is
evaluated.

user> (defn rand-num [] (rand-expr-mulit 1 2 3 4 5 6 7 8 9))
#'user/rand-num
user> (rand-num)
7
user> (rand-num)
7
user> (rand-num)
7
user> (rand-num)
7

Instead, you need to make sure the call to rand-int is in the code you
return, rather than in the logic the macro uses to decide what code to
return.

On Oct 24, 12:17 pm, Alan O'Donnell <alan.m.odonn...@gmail.com> wrote:
> 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

Reply via email to