S4 Classes and Methods
Lesson 34 of 48 in Coddy's R for C Developers course.
C instance-like helpers receive explicit struct pointers, and dispatch requires a separate function-pointer or tag convention. R S4 declares slots with setClass and selects external methods by generic signatures. Wrap top-level setGeneric in invisible to keep its returned name out of stdout. The method receives its object explicitly rather than a bound receiver.
C
#include <stdio.h>
struct Counter { int n; };
static void counter_add(struct Counter *self, int amount)
{
self->n += amount;
}
int main(void)
{
struct Counter counter = {2};
counter_add(&counter, 3);
counter_add(&counter, 4);
printf("%d\n", counter.n);
return 0;
}R
setClass("WindowDemo",slots=c(side="numeric"))
invisible(setGeneric("areaDemo",function(x)standardGeneric("areaDemo")))
setMethod("areaDemo","WindowDemo",function(x)x@side*x@side)
cat(areaDemo(new("WindowDemo",side=4)),"\n",sep="")S4 selects methods through a generic and a signature, not a bound field on each instance.
Challenge
EasyDefine S4 class Reading with numeric slot value. Define generic doubled(x) and its Reading method returning twice the slot. The adapter constructs Reading from one input number. Wrap setGeneric in invisible to avoid unintended printed output.
Keep the declared public API. The visible locked driver checks it directly as well as printing solve(lines). Inputs satisfy the stated contract; all arithmetic is small and finite.
Your code goes in Reading.R and Exercise.R. main.R sources dependencies in order and holds the supplied input/output code; it cannot be edited.
Try it yourself
source("Reading.R")
source("Exercise.R")
x<-new("Reading",value=7);stopifnot(isS4(x),is(x,"Reading"),identical(doubled(x),14))
lines <- suppressWarnings(readLines(file("stdin"), warn=FALSE))
cat(solve(lines), "\n", sep="")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in R for C Developers
1Files and Atomic Values
Run the R FilesText and OutputAtomic VectorsDivision and ModuloNULL and Missing ValuesRecap: Parcel Charge7Objects and Invariants
S3 Object ConstructionValidated ConstructorsS4 Classes and MethodsEnvironment IdentityClosure EncapsulationRecap: Running Peak2Logic and Iteration
Comparisons and RecyclingScalar ConditionsNamed AlternativesSafe Index SequencesBreak and NextRecap: Fare Bands5Functions and Closures
Functions and ReturnsDefaults and PromisesDots ArgumentsClosures and StateRecap: Discount Total8Collaboration and Contracts
Function CollaborationS3 Inheritance OrderS4 Validity ContractsIdentity and AttributesRecap: Grouped Counts3Collections and Ownership
Vector SubsettingHeterogeneous ListsNamed LookupValues and EnvironmentsRecap: Unique StockPractice on your own: Online R compiler