S3 Generic Dispatch
Lesson 30 of 48 in Coddy's R for Python Developers course.
Python singledispatch chooses an implementation from an argument type. R S3 dispatch uses a generic containing UseMethod and functions named generic.class. The class attribute can be a vector, and fallback methods can handle otherwise unrecognized values. This is real method dispatch, not a Python class declaration renamed in R.
Python
from functools import singledispatch
class Bell:
pass
@singledispatch
def speak(value):
return "quiet"
@speak.register
def _(value: Bell):
return "ring"
print(speak(Bell()))R
speak <- function(x) UseMethod("speak")
speak.bell <- function(x) "ring"
speak.default <- function(x) "quiet"
cat(speak(structure(list(),class="bell")), "\n", sep="")An S3 generic needs its dispatch operation; a matching method name alone does not invoke itself.
Challenge
EasyDefine 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="")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in R for Python Developers
1Files and Atomic Values
Run the R FilesText and OutputAtomic VectorsDivision and ModuloNULL and Missing ValuesRecap: Parcel Charge2Logic 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 Stock6Parsing and S3 Dispatch
String ParsingConditions and RecoverySource and EnvironmentsS3 Generic DispatchRecap: Observed MeanPractice on your own: Online R compiler