Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading subscript operator "["

I am trying to overload the subscript operator ("[") for a custom class I've created. I am trying to figure out how to deal with the following issues.

  • How can you figure out if the operator is on lhs or rhs ? i.e. a[x] = foo vs foo = a[x]
  • When subscripting the entire dimension like foo = a[,x] how can I identify the first parameter ?
  • When using a[seq(x,y)] it seems to be expanding the entire sequence. Is there an easy way to get the first, step and last values without expanding ?

EDIT: My first point has received multiple answers. In the process I've figured out the answer to the second one. You can use the "missing" function to figure out which parameters are present.

Here is a sample code:

setMethod("[", signature(x="myClass"),
          function(x, i, j, k, l) {
              if (missing(i)) { i = 0 }
              if (missing(j)) { j = 0 }
              if (missing(k)) { k = 0 }
              if (missing(l)) { l = 0 }
          })

I have accepted an answer to this question as point number 3 is of least priority to me.

like image 730
Pavan Yalamanchili Avatar asked Mar 14 '14 14:03

Pavan Yalamanchili


1 Answers

Discover the Generic so you know what you are aiming to implement :

getGeneric('[')
# standardGeneric for "[" defined from package "base"
# function (x, i, j, ..., drop = TRUE) 

And :

getGeneric('[<-')
# standardGeneric for "[<-" defined from package "base"
# function (x, i, j, ..., value) 

Then you implement it like this for example :

`[<-.foo` <-
function(x, i, j, value) 
{
       ....

}
like image 189
agstudy Avatar answered Oct 04 '22 20:10

agstudy