Closures

Closures are anonymous functions that capture variables from their surrounding scope. Pyr closures use copy-capture - they snapshot values at creation time, so mutations inside a closure never affect the outer scope.

Closures are anonymous functions created with fn. They capture variables from their enclosing scope.

fn main() {
  multiplier = 3
  triple = fn(x) x * multiplier

  println(triple(5))
  println(triple(10))

Closures can be passed to functions. Use fn(T) -> T to type the parameter.

  println(apply(7, fn(x) x + 1))
  println(apply(7, fn(x) x * x))
}

A function that takes a typed closure parameter.

fn apply(val: int, f: fn(int) -> int) -> int {
  f(val)
}
$ pyr run closures.pyr
15
30
8
49