Menu
CoddyTech

S3 Generic Dispatch

Lesson 30 of 48 in Coddy's R for C Developers course.

C can implement dynamic dispatch through tags or function-pointer tables chosen by the program. R S3 uses a generic calling UseMethod and method names of the form generic.class. An object may carry an ordered class vector and a default method can handle unmatched classes. A method name alone does not trigger dispatch without the generic operation.

C

#include <stdio.h>
#include <stddef.h>
struct Channel {
    const char *prefix;
    void (*send)(const struct Channel *self, const char *text);
};
static void send_prefixed(const struct Channel *self, const char *text)
{
    printf("%s:%s", self->prefix, text);
}
int main(void)
{
    struct Channel channels[] = {
        {"email", send_prefixed}, {"sms", send_prefixed}
    };
    for (size_t i = 0; i < 2; ++i) {
        if (i != 0) {
            putchar('|');
        }
        channels[i].send(&channels[i], "hi");
    }
    putchar('\n');
    return 0;
}

R

speak <- function(x) UseMethod("speak")
speak.bell <- function(x) "ring"
speak.default <- function(x) "quiet"
cat(speak(structure(list(),class="bell")), "\n", sep="")

UseMethod performs S3 dispatch; similarly named functions do not call themselves.

challenge icon

Challenge

Easy

Define describe(x) as an S3 generic, describe.default(x) returning plain, and describe.parcel(x) returning parcel:N from x$units. Input is a nonnegative number and the adapter constructs a parcel-class list.

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 Parcel.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("Parcel.R")
source("Exercise.R")
stopifnot(identical(describe(9),"plain"),identical(describe(structure(list(units=7),class="parcel")),"parcel:7"))
lines <- suppressWarnings(readLines(file("stdin"), warn=FALSE))
cat(solve(lines), "\n", sep="")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in R for C Developers

Practice on your own: Online R compiler