higher-order function with recursive

60 views
Skip to first unread message

srevu...@gmail.com

unread,
Apr 20, 2021, 1:15:15 PMApr 20
to Kdb+ Personal Developers
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

Ajay Rathore

unread,
Apr 20, 2021, 2:09:20 PMApr 20
to personal...@googlegroups.com
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
--
You received this message because you are subscribed to the Google Groups "Kdb+ Personal Developers" group.
To unsubscribe from this group and stop receiving emails from it, send an email to personal-kdbpl...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/personal-kdbplus/1dbf4e03-4685-4fea-ba9b-ee1a326f0fa6n%40googlegroups.com.

Alexander Unterrainer

unread,
Apr 20, 2021, 2:23:27 PMApr 20
to personal...@googlegroups.com
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/







--

srevu...@gmail.com

unread,
Apr 21, 2021, 4:30:26 AMApr 21
to Kdb+ Personal Developers
Thanks Alexander for your explanation.
Reply all
Reply to author
Forward
0 new messages