DEVELOPMENT EDITION · 769442725406
Language Reference
On this page

Pipelines, iteration, and reductions

A pipeline visits a supported source, applies zero or more stages, and finishes with a consumer. It is consumed in one expression or iteration context. It is not a storable, returnable lazy iterator object and does not create general escaping closures.

The APL chapter describes the embedded array language that shares these combinators' lowering, its distinct reduction and shape semantics, and the words both spell (scan, take and skip from the end, rfold, sorting and the array functions).

Common model

The source is an array, a discrete range, or a container with the required iteration protocol. Stages transform or filter each visited element. A consumer produces a result, constructs a collection, evaluates a quantifier, or drives supported loop execution. The compiler lowers these forms to loops and associated checks/invariants.

Component Role
Map Transform each accepted element through a safe pure expression
Filter Keep elements satisfying a predicate
Take while Stop at the first relevant element whose continuing condition is false
Reduction Update an accumulator using a reducer and initial value
All/any Universal/existential predicate result with the corresponding empty-domain identity
Collect Construct an array/container with the expected type and required bounds/capacity
Zip/lockstep Walk supported sources together, terminating at the shortest
Enumerate Introduce the frontend's documented counter alongside source elements
Optional first/find/last Produce a supported optional result through the required optional API

Not every frontend spells every consumer independently. This table describes the common roles; the syntax references enumerate the actual names and restrictions. The scan and the words added with APL are listed in the APL chapter; flat-map, general take/skip counts and parallel reduction are not implied.

Order and stage restrictions

Sources are visited in their declared traversal order. Array component traversal is row-major for multidimensional values. Each filter or transformation applies according to its stage order. A false filter skips the consumer for that element. Take-while ends the pipeline rather than merely discarding one element.

Stages apply in the order they are written. A filter written before a take-while decides which elements the stopping condition sees; a filter written after it only drops elements from what the take-while lets through, and does not move the stopping point. On [2, 1, 3]:

Varc chain Visited elements Sum
take_while(x => x > 1).filter(x => x != 1) 2, then 1 stops the pipeline 2
filter(x => x != 1).take_while(x => x > 1) 2, 3 (1 is filtered out before the stop) 5

The order example runs the first chain and prints order: 2. Vibe's takewhile(...) followed by an if filter in a generator or loop has the same written-order meaning. In Vada's iterator clauses, which put when before while, the filter comes first: while stops at the first element the filter keeps that fails the condition.

Stage expressions obey ordinary purity, bounds, and ownership rules. They can use permitted enclosing values directly because they execute inside the consumed expression, not later through an escaped closure.

Reduction semantics

A reduction starts with its initial accumulator. For every kept value in order, it applies the reducer to the previous accumulator and that value. An empty source returns the initial value. The reducer can be a supported operator symbol or a named function with a suitable profile. Its type must be determined by the expected result, initial value, or element context according to the accepted form.

This is a complete expression-function fragment with its required array declaration:

subtype Score is Integer range 0 .. 100;
type Scores is array (Positive range <>) of Score;
function Total (A : Scores) return Integer is (A'Reduce ("+", 0))
  with Pre => A'Length <= 1000;

The element bound and length precondition allow the accumulator to remain within Integer. Each executable accumulator operation has its required bounded-arithmetic safety checks. The logical specification-fold path used in proof is mathematical; using that fold in a contract does not itself prove an executable accumulator fits. Runtime evaluation of contracts depends on build policy and the supported executable/ghost form.

A floating-point reduction folds the elements in order, rounding after each step, exactly as the equivalent loop does. The result is not reassociated, vectorized or computed with extra precision, so it need not equal the exact real sum.

Source presentations

Vada can reduce an array directly or a bracketed value sequence:

[for X of A when X >= Mark => X]'Reduce ("+", 0)

This fragment needs compatible A and Mark. Its filter establishes the mark relationship for the mapped value. Varc presents supported stages as chains or |> pipelines, for example a.filter(x => x >= mark).sum(). Vibe recognizes supported sum, all, and any generator forms and selected collection/iteration helpers. Its generator object is not an ordinary first-class Python generator that can escape.

Varc also permits the general pipe's first-argument insertion before a pipeline begins, with its explicit placeholder restrictions. Once a pipeline stage has begun, ordinary calls cannot simply be appended after it; a valid consumer must finish it. B0707 through the applicable pipeline diagnostics explain missing consumers, illegal lambdas, placeholder counts, and invalid chaining.

Lockstep and counters

Lockstep advances a primary source and its supported companions until one ends. Equal lengths are not always required, but any expression using indices must still respect each source's actual bounds and origin. An enumerate counter is not necessarily the array's native index; Varc's supported .enumerate() counter starts at zero.

Vada's multiple-source and while clauses are Verada extensions gated by pragma Extensions_Allowed (On) in the applicable context. Varc and Vibe express supported forms through their native-looking syntax. translate --to vada --plain-ada expands supported placements, with explicit failures for combinations it cannot preserve.

Quantifiers and collections

An all result is true for an empty visited domain; any is false. Short-circuit/absorbing behavior applies where the consumer is recognized to stop once the result is determined. A collected value must have a known permitted target type. A fixed-capacity container requires capacity preconditions, while a dynamically sized array needs the supported shape/bounds construction. Collection fusion does not mean the final result consumes no storage or that allocation can never fail.

Filtered collection lengths differ from source lengths. Generated count/shape invariants help prove the relationship, but the destination and user postconditions can still need additional information. Vibe writes a filtered collection as a list comprehension, [x * 10 for x in values if x % 2 == 0]; see the Vibe reference.

Optional consumers

Verada.Optionals represents a value with a Present discriminant and conditional Item. None, Just, Has_Value, and Value supply its public interface. Value requires a present value. Keep_First and Keep_Last reducers express the corresponding selection.

Varc .find(predicate), .first(), and .last() use the supported visible optional instance and reducers. Automatic arbitrary optionals instantiation and proposed fallback consumer names must not be assumed. The result is an optional value, not the raw element with an undocumented default. Establish presence before extracting it.

Proof and recovery

The prover sees the loop meaning and generated invariants. A filter can establish facts used by a subsequent map, such as a nonzero divisor. Bounds on elements and source length can establish accumulator limits. Reductions in specifications use the supported fold/model reasoning; they do not license arbitrary effectful reducer code.

If a compact pipeline leaves an obligation unproved, an available expand-to-loop fix can turn supported return, assignment, or expression-function forms into explicit loop code. The user may then add an invariant. The fix is not available for every nested expression or target form. Check and prove the resulting source rather than treating any suggested rewrite as an independent proof certificate.

The maintained pipeline specification and loop implementation show complete context.