一元运算符过载:风险?

时间:2012-11-02 12:22:41

标签: r operator-overloading

在我继续寻求避免在一些简单的命令中使用括号时,我编写了以下运算符来创建一个新的图形窗口。我的问题是:除了明显无法在我的变量“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 
}
}

2 个答案:

答案 0 :(得分:4)

我执行了"!" = 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

答案 1 :(得分:1)

makeActiveBinding

你可以用LS替换ls(),而不需要一元运算符