gpt4 book ai didi

r - 一元运算符重载:风险?

转载 作者:行者123 更新时间:2023-12-03 13:37:11 28 4
gpt4 key购买 nike

为了避免在某些简单命令中使用括号,我编写了以下运算符以创建新的图形窗口。我的问题是:除了明显无法在我的变量“ newdev”上执行“ not”功能之外,我是否有“破坏” R中任何内容的风险?

# function to overload "!" for one purpose only
#this is adapted from the sos package code for "???", credited to Duncan Murdoch.
# Example of how to create a specialized unary operator that doesn't require
# parentheses for its argument. So far as I can tell,
#the only way to do this is to overload an existing function or
# operator which doesn't require parentheses. "?" and "!" meet this requirement.
`!` <- function (e1, e2) {
call <- match.call()
# match.call breaks out each callable function in argument list (which was "??foo" for the sos package "???",
# which allows topicExpr1 to become a list variable w/ callable function "!" (or "?" in sos)
original <- function() {
call[[1]]<-quote(base::`!`)
return(eval(call, parent.frame(2)))
}

# this does preclude my ever having an actual
# variable called "newdev" (or at least trying to create the actual NOT of it)
if(call[[2]] =='newdev') {
windows(4.5,4.5,restoreConsole=T)
}else{
return(original()) # do what "!" is supposed to do
}
}

最佳答案

我执行了"!" = function(a){stop("'NOT' is used")}并执行了replications函数,该函数使用!运算符,并且效果很好。因此,看起来可以安全地覆盖“!”。

您仍然可能想使用类,可以按照以下步骤进行操作:

# Create your object and set the class
A = 42
class(A) = c("my_class")

# override ! for my_class
"!.my_class" = function(v){
cat("Do wathever you want here. Argument =",v,"\n")
}

# Test ! on A
!A

关于r - 一元运算符重载:风险?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13195165/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com