# Closures

Closures (also called lambdas or anonymous functions) are functions that can capture variables from their enclosing scope. They are a core building block for functional-style programming, callbacks, and iterator chains in Vex.

## Syntax

Vex closure syntax uses pipe-delimited parameters directly followed by the body expression or block. No `=>` is needed:

```vex
// Basic closure: |params| expression
let double = |x: i32| x * 2

// Multi-parameter
let add = |a: i32, b: i32|  a + b

// No parameters
let greet = ||  $println("Hello")

// Multi-statement body with braces
let compute = |x: i32, y: i32|  {
    let temp = x * y
    let result = temp + 10
    return result
}
```

## Calling a Closure

Call closures with the same `()` syntax as regular functions:

```vex
let triple = |n: i32|  n * 3

let six = triple(2)       // 6
let nine = triple(3)      // 9
```

## Type Inference

Closure parameter types can often be inferred from context:

```vex
// Named function reference:
fn timesTwo(x: i32): i32 { return x * 2 }
let number: Option<i32> = Some(5)
let doubled: Option<i32> = number.map(timesTwo)

// An explicitly typed closure is another way to provide the callback:
let doubledAgain: Option<i32> = number.map(|x: i32| x * 2)
```

An expected callable type supplies context for a closure. Explicit parameter
types also document the callback contract and distinguish a borrowed `&T` from
an owned `T`. This matters for generic collection transforms and for callbacks
whose input and output types differ. See the [Option](option-api.md)
and [Result](result-api.md) examples.

## Capture Modes

Closures may capture variables from their enclosing scope. The compiler
analyzes how each capture is used and checks its ownership and lifetime.
Do not infer the physical representation solely from the source syntax:
the compiler can copy a read-only scalar into the environment,
borrow storage, or transfer ownership depending on the value and use.

### Shared (Immutable) Capture

When a closure only reads captured variables:

```vex
let multiplier = 10

// Reads multiplier. A Copy scalar can be copied into the environment.
let scale = |x: i32|  x * multiplier

let result = scale(5)  // 50
// multiplier is still usable here
```

### Mutable Capture

When a closure modifies captured variables:

```vex
let! counter = 0

// Captures counter by mutable reference
let increment = ||  {
    counter += 1
}

increment()
increment()
// counter is now 2
```

### Move Capture

Some uses transfer ownership into a closure environment. The exact outcome
depends on the captured type and how the closure is used. Do not assume that a
move-only value remains usable after ownership transfers. If a callback needs
repeatable access, borrow for a bounded call or give it an explicitly owned
handle with the appropriate sharing policy. A closure returning or retaining
a reference cannot extend the lifetime of its referent.

### A runnable capture example

This example exercises a read-only scalar, a mutable capture, an ordinary
callback and a returned closure. Save it as `capture-example.vx`:

```vex [capture-example.vx]
fn applyTwice(f: fn(i32): i32, x: i32): i32 { return f(f(x)); }
fn makeMultiplier(factor: i32): fn(i32): i32 { return |x: i32| x * factor; }
fn addOne(x: i32): i32 { return x + 1; }
fn main(): i32 {
    let multiplier = 10;
    let scale = |x: i32| x * multiplier;
    $println(scale(5));
    $println(multiplier);
    let! counter = 0;
    let increment = || { counter += 1; };
    increment(); increment();
    $println(counter);
    let addThree = |n: i32| n + 3;
    $println(applyTwice(addThree, 10));
    let timesFive = makeMultiplier(5);
    $println(timesFive(10));
    let named: fn(i32): i32 = addOne;
    $println(named(41));
    return 0;
}
```

`vex run capture-example.vx` prints:

```text
50
10
2
16
50
42
```

## Closure Types

Use a function-value signature to describe the callback interface independently
of its captures:

```vex
// Function that accepts any callable returning i32
fn applyTwice(f: fn(i32): i32, x: i32): i32 {
    return f(f(x))
}

let addThree = |n: i32|  n + 3
let result = applyTwice(addThree, 10)  // (10+3)+3 = 16
```

## Closures as Callbacks

Closures are the standard way to pass behavior into higher-order functions:

```vex
fn sumWhere(values: &Vec<i32>, predicate: fn(i32): bool): i32 {
    let! total = 0;
    for value in values {
        if predicate(*value) { total += *value; }
    }
    return total;
}
```

The vector remains borrowed for the call, and the callback receives an integer
copy. With `[1, 2, 3, 4, 5, 6]` stored in a `Vec<i32>`,
`sumWhere(&numbers, |n: i32| n % 2 == 0)` returns `12`.
For library adapters, use the receiver and callback signatures on the
[Vec](vec.md), [Option](option-api.md), and
[Result](result-api.md) pages. An array does not gain those methods
merely because it contains the same element type.

## Closures with `go` Blocks

`go` blocks capture the values they use. Ownership, borrowing and lifetime
checks still apply; inspect the diagnostics for the captured types rather than
assuming that every capture has the same representation:

```vex
let! messages = Channel.new<string>(10)

let prefix = "Msg: "

// The block uses both prefix and messages.
go {
    let text = prefix + "hello from goroutine"
    messages.send(text)
}

let received = <-messages
```

## Closures vs Function Pointers

| Feature | Closure | Named Vex function as a value |
| --- | --- | --- |
| Captures | May use an environment | Does not capture local variables |
| Native callable | Entry point plus environment/context | Uses the Vex callable representation as well |
| Cost | Depends on capture, lifetime, lowering and optimization | Depends on lowering and optimization |
| Foreign callback | Requires an explicitly supported foreign adapter and lifetime contract | Also requires the exact foreign ABI and a supported adapter |

The native implementation represents a Vex function value with a code
pointer and an environment/context pointer. Environment storage depends on the
captures and may outlive the defining scope when supported. This is an internal
implementation detail, not a stable public or C ABI. Do not assume a native
`fn(...)` value is one pointer or that either kind of callable is directly
interchangeable with a C callback. See [Function Types](function-types.md)
and [FFI callbacks](../ffi-deep-dive.md#callbacks).

```vex
// Named function as a native Vex callable; no local capture.
let fp: fn(i32): i32 = someTopLevelFn

// Closure: can capture, used for local callbacks
let closure = |x|  x + capturedValue
```

## Returning Closures

An escaping closure must retain valid captures for its lifetime. Allocation and
capture strategy are implementation details and may vary with the compiler:

```vex
fn makeMultiplier(factor: i32): fn(i32): i32 {
    // This closure escapes the function and retains the scalar factor.
    return |x: i32|  x * factor
}

let timesFive = makeMultiplier(5)
let result = timesFive(10)  // 50
```

## Best Practices

1. Use the shortest closure form (`|x|  x * 2`) when the body is a single expression.
2. Use brace-delimited bodies for multi-statement closures.
3. Let type inference work -- annotate parameter types only when the compiler asks for it.
4. Be aware of capture and ownership: reads may copy or borrow, mutation requires appropriate access, and some uses transfer ownership.
5. For `go` blocks, be explicit about which variables are used inside to avoid accidental captures.
6. For FFI callbacks, verify the foreign ABI, adapter, context lifetime and thread rules; a native `fn(T): R` alone is not sufficient.

## Related Pages

- [Function Types](function-types.md) -- `fn(T): R` pointers
- [Loops & Labels](../basics/loops.md) -- closures in iteration
- [Async](../concurrency/async.md) -- closures in async context
