On Wed, Aug 11, 2010 at 1:03 PM, Shantanu Kumar
<kumar.shant...@gmail.com> wrote:
> I tried to assign a data type to a var and then instantiate it using
> the var, but it doesn't seem to work:
>
> user=> (defrecord X [])
> user.X
>
> user=> (X.)
> #:user.X{}
>
> user=> X
> user.X
>
> user=> (def hey X)
> #'user/hey
>
> user=> (hey.)
> java.lang.IllegalArgumentException: Unable to resolve classname: hey
> (NO_SOURCE_FILE:59)
>
> user=> (new X)
> #:user.X{}
>
> user=> (new hey)
> java.lang.IllegalArgumentException: Unable to resolve classname: hey
> (NO_SOURCE_FILE:61)
>
> user=> (apply new hey)
> java.lang.Exception: Unable to resolve symbol: new in this context
> (NO_SOURCE_FILE:62)
>
> Can anybody help me understand how to accomplish this when using the
> var? This will give me a generic way to instantiate the type when I
> know the parameters.

The problem is that "X." is a special form, so when you say
"hey." it's looking for a class literally named "hey".

The best solution is to provide for each defrecord a real Clojure
function to act as a factory.  There are several places that such
a function can be helpful, and in real-world code you almost
always run into at least one of them:

    (defrecord X [])
    (defn new-X [] (X.))

    (def hey new-X)

    (hey)
        ;=> #:user.X{}

If you don't like the idea of a named factory function for each
record type, you can create an anonymous fn on the fly instead:

    (defrecord X [])

    (def hey #(X.))

    (hey)
        ;=> #:user.X{}

Note in either case when you define the factory fn (named or
not), you need to specify all the args the real record
constructor requires.

--Chouser
http://joyofclojure.com/

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