Back to Each

Iterators · Each · Practice Question

Repeat Each Number N Times to Build a Jagged List

Sign in to track your progress

Question

Write a q expression that produces the following list of lists, where each number n appears exactly n times:

,1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
6 6 6 6 6 6
7 7 7 7 7 7 7
8 8 8 8 8 8 8 8
9 9 9 9 9 9 9 9 9
10 10 10 10 10 10 10 10 10 10

Solution

{x#x}'[1+til 10]

Alternative Solution

(#') . 2#enlist 1+til 10

Alternative Solution

#[;] .' flip 2#enlist 1+til 10

Explanation

Each solution — {x#x}'[1+til 10]

1+til 10 produces 1 2 3 4 5 6 7 8 9 10. The each iterator ' applies the lambda {x#x} to every element. For each n, n#n takes n copies of the atom n:

1#1  -> ,1
2#2  -> 2 2
3#3  -> 3 3 3

The result is a list of 10 sublists, each of length equal to its value.

First alternative — (#') . 2#enlist 1+til 10

enlist 1+til 10       / ,1 2 3 4 5 6 7 8 9 10 — wrap the list in a one-item list
2#enlist 1+til 10     / repeat it twice: a 2-row matrix, each row 1 2 3 4 5 6 7 8 9 10

(#') is # (take) decorated with ' (each-both), making it apply element-wise between two lists of equal length: counts #' values. The monadic . (apply) spreads a list of arguments into a function call:

f . (a; b)   /  equivalent to  f[a; b]

So (#') . (1 2..10; 1 2..10) becomes 1 2..10 #' 1 2..10, which applies n#n for every position:

1#1 -> ,1
2#2 -> 2 2
3#3 -> 3 3 3   ...

The key insight: duplicating the list with 2#enlist gives both the count argument and the value argument of #' from the same source, so each number naturally takes that many copies of itself.

Second alternative — #[;] .' flip 2#enlist 1+til 10

Similar setup, but uses flip to transpose the 2×10 matrix into a 10×2 list of pairs (1 1; 2 2; 3 3; ...), then .' (apply-each-spread) to fan each pair out as separate arguments to the #[;] projection:

#[;] .' (1 1; 2 2; 3 3; ...)
-> (1#1; 2#2; 3#3; ...)
-> (,1; 2 2; 3 3 3; ...)

.' differs from . in that it applies the function to each sub-list rather than once to the whole argument list.

Comparison:

{x#x}'(#') .#[;] .' flip
StyleExplicit lambdaTacit, each-bothTacit, projection + flip
Key primitive' each#' each-both + . apply.' apply-each-spread
Relative clarityEasiest to read aloudConcise, no flip neededMost moving parts
Interview useClearest to explainGood follow-upShows depth

The lambda form is easiest to explain in an interview; (#') . is the most compact tacit form; the .' version demonstrates projections and apply-each-spread at the cost of an extra flip.

See also: the companion question Build an Ever-Increasing List Using Scan for the related pattern where each sublist goes from 1 up to n (1 2 3 4 5 ...) rather than repeating n.