Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ambiguity of `<<-` when defining it for `x < y <- z`

@g-grothendieck's answer to this question inspired me to play with some assignment functions such as ==<- or ><-.

See the following :

`><-` <- function(e1,e2,value) replace(e1, e1 > e2, value)
x <- c(5,15)
x > 10 <- 42
x
# [1]  5 42

I can also define it for < :

`<<-` <- function(e1, e2, value) replace(e1, e1 < e2, value)
x <- c(5,15)
x < 10 <- 42
x
# [1] 42 15

But the problem is that now the <<- operator is redefined and this doesn't work anymore :

x <<- "hello"

Error in replace(e1, which(e1 < e2), value) : argument "value" is missing, with no default

Interestingly x < y <- z calls <<- even when it's not been overwritten.

rm(`<<-`)
x < 10 <- 42

Error in x < 10 <- 42 : incorrect number of arguments to "<<-"

Would there be a way to keep the original behavior of <<- while still defining this custom behavior ?

like image 718
Moody_Mudskipper Avatar asked Dec 14 '18 13:12

Moody_Mudskipper


People also ask

What does ambiguous mean in math?

An expression is said to be ambiguous (or poorly defined) if its definition does not assign it a unique interpretation or value. An expression which is not ambiguous is said to be well-defined.

What type of ambiguity can be resolved by defining virtual base?

An ambiguity can arise when several paths exist to a class from the same base class. This means that a child class could have duplicate sets of members inherited from a single base class. This can be solved by using a virtual base class.

What is ambiguity in inheritance explain with example how it can be resolved?

Ambiguity in inheritance can be defined as when one class is derived for two or more base classes then there are chances that the base classes have functions with the same name. So it will confuse derived class to choose from similar name functions. To solve this ambiguity scope resolution operator is used “::”.


1 Answers

This seems to work :

`<<-` <- function(e1, e2, value){
  if(missing(value)) 
    eval.parent(substitute(.Primitive("<<-")(e1, e2)))
  else 
    replace(e1, e1 < e2,value)
}

x <- c(5,15)
x < 10 <- 42
x
# [1] 42 15

x <<- "hello"
x
# [1] "hello"
like image 69
Moody_Mudskipper Avatar answered Oct 07 '22 10:10

Moody_Mudskipper