Closures

Capturing a function's enclosing environment.

What is a Closure?

A closure is a function that remembers the environment in which it was created. Because functions in Ry are first-class (they can be treated like any other value), you can return them from other functions. When you do, they "close over" any variables they reference from their parent scope.

This allows you to create stateful functions that retain access to data even after their parent function has finished executing.

Example: A Simple Counter

The classic example of a closure is a counter. The outer function is called once, creating a persistent state (the variable i), and the inner function can modify that state on each call.

func makeCounter() {
    data i = 0
    func count() {
        i = i + 1
        return i
    }
    return count
}

# makeCounter() returns the 'count' function, which closes over 'i'
data counter = makeCounter()

out(counter()) # Output: 1
out(counter()) # Output: 2
out(counter()) # Output: 3

Example: Function Factories

Closures are also excellent for creating "function factories"—functions that generate and configure other functions.

func makeAdder(data x) {
    # This inner function closes over 'x'
    func add(data y) {
        return x + y
    }
    return add
}

# Create a specialized function that adds 5 to any number
data add5 = makeAdder(5)

# Create another one that adds 10
data add10 = makeAdder(10)

out(add5(2))  # Output: 7
out(add10(2)) # Output: 12

With an understanding of functions and closures, you're ready to add define your own custom objects using Classes.

Next: Classes!