Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Lambdas

A lambda — an anonymous function written |x, y, z| body — is the primary way to specialise a higher-order operator per call site. Parameter types may be inferred from context or given explicitly:

map(|x| x * 2.0, arr)
map(|x: f32| x * 2.0, arr)

Environment Capture

A lambda captures every free variable in its body — every identifier that is bound outside the lambda but referenced inside it. The captured values become part of the lambda’s behaviour and travel with it wherever it is passed.

def above(threshold: i32, arr: [n]i32) ?k. [k]i32 =
    filter(|x| x > threshold, arr)

The lambda captures threshold from the enclosing function’s parameters; filter invokes the lambda once per element of arr, and each invocation sees the captured threshold.

Capture is by value: each captured value is snapshotted at the lambda’s construction site. Because Wyn is purely functional there is no observable difference between by-value and by-reference capture in any case.

A lambda may capture any value visible at its definition site — scalars, arrays, vectors, records, tuples, and references to named functions. References to named functions are resolved statically; they do not become runtime function values.

Restrictions

Lambdas do not permit type parameters — they are inherently monomorphic at their definition site. To express a polymorphic higher-order computation, use a named function and pass it to the operator instead.

The restrictions on functional types described under Higher-order Functions apply to lambda-valued expressions just as to any other functional-typed value.