Closures

Functions capture variables from surrounding scopes.

Inner functions close over variables from outer scopes. Those bindings stay alive after the outer function returns.

This is how you build factories, counters, and callbacks in Rain.

Counter factory

Inner functions keep outer variables alive: each call to `makeCounter` gets its own state.

Counter factory
fun makeCounter() {
  var count = 0;
  fun tick() {
    count = count + 1;
    return count;
  }
  return tick;
}

var next = makeCounter();
print next();
print next();
print next();
output
1
2
3

Pass functions around

Functions are values: pass a named function to another function as an argument.

Pass functions around
fun applyTwice(fn, value) {
  return fn(fn(value));
}

fun inc(n) { return n + 1; }

print applyTwice(inc, 10);
output
12

Anonymous callback

Pass an inline `fun` when you only need the callback once.

Anonymous callback
fun applyTwice(fn, value) {
  return fn(fn(value));
}

print applyTwice(fun(n) { return n + 1; }, 10);
output
12