q/kdb 中存在函数

问题描述 投票:0回答:4

我需要在 q/kdb 中编写一个函数,它接受一个变量 v,如果 v 是,则返回 1b 已定义,如果未定义则为 0b:

$ a:2
$ doesExist`a
1b
$ doesExist`b
0b

任何想法表示赞赏。

kdb
4个回答
11
投票
q)doesExist:{x~key x}
q)a:2
q)doesExist`a
    1b
q)doesExist`b
    0b

7
投票
key`.

将为您提供当前命名空间中的所有变量。

同样

key`.foo

将为您提供

.foo
命名空间中的所有变量。

延伸来说:

`a in key`.

会给你你想要的布尔值


6
投票

根据MdSalih的回答和小册子的评论,也许我们可以测试相反的情况。由于如果未定义变量,key 会输出一个空列表,因此我们应该对此进行测试,这可以帮助我们解决键控表问题。

q)AnswerToLifeUniverseAndEverything:42
q)doesExist:{not () ~ key x}
q)doesExist[`AnswerToLifeUniverseAndEverything]
1b
q)doesExist[`UltimateQuestionToLifeUniverseAndEverything]
0b

0
投票

根据@compassionate_badger的回答和@Helios的评论,我建议以下功能:

doesExistsGlobal:{[sym]
    if[-11h<>type sym;'"The input is not a symbol"];
    exists:not ()~key sym;
    if[exists;:exists];
    / Either sym does not exist, or value of sym is ()!()
    $[0b~@[value;sym;0b];:0b;:1b];
 };
© www.soinside.com 2019 - 2024. All rights reserved.