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
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.