Back to Scan

Iterators · Scan · Practice Question

Build an Ever-Increasing List Using Scan

Sign in to track your progress

Question

Write a q expression that produces:

,1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

Solution

(,\) 1+til 5

Alternative Solution

{x,1+last x}\[4;1]

Alternative Solution

(1+til 5)#\:1+til 5

Explanation

The scan iterator:

\

applies a function successively, feeding the result of each step into the next, and keeps every intermediate result — unlike over (/), which only keeps the final one.

(,\) 1+til 5

applies join (,) as a running scan over 1+til 5 (1 2 3 4 5) — the same accumulate pattern as +\ for running totals, but using , instead of +, so each step joins the running list with the next value:

,1
1,2     -> 1 2
1 2,3   -> 1 2 3
1 2 3,4 -> 1 2 3 4
1 2 3 4,5 -> 1 2 3 4 5

producing exactly the growing list required.

The first alternative reaches the same place with an explicit accumulator function and a seed, growing the list one element at a time. It uses the Do form of Scan: \[4;1] applies the function 4 times to the seed 1, and Scan returns the seed plus the 4 results — 5 rows in total.

The second alternative takes a completely different, non-scan route: (1+til 5)#\:1+til 5 uses each-left to take the first n elements of 1 2 3 4 5 for every n in 1 2 3 4 5, which happens to produce the same triangular shape.