Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R unary operator overload: risks?

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 
}
}
like image 351
Carl Witthoft Avatar asked Nov 02 '12 12:11

Carl Witthoft


People also ask

How many arguments a unary operator overloading function takes when it's a post fix unary operator?

When unary operators are overloaded through a member function, they do not take any explicit arguments. But when overloaded by a friend function, they take one argument.

Does R support operator overloading?

Does R not support operator overloading? @David Heffernan It does. But does not allow to redefine some object (functions, operators, constants). Check another question about it on stackoverflow.

How can you overload a unary operator?

You can overload a prefix or postfix unary operator by declaring a nonstatic member function taking no arguments, or by declaring a nonmember function taking one argument. If @ represents a unary operator, @x and x@ can both be interpreted as either x.


2 Answers

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
like image 196
bcmpinc Avatar answered Oct 04 '22 16:10

bcmpinc


with

makeActiveBinding

you can replace ls() by e.g LS w/o need of unary operators

like image 41
lebatsnok Avatar answered Oct 04 '22 15:10

lebatsnok