Viriya
Viriya

Reputation: 177

Exists function in q/kdb

I need to write a function in q/kdb which takes a variable v and returns 1b if v is defined and 0b if it is not:

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

Any ideas appreciated.

Upvotes: 9

Views: 8310

Answers (4)

L. Francis Cong
L. Francis Cong

Reputation: 359

Based on @compassionate_badger's answer and @Helios's comment, I suggest the following function:

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];
 };

Upvotes: 0

compassionate_badger
compassionate_badger

Reputation: 267

Based on MdSalih's answer and pamphlet's comment, perhaps we can test the opposite. Since key outputs an empty list if the variable is not defined, we should test for that, which gets us around the keyed table problem.

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

Upvotes: 6

MdSalih
MdSalih

Reputation: 1996

q)doesExist:{x~key x}
q)a:2
q)doesExist`a
    1b
q)doesExist`b
    0b

Upvotes: 11

Manish Patel
Manish Patel

Reputation: 4491

key`.

Will give you all the variables in the current namespace.

Similarly

key`.foo

Will give you all the variables in the .foo namespace.

By extension:

`a in key`.

Will give you the boolean you're after

Upvotes: 8

Related Questions