Search code examples
kdb

call function with multiple value kdb\q


I have a function declaration:

func:{[id;time] select last synp from synp_t where instr_id = id, tp_time < time}

where instr_id has type i and tp_time has type v.

For example, func[8;05:00:11] works fine and gives me value 17.55.

However, if I try func[8 1;05:00:11 07:10:59], I get:

'length ERROR: incompatible lengths (different lengths of operands for synchronized operation or table columns lengths are not the same

What I want to get is, for example, 17.55 9.66.

Same error will pop up as well if I do select res:func_demo[id;time]from tab, where tab is table with two column of instr_id and tp_time.

I guess enlist could possibly resolve the problem, but I don't know exactly how to use it. How could I fix this issue?


Solution

  • I'll recommend using aj to get the results, looking at your query it looks like you want the last price for the given id and smaller than the input time.

    q)func:{[id;time] aj[`instr_id`tp_time; ([] instr_id:id;tp_time: time);synp_t]}
    q)func[1 1 2;05:00:11 07:10:59 10:10:00]
    

    with each-both you are calling the function n times and selecting the data n times. aj is one of the powerful features Kdb provides for the asof prices.

    Actually, you don't need func function, you can directly get the results using aj.

    aj[`instr_id`tp_time; update instr_id:id, tp_time: time from tab;synp_t]