cancel
Showing results for 
Search instead for 
Did you mean: 

higher-order function with recursive

srevurikdb
New Contributor
Hi All,
I am new to KDB+ and q. I am trying implement higher-order function with recursive and found below code in the docs.
I could not understand how it is working.
Could you please explain below code.
code
q) 10 {x,sum -2#x}/ 1 1

results
1 1 2 3 5 8 13 21 34 55 89 144
3 REPLIES 3

ajay
New Contributor II
This is generating Fibonacci sequence, in each iteration appending the sum of last two elements.

Can also use scan

q)last flip 10{x[1],sum x}\1 1
1 2 3 5 8 13 21 34 55 89 144



unterrainer_ale
New Contributor
Hi,
so basically you are looking at one of the applications of iterators  (previously known as adverbs). This particular form can be compared to a "Do" loop in other programming languages. Let's have a look at the code, for simplicity let's define the function f as following 

f:{x,sum -2#x}

Then your code becomes 
10 f/ 1 1 
On a side note this could also be written as f/[10;1 1] which might make it easier to understand. In this case / (over) acts as an accumulator, executing your function f 10 times using 1 1 as initial parameter. the result of the first iteration then becomes the input of the second iteration and so on. 

what does f do? 

q is executed left of right, means from right to left. -2#x takes the last two elements of x (1 1), sum sums them and the result gets concatenated to the initial input x, thus after your first iteration you get 1 1 2. This will now become the input to your second iteration. A helpful way to understand over better is to use scan \ instead of over. Scan does basically the same as over except it outputs the intermediate steps. The result of over is the last output of scan.

q)10 {x,sum -2#x}\1 1
1 1
1 1 2
1 1 2 3
1 1 2 3 5
1 1 2 3 5 8
1 1 2 3 5 8 13
1 1 2 3 5 8 13 21
1 1 2 3 5 8 13 21 34
1 1 2 3 5 8 13 21 34 55
1 1 2 3 5 8 13 21 34 55 89
1 1 2 3 5 8 13 21 34 55 89 144

Hope this helps. 

More details about Iteration can be found here https://code.kx.com/q/basics/iteration/
There is also a great white paper about it here https://code.kx.com/q/wp/iterators/
And the particular DO case is explained here: https://code.kx.com/q/ref/accumulators/







Thanks Alexander for your explanation.