KDB: apply dyadic function across two lists

时光总嘲笑我的痴心妄想 提交于 2019-12-01 07:39:37

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

raze F ./: xList cross yList

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

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

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
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!