Search code examples
kdb

How can we use iterators in q to apply a list of functions to each of a list of arguments?


In q/kdb, we can apply a function to a number of arguments, as below:

f each (1;2;3)

We can also apply a defined argument to a list of functions:

flist: (f1:{x+y+z},f2:{x+y-z},f3:{x-y+z});
flist  .\: 1 2 3

What is the most efficient way to combine both of these- to apply every function in a list to each value in a list as parameters. For example, to apply 3 unary functions, f1, f2 and f3, to a list containing values 1, 2 and 3 (producing 9 calls).

Any help with this is much appreciated!


Solution

  • You can use the eachboth (') operator:

    q)f1:1+;f2:2+;f3:3+
    q)(f1;f2;f3) @' 10 20 30
    11 22 33
    

    or in the case of multi-argument functions,

    q)g1:+;g2:-;g3:*
    q)(g1;g2;g3) .' (2 1;3 2;2 2)
    3 1 4
    

    and if you want to apply each function to each value, you need to form a cross product first:

    q)(@/)each(f1;f2;f3) cross 10 20 30
    11 21 31 12 22 32 13 23 33