Back to Over

Iterators · Over · Practice Question

Compute the Fibonacci Sequence

Sign in to track your progress

Question

Write a q expression that computes the first 12 terms of the Fibonacci sequence, starting from 1 2.

Expected result:

1 2 3 5 8 13 21 34 55 89 144 233

Solution

{x,sum -2#x}/[10;1 2]

Explanation

-2#x takes the last two elements of the running list x. sum -2#x adds them together to get the next Fibonacci term, and x,sum -2#x appends that term onto the end of x — so each call grows the list by one element, using the list's own last two values to produce the next one.

This is the Do form: n f/[x] runs f exactly n times, using / (over), and returns only the result of the final call. Here n is 10 and the seed x is 1 2, so the function fires 10 times, growing the list by one term each time:

1 2
1 2 3
1 2 3 5
1 2 3 5 8
1 2 3 5 8 13
...
1 2 3 5 8 13 21 34 55 89 144 233

Because the function builds the sequence by growing the list itself, each pass already contains every term seen so far — over only needs to hand back the last pass to have the complete answer, which is why 10 iterations starting from a 2-item seed produce all 12 terms in one go, with no separate "collect the results" step needed.

Swapping / for \ — {x,sum -2#x}\[10;1 2] — runs the exact same 10 steps but returns every intermediate list along the way instead of just the final one, the same final-result-only-vs-every-step distinction as the companion null-fill questions in this section and the Scan section.