S3 Object Construction
Lesson 32 of 48 in Coddy's R for GDScript Developers course.
GDScript script classes hold member variables and methods and can initialize instances in _init. An R S3 object can simply be a list with a class attribute and external generic methods. Constructor functions should establish its structure because the tag alone validates no fields. Preserve one consistent public object shape across files.
GDScript
extends SceneTree
class Counter:
var n
func _init(initial):
n = initial
func _init():
var first = Counter.new(4)
var second = Counter.new(7)
first.n = 9
print(str(first.n) + ":" + str(second.n))
quit()R
new_lamp <- function() structure(list(on=FALSE),class="lamp")
a<-new_lamp();b<-new_lamp();a$on<-TRUE
cat(b$on,"\n",sep="")An S3 class label does not validate every field automatically.
Challenge
EasyImplement new_meter(value) returning an S3 object with class meter and one numeric list member value. Implement read_meter(x) returning its value. Input is one number.
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 Meter.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("Meter.R")
source("Exercise.R")
x<-new_meter(17);stopifnot(inherits(x,"meter"),is.list(x),identical(x$value,17),identical(read_meter(x),17))
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 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