Optimize/Concise q kdb中的条件代码

Optimize/Concise the conditional code in q kdb

我有一个 table t,我必须根据它为变量 v 赋值。

q)t:([] sym:`goog`amzn; px:100 200);
q)v:$[count dv:exec distinct sym from t where px=101;dv;enlist`default]; 
/ return distinct syms in case of satisfied condition from t as return enlist symbol.

有没有办法使条件代码简洁?(通过删除临时变量 dv 或任何其他替代方法)

如果不想引入临时变量,请不要:

q)v:$[count v:exec distinct sym from t where px=100;v;enlist`default];

在单个表达式中多次重复使用一个变量是 q 中的常见做法。

或者您可以创建一个简单的函数,并在需要用单例列表替换空列表时使用它:

q)withDefault:{$[count y;y;enlist x]}
q)withDefault[`default] exec distinct sym from t where px > 100
,`amzn
q)withDefault[`default] exec distinct sym from t where px > 1000
,`default

您也可以只使用 if 而不是 if-else:

if[not count v:exec distinct sym from t where px=101;v:1#`default];