推荐使用宏向 Clojure 的 defrecord 构造函数添加功能吗?
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
in clojure allows for defining simple data containers with custom fields.
e.g.
user=> (defrecord Book [author title ISBN])
user.Book
The minimal constructor that results takes only positional arguments with no additional functionality such as defaulting of fields, field validation etc.
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}
It is always possible to write functions wrapping the default constructor to get more complex construction semantics - using keyword arguments, supplying defaults and so on.
This seems like the ideal scenario for a macro to provide expanded semantics. What macros have people written and/or recommend for richer defrecord
construction?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
支持完整和部分记录构造函数以及支持可评估打印和 pprint 表单的示例:
David 是我的一位同事,我们在项目中广泛使用这个 defrecord2。我认为这样的东西确实应该成为 Clojure 核心的一部分(当然细节可能会有很大差异)。
我们发现重要的事情是:
Examples of support for full and partial record constructor functions and support for eval-able print and pprint forms:
David is a colleague of mine and we are using this defrecord2 extensively in our project. I think something like this should really be part of Clojure core (details might vary considerably of course).
The things we've found to be important are:
这是一个定义记录的具有默认值和不变量。它创建一个可以使用关键字参数来设置字段值的构造函数。
就像我说的......不变量:
但它们只有在 Trammel 的上下文中才有意义。
Here is one that defines a record with default values and invariants. It creates a ctor that can take keyword args to set the values of the fields.
And like I said... invariants:
But they only make sense in the context of Trammel.
这是一种方法: http://david-mcneil.com/post/765563763/增强型 Clojure 记录
Here is one approach: http://david-mcneil.com/post/765563763/enhanced-clojure-records