Controlling symbol generation in Clojure macros

Posted by mikera on Stack Overflow See other posts from Stack Overflow or by mikera
Published on 2010-05-15T12:37:51Z Indexed on 2010/05/15 12:44 UTC
Read the original article Hit count: 241

Filed under:
|
|
|

I'm trying (as a self-learning exercise) to create a Clojure macro that will generate code to apply a function to a sequence of integers and sum the result, e.g.

f(0) + f(1) + f(2) + f(3)

This is my attempt:

(defmacro testsum [func n] 
  `(fn [x#] (+ ~@( map (fn [i] `(~func x#)) (range n)))))

However something seems to go wrong with the x# gensym and I end up with two different versions of x and hence the function doesn't work:

(macroexpand '(testsum inc 3))

gives:

(fn* ([x__809__auto__] 
  (clojure.core/+ 
    (inc x__808__auto__) 
    (inc x__808__auto__) 
    (inc x__808__auto__))))

This is pretty much exactly what I want apart from the different 809 and 808 versions of x.....

What am I doing wrong? I thought that the auto gensym was meant to create a single unique symbol for exactly this kind of purpose? Is there a better way of doing this?

© Stack Overflow or respective owner

Related posts about clojure

Related posts about macro