问题描述
vctrs S3 vectors vignette 建议说,当不带参数调用时,用户友好的构造函数应该返回一个零长度的向量,如百分比()示例:
library("vctrs")
new_percent <- function(x = double()) {
vec_assert(x,double())
new_vctr(x,class = "vctrs_percent")
}
percent <- function(x = double()) {
x <- vec_cast(x,double())
new_percent(x)
}
percent()
#> <vctrs_percent[0]>
解释是这样可以更容易地用作原型,如vec_cast(x,percent())
。
但后来,rational() 示例并没有遵循这个建议:
library("vctrs")
library("zeallot")
new_rational <- function(n = integer(),d = integer()) {
vec_assert(n,ptype = integer())
vec_assert(d,ptype = integer())
new_rcrd(list(n = n,d = d),class = "vctrs_rational")
}
rational <- function(n,d) {
c(n,d) %<-% vec_cast_common(n,d,.to = integer())
c(n,d) %<-% vec_recycle_common(n,d)
new_rational(n,d)
}
rational()
#> Error in vec_cast_common(n,.to = integer()): argument "n" is missing,with no default
因此大概要调用rational 类作为原型,您会使用vec_cast(x,new_rational())
。
在实现我自己的基于 vctrs 的类时,我很难理解要使用哪种模式。一方面,percent() 返回一些作为原型的东西很有用,因为要允许用户使用理性做同样的事情,你必须导出内部构造函数 new_rational(),这似乎并不理想.另一方面,使用更复杂的构造函数来维护这种行为是很尴尬的,例如带有默认值和必需参数,并以用户不太容易理解的签名结束。
对于构造函数是否/何时可以不返回零长度向量,是否有任何建议?类是 vctr 还是 rcrd 有关系吗?如果你写了一个没有的,低级构造函数 new_x() 是否应该被导出并用作原型?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)