如何使kdb+/q代码更加简短?
Code Golf(代码高尔夫)是一种计算机编程竞赛,在该竞赛中,参与者努力用尽可能短的源代码实现特定算法。作为一种紧凑简洁的语言,kdb+/q非常适合于此。通常,kdb+有可能在一行代码中实现一个算法,而其他语言根本无法实现。下面给出几个code golf的例子。
q)x:til 10
q)(count x)>
1b
q)count[x]>
1b
q)<count x
1b
q)k)<#x
1b
q)count each("(count x)>0";"count[x]>0";"0<count x")
11 10 9 4
q)x:2;type x:x,()
7h
q)x:2;typex,:()
7h
q)count each("x:x,()";"x,:()")
65
q)x:til 10
q)(count x)%2
5f
q).5*count x //丢掉0.5开头的0很重要
5f
q)k).5*#x
5f
q)reciprocal 10
.1
q)1%10
.1
q)dbl:2* //dbl是一个投影,2是固定参数
q)dbl 4 6 18
8 12 36
q)f:{x+3*y}
q)f[1;2 3 4]
7 10 13
q)f[1]2 3 4 //省略; 更简短
7 10 13
q)x:til 10
q)(0,floor .5*count x)_x
0 1 2 3 4
5 6 7 8 9
q)k)(0,_.5*#x)_x
0 1 2 3 4
5 6 7 8 9
q)2 0N#x
0 1 2 3 4
5 6 7 8 9
q)count each("(0,floor .5*count x)_x";"(0,_.5*#x)_x";"2 0N#x")
22 12 6
q)show trade:([]time:.z.p;sym:10?`AAPL`GOOG`IPM`JPM`GE;price:10?100.0;side:10?`B`S)
q)2#trade
time sym price side
----------------------------------------------------------
2021.01.03D08:15:36.712108000 GOOG 49.31835 B
2021.01.03D08:15:36.712108000 GOOG 19.59907 S
q)buy:select from trade where side=`B
q)sell:select from trade where side=`S
q)buy:delete from trade where trade in sell:select from trade where side=`S
q)buy:trade except sell:select from trade where side=`S
q)\ts:10000 buy:select from trade where side=`B;sell:select from trade where side=`S
35 1776
q)\ts:10000 buy:delete from trade where trade in sell:select from trade where side=`S
89 2192
q)\ts:10000buy:trade except sell:select from trade where side=`S
84 1328
q)delete from sell where([]time;sym)in select time,sym from buy
q)delete from sell where([]time;sym)in`time`sym#buy
q){?["+"=x;1;-1]}"++--+" // Vector conditional
1 1 -1 -1 1
q){("+-"!1 -1)x}"++--+" // Dictionary map
1 1 -1 -1 1
q){-1 1"+"=x}"++--+" // Conditional indexing
1 1 -1 -1 1
相关文章