Skip to content

Controlling evaluation

Evaluation is controlled by

  • iterators (maps and accumulators) for iteration
  • conditional evaluation
  • explicit return from a lambda
  • signalling and trapping errors
  • control words
  • exit



Iterators are the primary means of iterating in q.


The maps Each, Each Left, Each Right, Each Parallel, and Each Prior are iterators that apply values across the items of lists and dictionaries.


The accumulators Scan and Over are iterators that apply values progressively: that is, first to argument/s, then progressively to the result of each evaluation.

For unary values, they have three forms, known as Converge, Do, and While.


Case control structures in other languages map values to code or result values. In q this mapping is more often handled by indexing into lists or dictionaries.

q)show v:10?`v1`v2`v3               / values
q)`r1`r2`r3 `v1`v2`v3?v             / Find
q)(`v1`v2!`r1`r2) v                 / dictionary: implicit default
q)`r1`r2`default `v1`v2?v           / explicit default

The values mapped can be functions. The pseudocode

for-each (x in v) {
    switch(x) {
    case `v1:
    case `v2:
        string x;

can be written in q as

q)((`abc,;string;::) `v1`v2?v)@'v

and optimized with .Q.fu.

See also the Case iterator.

Control structures

Conditional evaluation


Cond evaluates and returns ef when test is zero; else et.

In the ternary form, two expressions are evaluated: test and either et or ef. With more expressions, Cond implements if/then/elseif… control structures.


Vector Conditional

The Vector Conditional operator, unlike Cond, can be used in query templates.

Vector Conditional is an example of a whole class of data-oriented q solutions to problems other languages typically solve with control structures. Data-oriented solutions are typically more efficient and parallelize well.

Control words


evaluate some expression/s some number of times


evaluate some expression/s if some condition holds


evaluate some expression/s while some condition holds

Control words are not functions. They return as a result the generic null.

Common errors with control words

a:if[1b;42]43               / instead use Cond
a:0b;if[a;0N!42]a:1b        / the sequence is not as intended!

Control words are little used in practice for iteration. Iterators are more commonly used.

Explicit return

:x has a lambda terminate and return x.

Explicit return

Signalling and trapping errors

Signal will exit the lambda under evaluation and signal an error to the expression that invoked it.

Trap and Trap At set traps to catch errors.


The exit keyword terminates kdb+ with the specified return code.

Back to top