Menu
CoddyTech

Lambdas and Captured State

Lesson 39 of 48 in Coddy's Ruby for C Developers course.

Portable C pairs a function pointer with an explicit context for retained state; that context must outlive calls. Ruby closures retain lexical bindings, so later assignment to a captured binding can affect a subsequent call. Blocks, procs and lambdas differ in return and argument rules. Retaining state does not imply asynchronous execution.

C: complete program

#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;
}

Ruby: complete program

prefix = "old"
label = ->(text) { prefix + ":" + text }
prefix = "new"
puts label.call("x")
challenge icon

Challenge

Easy

Define make_counter(start) returning a lambda accepting delta, adding it to captured state and returning the new state. Each call to make_counter creates independent state. solve reads start then deltas; output results space-separated, or none if no deltas.

Return text from solve(input) without printing. The locked driver prints the returned text with one final newline and checks required public APIs independently.

Your code goes in exercise.rb, counter_factory.rb. main.rb holds the supplied input/output code and cannot be edited.

Try it yourself

require_relative 'exercise'
require_relative 'counter_factory'
def check(value)
  raise 'Public API check failed' unless value
end
a = make_counter(4); b = make_counter(9)
check(a.call(3) == 7 && b.call(-2) == 7 && a.call(1) == 8)
check(a.lambda?)

puts solve(STDIN.read)
quiz iconTest yourself

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

All lessons in Ruby for C Developers

Practice on your own: Online Ruby compiler