【发布时间】:2011-04-20 21:06:38
【问题描述】:
clojure 中的defrecord 允许使用自定义字段定义简单的数据容器。
例如
user=> (defrecord Book [author title ISBN])
user.Book
生成的最小构造函数只接受位置参数,没有其他功能,例如字段默认值、字段验证等。
user=> (Book. "J.R.R Tolkien" "The Lord of the Rings" 9780618517657)
#:user.Book{:author "J.R.R Tolkien", :title "The Lord of the Rings", :ISBN 9780618517657}
总是可以编写包装默认构造函数的函数来获得更复杂的构造语义——使用关键字参数、提供默认值等等。
这似乎是宏提供扩展语义的理想方案。人们为更丰富的defrecord 构造编写和/或推荐了哪些宏?
【问题讨论】:
-
我应该指出,defrecord 在如何与 Clojure/Java 生态系统一起工作方面还有很多用处,上面的“简单数据容器”并不意味着初级,恰恰相反.
-
需要说明的是,从clojure 1.3.0开始,你可以做到
(map->Book {:author "J.R.R Tolkien", :title "The Lord of the Rings", :ISBN 9780618517657)或者#user.Book{:author "J.R.R Tolkien", :title "The Lord of the Rings", :ISBN 9780618517657} -
有关 Claude 指出的功能的文档,请参阅:dev.clojure.org/display/design/defrecord+improvements
标签: macros constructor clojure record