Closure Encapsulation
Lesson 36 of 48 in Coddy's R for Python Developers course.
Python properties mediate access through descriptor behavior. An R closure can hide a binding inside its enclosing environment and expose getter/setter functions in a returned list. This is an actual closure object pattern, not a native property syntax. Validation should happen before superassignment so rejected updates leave the old state intact.
Python
class Thermostat:
def __init__(self):
self._degrees = 20
@property
def degrees(self):
return self._degrees
@degrees.setter
def degrees(self, value):
if not 0 <= value <= 30:
raise ValueError("range")
self._degrees = value
t = Thermostat()
try:
t.degrees = 99
except ValueError:
pass
print(t.degrees)R
thermostat <- function(){n<-20;list(get=function()n,set=function(x){if(x<0||x>30)stop("range");n<<-x})}
t<-thermostat();invisible(tryCatch(t$set(99),error=function(e)NULL))
cat(t$get(),"\n",sep="")A closure accessor API must be called as functions rather than treated as native property assignment.
Challenge
EasyImplement new_wallet(start) returning a list with closures balance() and spend(amount). spend returns FALSE for negative amounts or amounts over the balance, without mutation; otherwise subtracts and returns TRUE. Input is start followed by spending requests; output final balance. All start balances are nonnegative.
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 Wallet.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("Wallet.R")
source("Exercise.R")
w<-new_wallet(9);v<-new_wallet(2);stopifnot(isTRUE(w$spend(4)),identical(w$balance(),5),identical(w$spend(8),FALSE),identical(w$balance(),5),identical(v$balance(),2))
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