Search code examples
kdb+

How to Apply a Function Modifying table_1 Based on Each Row of table_2 in Q/KDB+?


I have a function f in Q/KDB+ that modifies table_1 based on input parameters from a row in table_2. Here's a simplified version of my problem:

f:{[table_1; stk; jts; bidf;i]
  / Modify table_1 based on a row from table_2
  / Logic to modify table_1 based on line
  table_1
}

/ Initialize table_1 and table_2
table_1: ([] col1:(); col2:())
line_table: ([] param1: 1 2 3; param2: `a`b`c)

/ Apply the function on each row of table_2
result: @[table_1;;{f[x; stk; jts; bidf; y]}] each til count table_2

However, result only gives me a printout of the function calls, rather than the modified table_1. I initially tried applying the function on the whole table directly, but it only works when iterating over indices.

How can I correctly apply this function to modify table_1 for each row in table_2?


Solution

  • A couple of ways to approach it, one might be to use an iterator

    q)table_1: ([] col1:"j"$(); col2:`$())
    q)line_table: ([] param1: 1 2 3; param2: `a`b`c)
    q)f:{$[`b=y`param2;x upsert value @[y;`param1;10*];x upsert value y]}
    q)
    q)f/[table_1;line_table]
    col1 col2
    ---------
    1    a
    20   b
    3    c
    

    Or if you're happy to make changes globally within the function

    q)f:{$[`b=y`param2;x insert value @[y;`param1;10*];x insert value y]}
    q)f[`table_1]each line_table;
    

    Or if you want each column to be parameterised

    q)f:{$[`b=z;x insert(10*y;z);x insert(y;z)]}
    q)exec f'[`table_1;param1;param2]from line_table;