KDB: apply dyadic function across two lists

2019-02-18 05:10发布

Consider a function F[x;y] that generates a table. I also have two lists; xList:[x1;x2;x3] and yList:[y1;y2;y3]. What is the best way to do a simple comma join of F[x1;y1],F[x1;y2],F[x1;y3],F[x2;y1],..., thereby producing one large table?

标签: function kdb
4条回答
贪生不怕死
2楼-- · 2019-02-18 05:19

You have asked for the cross product of your argument lists, so the correct answer is

raze F ./: xList cross yList
查看更多
一夜七次
3楼-- · 2019-02-18 05:25

Depending on what you are doing, you might want to look into having your function operate on the entire list of x and the entire list of y and return a table, rather than on each pair and then return a list of tables which has to get razed. The performance impact can be considerable, for example see below

q)g:{x?y} //your core operation
q)//this takes each pair of x,y, performs an operation and returns a table for each 
q)//which must then be flattened with raze
q)fm:{flip `x`y`res!(x;y; enlist g[x;y])}  
q)//this takes all x, y at once and returns one table
q)f:{flip `x`y`res!(x;y;g'[x;y])} 
q)//let's set a seed to compare answers
q)\S 1
q)\ts do[10000;rm:raze fm'[x;y]]
76 2400j
q)\S 1
q)\ts do[10000;r:f[x;y]]
22 2176j
q)rm~r
1b
查看更多
干净又极端
4楼-- · 2019-02-18 05:34

Setup our example

q)f:{([] total:enlist x+y; x:enlist x; y:enlist y)}
q)x:1 2 3
q)y:4 5 6

Demonstrate F[x1;y1]

q)f[1;4]
total x y
---------
5     1 4
q)f[2;5]
total x y
---------
7     2 5

Use the multi-valent apply operator together with each' to apply to each pair of arguments.

q)raze .'[f;flip (x;y)]
total x y
---------
5     1 4
7     2 5
9     3 6
查看更多
相关推荐>>
5楼-- · 2019-02-18 05:39

Another way to achieve it using each-both :

x: 1 2 3
y: 4 5 6
f:{x+y}
f2:{ a:flip x cross y ; f'[a 0;a 1] }

f2[x;y]
5j, 6j, 7j, 6j, 7j, 8j, 7j, 8j, 9j
查看更多
登录 后发表回答