Skip to content
Prev 9833 / 63424 Next

Creating a vector class

(better late than never, hopefully--a few comments on this example)
Duncan Murdoch wrote:
It seems to say the right thing.  1) 'orientation' is a virtual class;
2) it extends 'vector', with no implication about the contents of either
class and, since 'vector' is also virtual, no need to supply functions
to coerce one to the other.
Yes to the second question.  To be honest, it probably doesn't make much
practical difference now, but it's the "right thing" to do, as I
understand your example.

The assertion is that for all 'orientation' objects, the vector
computations ( principally "[", "[[", and length) are meaningful & so 
'orientation' objects should inherit methods written for class "vector"
in terms of such computations.

In practice, there aren't many such methods, but there may be more
sometime.  Furthermore, there are many computations that are currently
not methods but that should conceptually be methods for "vector".  The
function rev, e.g.:

R> rev
function (x) 
if (length(x) > 0) x[length(x):1] else x
<environment: namespace:base>

This should really not be applied to non-vectors, and the definition is
in terms of vector computations.

A related point is that "[", etc. currently apply to objects for which
they are not conceptually meaningful.  Objects representing calls to
functions, for example.   (Both R and S-Plus allow it. R gets credit for
not allowing subsets of function objects, though, which S-Plus does
allow.)

R> ttt = quote(plot(x^2, y, pch ="+"))
R> ttt[2:3]
x^2(y)
R> rev(ttt)
"+"(y, x^2, plot)

!!


The behavior of [ is perhaps unlikely to be changed in base.  But if one
could optionally attach a more strict method-based package, I think it
would make sense to restrict "[" to classes that extend "vector" (which
includes, of course, the basic vector datatypes).
No, you don't need or want such a method.  In fact, it would be nice to
require that non-virtual classes extending 'orientation' DO have methods
for "[" (and, presumably, length()?  what about "[["?)

There is a simple technique considered for the Omegahat OOP package that
might be a useful addition in S4 methods as well.  We would introduce a
function, requireMethod, to force methods to be defined:

  requireMethod("[", "orientation")

The function is just like setMethod, except without a method definition,
and its effect is to generate an error for an object that dispatches
this combination of function and signature.  (Under the hood, it can
just call setMethod with a method that produces an appropriate error
message.)

The idea seems to convey what we want for virtual classes such as
'orientation'.  For example, by defining your method below for
"rotmatrix", you satisfy the requirement, and block dispatch of the
error method.
... the rest was discussed before