The compiler, and the macro system, work with data structures like
lists and vectors, which have already been parsed from characters by
the reader.
If you want the field names as well, it's not hard to change my
original answer:
(defmacro defrecord-withstr [name include? columns fields]
(let [displayed (if include? columns (remove (set columns)
fields))]
`(defrecord ~name ~fields
Object
(toString [_#]
(clojure.string/join " " [~@(mapcat (fn [field]
[(keyword field)
field])
displayed)])))))
user> (macroexpand-1 '(defrecord-withstr Test true [a b] [a b c d]))
(clojure.core/defrecord Test [a b c d] java.lang.Object (user/toString
[___2278__auto__] (clojure.string/join " " [:a a :b b])))
user> (defrecord-withstr Test true [a b] [a b c d])
user.Test
user> (def tt (Test. 1 2 3 4))
#'user/tt
user> tt
#:user.Test{:a 1, :b 2, :c 3, :d 4}
user> (str tt)
":a 1 :b 2"
On Oct 18, 9:33 pm, Dusan <[email protected]> wrote:
> Thank you for claridying this. I thought it was much simpler, that the
> macro output is the text which is the input of the function at compile
> time.
> I will definitely need some time to understrand how the reader works.
> Btw. your version of macro doesn't give the key-value pairs, just the
> values...
>
> On Oct 18, 8:25 pm, "Marshall T. Vandegrift" <[email protected]>
> wrote:
>
>
>
>
>
>
>
> > Dusan <[email protected]> writes:
> > > (symbol(str "(str (:" % " " vv "))"))
>
> > This expression is the (immediate) problem child. You are producing a
> > symbol which contains literal space and parenthesis characters embedded
> > in it. When you print out the macro-expansion, it looks fine, but the
> > actual forms generated contain that weird symbol instead of the expected
> > list structure.
>
> > You do have other problems though --
>
> > - A symbol prefixed with a colon is just a symbol prefixed with a
> > colon, not a keyword. You need to use the `keyword' function to
> > create a keyword from a symbol or string.
>
> > - Instead of calling `gensym' directly, it's probably easier to just
> > use autogensyms in this sort of situation.
>
> > For fun, here's a (hopefully) more idiomatic version:
>
> > (defmacro defrecord-withstr [name fields columns include?]
> > (let [displayed (->> (if include? columns (remove (set columns) fields))
> > (map keyword))]
> > `(defrecord ~name ~fields
> > Object
> > (toString [this#]
> > (str/join " " ((juxt ~@displayed) this#))))))
>
> > -Marshall
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to [email protected]
Note that posts from new members are moderated - please be patient with your
first post.
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en