Skip to content

Closures

A closure is a function that captures variables from its surrounding scope. This means the function can remember and access those variables even after the outer function has finished executing. Closures are useful for creating factory functions, maintaining state, and implementing data hiding.

Closures are a powerful feature that enable advanced programming patterns and encapsulation.

Example

# Returns a function that captures its environment
fn make_adder(x: Int) {
    return fn(y) => x + y
}

let add5 = make_adder(5)
print(add5(10))  # Should print 15

Let's break down how this example works:

  • make_adder is a function that takes a number x as its input.
  • Inside make_adder, a new function is created and returned. This new function takes a number y as its input and adds it to x.
  • When you call make_adder(5), you get back a function that always adds 5 to its input. This returned function "remembers" the value of x (which is 5) even after make_adder has finished running. That's what makes it a closure.
  • When you call add5(10), it adds 10 (the value of y) to 5 (the remembered value of x), resulting in 15.

This shows how closures let functions keep information from their creation context and use it later.


Next
Up