Search code examples
iteratorsimulationkdb

run function recursively over table


Every call to function fx left-joins a new column to x based on some data in table t and integers p and q.
I show desired iteration over values of p and q below but do not know how to do it properly using KDB+ iterators.
Sample data and solution:

x:([]date:(2013.07.01+til 10);ords:til 10); /Some random table with date (key column)
t:p:([]date:(2013.07.01+1000#til 200);px:1000?10e); /Some random table.
fx:{[x;t;p;q]
    /Do something with t;p;q and left-join output column to x on date;
    t:([]date:(2013.07.01+til 10);ords:10?10000);
    col_names:(`date;`$""sv(string(`P);string(p);string(`Q);string(q)));
    t: x lj 1!col_names xcol t;
    :t
    };

/Run simulation for p=1 to 2 and q=3 to 4 as follows:
fx[ fx[ fx[ fx[x;t;1;3]; t;2;3]; t;1;4]; t;2;4] /How to do this iteration properly?

Last statement has two for loops on p and q from 1to2 and 3to4 respectively. I am sure there is a better way to achieve this using scan/over but I am not able to figure it out. Could someone help here.


Solution

  • We can pass t as a projection as it remains constant over each iteration and then use scan iterate over the other variables

    fx[;t;;]/[x;1 2 1 2;3 3 4 4]