I am a total newbie to clojure and trying to follow some tutorials basically. I have a question about defrecord
s.
Here is the thing that I am trying to do :
(defrecord somemap [key1 key2 key3 key4])
(defn give-me-map [m1 m2]
(somemap. m1 m2))
On the code above, i would like to have key3
and key4
as optional, so that i wont need to give values to them each time a create a somemap
object.
there is a similar question here, but it does the reverse of what i am trying to do here.
So the is it possible to define defrecord
with optional fields?
When you use (defrecord T [...])
, two factory functions are created: ->T
and map->T
.
The first uses the positional parameters as keys. The second applies an arbitrary map to the record.
You can keep key3
and key4
in the constructor and use map->somemap
.
(defrecord somemap [key1 key2 key3 key4])
(defn give-me-map
[key1 key2]
(map->somemap {:key1 key1 :key2 key2}))
Since records in Clojure implement the map interface, all fields except for the ones specified in the constructor are optional.
So, declaring your record with only key1
and key2
is correct: only key1
and key2
will be required in the constructor, but you can easily set key3
or key4
(or any other key, for that matter) by associng a value to them onto the record like any other map.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With