[Rd] : Operator overloading for custom classes
Peter Ruckdeschel
peter.ruckdeschel at web.de
Fri Mar 26 23:16:08 CET 2010
>
> I need some help to get some of the object orientation, specifically the
> methods that overload the basic arithmetic operations, from sample C++
> code to R. I don't have experience with such advanced language features
> inside of R. So I was wondering if some of you could help me out in this
> regard.
>
> I have written a simple demonstration of a forward mode automatic
> differentiator in C++ and it is currently hosted on github:
> http://github.com/quantumelixir/ad-demo/blob/master/simple.cpp. It uses
> simple operator overloading techniques to modify the meaning of the
> basic arithmetic operations (+, -, *, /) for the "derivative" type Dual
> number class that I have defined. Could you show me how this could be
> equivalently done in R? I want to know how to define custom classes and
> define the meaning of arithmetic for them.
>
> I had checked for operator overloading in R but could only find the
> equivalence of a + b and '+'(a, b) in the R language definition. Could
> you show how I could extend the simple object oriented-ness in the C++
> code neatly to R?
>
> Thanks a bunch!
> Chillu
>
> [[alternative HTML version deleted]]
>
First of all you should read about S4 classes, in particular
the books of John Chambers should be helpful ;-)
(others on this list might point you to further sources).
The key is to define S4 classes for your operands
[i.e; if I have understood correctly you would implement
your Dual number class as S4 class].
Then you would define new methods by setMethod().
Not sure whether this gives you the indications you look for,
but we have overloaded arithmetic operators to act on distribution
classes in package distr (cf CRAN, developped under r-forge).
You might want to look at the code in NormalDistribution.R resp.
ContDistribution.R
HTH Peter Ruckdeschel
More information about the R-devel
mailing list