简体   繁体   English

如何将赋值运算符的重载与长度函数组合起作用?

[英]How does the overloading of the assignment operator in combination of the length function work?

How does the mutating implementation of length() actually work? length()的变异实现如何实际工作?

Example: Give a vector v , how does this set the length to 12? 示例:给出向量v ,如何将长度设置为12?

length(v) <- 12

Can I create my own function that can overload an operator in the same way? 我可以创建自己的功能,可以以相同的方式使操作员过载吗?

Example: Set every other element to 7 示例:将每个其他元素设置为7

everyOther(v) <- 7

Those assignment functions are just that, functions. 那些赋值函数就是函数。 They can be written in the following form (note the backticks - they must be used), where fname distinguishes the function name. 它们可以用以下形式编写(注意反引号 - 必须使用它们),其中fname区分函数名称。

`fname<-` <- function(x, value) { ... }

So your everyOther assignment function can be written as 所以你的everyOther赋值函数可以写成

`everyOther<-` <- function(x, value) {
    x[c(FALSE, TRUE)] <- value
    x
}

And we can use it just as we would length(x) <- value 我们可以像使用length(x) <- value一样使用它

v <- 1:20
everyOther(v) <- 7
v
# [1]  1  7  3  7  5  7  7  7  9  7 11  7 13  7 15  7 17  7 19  7

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM