简体   繁体   English

如何从地图填充Clojure记录?

[英]How to populate a Clojure record from a map?

Is there something like struct-map for records? 是否有类似struct-map的记录? 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). 现在,我想将其与映射中具有此信息的代码进行接口(并且在记录中包含数据的超集)。

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]) . 对于文档,您仅可以添加文档字符串或注释,或创建类似(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. 如果仍然需要记录,则可以选择两种方式,具体取决于您使用的是Clojure 1.3版还是更高版本。 If so, (defrecord Whatever ...) also defines a map->Whatever function, and a ->Whatever function that takes positional args. 如果是这样,则(defrecord Whatever ...)还定义了map->Whatever函数,以及一个带有位置参数的->Whatever函数。 If not, you can write (into (Whatever. nil nil nil) some-map) (passing the right number of nils for the record type). 如果没有,则可以写入(into (Whatever. nil nil nil) some-map) 。nil (into (Whatever. nil nil nil) some-map) (为记录类型传递正确数量的nil)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM