一元运算符超载:风险? [英] R unary operator overload: risks?

查看:84
本文介绍了一元运算符超载:风险?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my continuing quest to avoid using parentheses for some simple commands, I wrote up the following operator to create a new graphics window. My question is: am I at risk of "breaking" anything in R, other than the obvious inability to execute the "not" function on my variable "newdev"?

# 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函数,该函数使用!运算符,并且效果很好.因此,看起来可以安全地覆盖!".

I executed "!" = function(a){stop("'NOT' is used")} and executed the replications function, which uses the ! operator, and this worked fine. So it looks like it is safe to override "!".

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

Still you probably want to use classes, which you can do as follows:

# 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

这篇关于一元运算符超载:风险?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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