Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

defrecord with optional keys

Tags:

clojure

I am a total newbie to clojure and trying to follow some tutorials basically. I have a question about defrecords.

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?

like image 907
denizdurmus Avatar asked Nov 15 '12 05:11

denizdurmus


2 Answers

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}))
like image 104
kotarak Avatar answered Nov 10 '22 23:11

kotarak


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.

like image 34
Jordan Lewis Avatar answered Nov 11 '22 01:11

Jordan Lewis