如何从一系列值创建记录 [英] How to make a record from a sequence of values

查看:91
本文介绍了如何从一系列值创建记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的记录定义,例如

 (defrecord User [name email place])

创建具有序列中值的记录的最佳方法

 (def my-values [Johnjohn@example.comDreamland])

我希望像

 (apply User。my-values) 

但不起作用。我最后做:

 (defn make-user [v] 
nth v 1)(nth v 2)))

但我感觉有一些更好的方法

警告:只适用于文字序列!(请参阅Mihał的评论)



尝试此宏:

 (defmacro instantiate [klass values ] 
`(new〜klass〜@ values))



(macroexpand'(instantiate User [Johnjohn@example.comDreamland]))



您会得到:



john@example.comDreamland)



这是基本上你需要的。



您可以使用它来实例化其他记录类型或Java类。基本上,这只是一个类构造函数,它接受一个参数序列,而不是很多参数。


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"])

I hoped for something like

(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...

解决方案

Warning: works only for literal sequables! (see Mihał's comment)

Try this macro:

(defmacro instantiate [klass values] 
        `(new ~klass ~@values))

If you expand it with:

(macroexpand '(instantiate User ["John" "john@example.com" "Dreamland"]))

you'll get this:

(new User "John" "john@example.com" "Dreamland")

which is basically what you need.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆