Menu
CoddyTech

Closure Encapsulation

Lesson 36 of 48 in Coddy's R for C Developers course.

C has no private field keyword; opaque structs and controlled module functions can hide representation. R closures retain bindings in enclosing environments and expose getter/setter functions through a list. This is an accessor API, not native property-assignment syntax. Validate before superassignment so rejected updates leave the old state intact.

C

#include <stdio.h>
struct Meter{int level;};
static void meter_set(struct Meter *m,int level){if(level>=0)m->level=level;}
static int meter_get(const struct Meter *m){return m->level;}

int main(void) {
struct Meter m={4};meter_set(&m,-1);printf("%d\n",meter_get(&m));
return 0;
}

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 icon

Challenge

Easy

Implement 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="")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in R for C Developers

Practice on your own: Online R compiler