Environment Identity
Lesson 35 of 48 in Coddy's R for Python Developers course.
Python class attributes can hold shared mutable state. R has no universal class-static field model covering S3 and S4; environments can deliberately hold shared state instead. Each factory call can allocate a distinct environment when independence is needed. Choose state lifetime explicitly rather than simulating a nonexistent Python class syntax.
Python
class Shelf:
kind = "storage"
def __init__(self):
self.books = []
a = Shelf()
b = Shelf()
a.books.append("tea")
print(len(b.books))R
new_shelf <- function(){e<-new.env(parent=emptyenv());e$books<-character(0);e}
a<-new_shelf();b<-new_shelf();a$books<-c(a$books,"tea")
cat(length(b$books),"\n",sep="")A shared environment is shared by reference, not copied per function call.
Challenge
EasyImplement new_counter() returning an environment with value zero, and advance(counter,amount) adding amount to its value and returning the new value. For all input numbers, call advance on one counter and return its final value. Empty input returns zero.
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 Counter.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("Counter.R")
source("Exercise.R")
a<-new_counter();b<-new_counter();alias<-a;stopifnot(is.environment(a));invisible(advance(a,6));stopifnot(identical(alias$value,6),identical(b$value,0))
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 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