Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to populate a Clojure record from a map?

Is there something like struct-map for records? If not, should I use a struct (the docs discourage use of structs)?

Maybe I am doing the wrong thing completely? I have a rather complex function which currently takes a map of options. I am trying to clarify what option values are acceptable/used (by replacing it with a record). And now I want to interface that to code that has this information in maps (and which contain a superset of the data in the record).

like image 601
andrew cooke Avatar asked May 25 '12 18:05

andrew cooke


1 Answers

It's not recommended to use records simply for "documentation" - plain old maps are more flexible, simpler, and easier. For documentation, you can merely add a docstring, or a comment, or create a function like (defn make-whatever [thing1 thing2]).

If you still want a record, you have a couple choices depending on whether you're using clojure version 1.3 or higher. If so, (defrecord Whatever ...) also defines a map->Whatever function, and a ->Whatever function that takes positional args. If not, you can write (into (Whatever. nil nil nil) some-map) (passing the right number of nils for the record type).

like image 122
amalloy Avatar answered Sep 23 '22 18:09

amalloy