Skip to content

Iteration in q

Reviewing and extending how you first learned to iterate in q

Traktor hjularna går rund, rund, rund
Rund, rund, rund; rund, rund, rund
Traktor hjularna går rund, rund, rund
Rund, rund, rund på betar
— Swedish nursery rhyme

The rhyme tells about beets and tractor wheels going round and round and round. It’s about iteration and it’s in a language you are probably not familiar with. And here we are.

Iterating through the items of a list is such a basic part of programming you may be surprised how little you need to do about it in q.

Distinguish two kinds of iteration.

Map iteration

Evaluates an expression once on each item in a list or dictionary. The evaluations are independent: if they have no side effects, they can be performed in parallel.

Map iteration

Accumulator iteration

Evaluates an expression successively: the result of one evaluation becomes an argument of the next.

Accumulator iteration

Sometimes you need map iteration, sometimes accumulator, sometimes a combination. We look here at four ways of iterating in q.

  1. Implicit Iteration Lists are first-class objects in q, and most operators and keywords iterate through them. The first lesson is about when to leave it to q. That is: when not to specify iteration.
  2. The map iterators apply a function once to each item in a list.
  3. The accumulators apply a function successively, with the result of one evaluation becoming the argument to the next.
  4. Control words When none of the above works for you, there are the control words do and while. Learn to avoid them; learn also when it is right to use them.

The map and accumulator iteration operators go well beyond what you may already have learned to do with the keywords each, prior, scan, and over. You can use them to iterate functions of any rank; that is, any number of arguments.

Implicit iteration

Back to top