# Was this an idiomatic and prudent way to extend R's matrix multiplication syntax? Should I have used R's object system?

After reading one too many Lisp books, I decided to try extending R's syntax. My goal was to implement repeated matrix multiplication in a way such that I could write matrix%^%n to produce the result from multiplying matrix by itself n times (where n is a natural number). I produced the following working code that gives the expected outputs, but found it unsatisfactory.

%^%<-function(squareMat,exponent)
{
stopifnot(is.matrix(squareMat),is.numeric(exponent),exponent%%1==0)
out<-diag(nrow = nrow(squareMat))
for(i in seq_len(exponent)){out<-squareMat%*%out}
out
}
testMatrix<-matrix(c(0,10,20,30),2,2)
lapply(0:3,function(k) testMatrix%^%k)#tests


For the purposes of this question, I'm happy to ignore the contents of my for loop. I know that it's not optimised. What I'm more interested in investigating is if this was a prudent way to extend R's syntax. I have listed my objection to my code below. If they are valid, how can they be addressed?

1. The method for checking if exponent is an integer is pathetic. I don't think that doing better is possible, but I would dearly love to be proven wrong.
2. My strongest objection is that I believe that this problem calls for an S3 or S4 solution, but I do not believe that one is possible. isS4(testMatrix) tells me that matrices are not S4 objects, ruling that out. S3 might be possible, but I'm unsure if this will make problem #1 even worse (because S3 is not very strict on types) or requiring risky hacking of the matrix type.
3. Because of problem #1, stopifnot does not throw useful error messages.
4. The job of throwing errors regarding the multiplication is delegated to %*%. I'm OK with that, but I don't know if I should be.
5. Again, ignoring the content of the for loop, was for actually the right thing to use? Is there something like an apply family function for "the index of my loop doesn't actually matter, I just want to run this code seq_len(exponent) times"?
• When I tagged this yesterday, we had an S3 tag. It's now being redirected to some Amazon stuff. I don't know why this is. Is there a better tag for R's OOP? Jan 26 at 14:46