S3 Inheritance Order
Lesson 39 of 48 in Coddy's R for GDScript Developers course.
GDScript extends and super provide class inheritance and explicit delegation to parent behavior. R S3 dispatch instead follows an ordered vector of class names, and NextMethod continues that chain. Test that an augmenting method combines the next result once instead of replacing or accidentally repeating it.
GDScript
extends SceneTree
class Base:
var price = 5
func total(quantity):
return price * quantity
class Delivery extends Base:
var fee = 2
func total(quantity):
return super.total(quantity) + fee
func _init():
var delivery = Delivery.new()
print(str(delivery.total(3)) + ":" + str(delivery.total(0)))
quit()R
sound <- function(x)UseMethod("sound")
sound.soft <- function(x)paste0(NextMethod(),"?")
sound.bell <- function(x)"ring"
x<-structure(list(),class=c("soft","bell"))
cat(sound(x),"\n",sep="")S3 class order affects the dispatch chain.
Challenge
EasyDefine generic fee(x). Its parcel method returns x$units*2. Its urgent method returns NextMethod()+5. The adapter creates class c("urgent","parcel") when input flag is 1, otherwise class parcel. Input is nonnegative units followed by flag 0 or 1.
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(fee(structure(list(units=7),class=c("urgent","parcel"))),19),identical(fee(structure(list(units=7),class="parcel")),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 GDScript 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 StockPractice on your own: Online R compiler