Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a record from a sequence of values

Tags:

clojure

I have a simple record definition, for example

(defrecord User [name email place])

What is the best way to make a record having it's values in a sequence

(def my-values ["John" "[email protected]" "Dreamland"])

I hoped for something like

(apply User. my-values)

but that won't work. I ended up doing:

(defn make-user [v]
  (User. (nth v 0) (nth v 1) (nth v 2)))

But I'm sensing there is some better way for achieving this...

like image 939
Nevena Avatar asked Dec 22 '10 22:12

Nevena


2 Answers

Warning: works only for literal sequables! (see Mihał's comment)

Try this macro:

(defmacro instantiate [klass values] 
        `(new ~klass ~@values))

If you expand it with:

(macroexpand '(instantiate User ["John" "[email protected]" "Dreamland"]))

you'll get this:

(new User "John" "[email protected]" "Dreamland")

which is basically what you need.

And you can use it for instantiating other record types, or Java classes. Basically, this is just a class constructor that takes a one sequence of parameters instead of many parameters.

like image 71
Goran Jovic Avatar answered Sep 19 '22 12:09

Goran Jovic


the defrecord function creates a compiled class with some immutable fields in it. it's not a proper clojure functions (ie: not a class that implements iFn). If you want to call it's constructor with apply (which expects an iFun) you need to wrap it in an anonymous function so apply will be able to digest it.

(apply #(User. %1 %2 %3 %4) my-values)

it's closer to what you started with though your approach of defining a constructor with a good descriptive name has its own charm :)

from the API:

Note that method bodies are
not closures, the local environment includes only the named fields,
and those fields can be accessed directy.
like image 34
Arthur Ulfeldt Avatar answered Sep 21 '22 12:09

Arthur Ulfeldt