Following up on How to make a record from a sequence of values, how can you write a defrecord constructor call and assign the fields from a Map, leaving un-named fields nil?
(defrecord MyRecord [f1 f2 f3])
(assign-from-map MyRecord {:f1 "Huey" :f2 "Dewey"}) ; returns a new MyRecord
I imagine a macro could be written to do this.
You can simply
mergethe map into a record initialised withnils:Note that records are capable of holding values stored under extra keys in a map-like fashion.
The list of a record’s fields can be obtained using reflection:
The latter function returns a seq of strings:
__metaand__extmapare the fields used by Clojure records to hold metadata and to support the map functionality, respectively.You could write something like
and use it to create empty instances of record classes like so:
The fully qualified name is essential here. It’s going to work as long as the record class has been declared by the time any
empty-recordforms referring to it are compiled.If
empty-recordwas written as a function instead, one could have it expect an actual class as an argument (avoiding the “fully qualified” problem — you could name your class in whichever way is convenient in a given context), though at the cost of doing the reflection at runtime.