Menu
CoddyTech

Closures and State

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

Portable C callbacks commonly pair a function pointer with an explicit state pointer and a managed lifetime. R closures retain their lexical environment, and <<- searches enclosing bindings. Initialize local state in the factory before using superassignment to avoid accidentally reaching a global. force can capture a promised configuration before later changes affect evaluation.

C

#include <stdio.h>
struct Counter { int n; };
struct Callback { int (*call)(void *); void *context; };
static int step(void *context) {
    struct Counter *counter = context;
    counter->n += 1;
    return counter->n;
}
int main(void) {
    struct Counter counter = {0};
    struct Callback callback = {step, &counter};
    int first = callback.call(callback.context);
    int second = callback.call(callback.context);
    printf("%d\n", first + second);
    return 0;
}

R

make_toggle <- function() { on<-FALSE; function(){on<<-!on;on} }
f<-make_toggle()
cat(f(),f(),"\n")

Establish the intended enclosing binding before using superassignment.

challenge icon

Challenge

Easy

Implement make_adder(offset) returning a function that adds the captured offset to its numeric argument. Input first number is offset and remaining numbers are inputs for that function; no remaining numbers prints an empty line.

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 Functions.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("Functions.R")
source("Exercise.R")
f<-make_adder(8); g<-make_adder(2); stopifnot(identical(f(4),12),identical(g(4),6))
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