Closure Encapsulation
Lesson 36 of 48 in Coddy's R for Dart Developers course.
Dart getters and setters can validate access to an underscore-prefixed, library-private field. R closures retain bindings and expose getter/setter functions in a list. Call those functions explicitly; ordinary list assignment does not trigger them. Validate before superassignment so a rejected update preserves old state.
Dart
class Meter{int _level=4;int get level=>_level;set level(int value){if(value<0)throw ArgumentError.value(value);_level=value;}}
void main(){
final meter=Meter();meter.level=7;print(meter.level);
}
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="")Call the accessor functions; ordinary list-element assignment does not invoke them.
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 Dart 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