如何从值序列中创建记录 [英] How to make a record from a sequence of values
问题描述
我有一个简单的记录定义,例如
I have a simple record definition, for example
(defrecord User [name email place])
制作具有序列值的记录的最佳方法是什么
What is the best way to make a record having it's values in a sequence
(def my-values ["John" "john@example.com" "Dreamland"])
我希望像这样
(apply User. my-values)
但这行不通.我最终做了:
but that won't work. I ended up doing:
(defn make-user [v]
(User. (nth v 0) (nth v 1) (nth v 2)))
但我感觉有一些更好的方法可以实现这一目标...
But I'm sensing there is some better way for achieving this...
推荐答案
警告:仅适用于文字序列!(参见 Mihał 的评论)
Warning: works only for literal sequables! (see Mihał's comment)
试试这个宏:
(defmacro instantiate [klass values]
`(new ~klass ~@values))
如果你扩展它:
(macroexpand '(实例化用户 ["John" "john@example.com" "Dreamland"]))
你会得到这个:
(新用户John"john@example.com"Dreamland")
这基本上就是您所需要的.
which is basically what you need.
您可以使用它来实例化其他记录类型或 Java 类.基本上,这只是一个类构造函数,它接受一个参数序列而不是多个参数.
And you can use it for instantiating other record types, or Java classes. Basically, this is just a class constructor that takes a one sequence of parameters instead of many parameters.
这篇关于如何从值序列中创建记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!