clojure defrecord named parameters?
Does defrecord support named parameters? i.e. if if I have something like this:
(defrecord Person [name age])
Can I do something like this:
(Person. {:age 99 :name "bob"})
(Person. :age 99 :name "bob")
The only thing I see by googling is stuf开发者_C百科f like this:
(Person. "bob" 99)
Which seems less clear...
Not built in, but you could use something like:
(defmulti make-instance (fn [class & rest] class))
(defmacro defrecord* [record-name fields]
`(do
(defrecord ~record-name ~fields)
(defmethod make-instance (quote ~record-name) [_# & {:keys ~fields}]
(new ~record-name ~@fields))))
(defrecord* Person [name age])
(make-instance 'Person :age 99 :name "bob")
Not sure how suitable that would be for what you want.
It looks like this is not yet supported by clojure?
http://david-mcneil.com/post/765563763/enhanced-clojure-records
Not currently.
But you can just forget about naming the parameters and use an extension map:
(defrecord Person [])
(Person. nil {:age 99 :name "bob"})
I personally find this to be the easiest way to use records when you have large numbers of possible fields.
精彩评论