Exists function in q/kdb
Asked Answered
M

4

9

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.

Manfred answered 23/7, 2014 at 23:4 Comment(0)
H
11
q)doesExist:{x~key x}
q)a:2
q)doesExist`a
    1b
q)doesExist`b
    0b
Heredia answered 24/7, 2014 at 15:27 Comment(2)
This may or may not work, depending on the type of item referenced by x. For example, if value x is a keyed table, key x will return a table, not the symbol x.Meat
Thank you! this is an extremely useful command also for checking whether a table exists!Bookmaker
G
7
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

Guardhouse answered 24/7, 2014 at 12:55 Comment(0)
F
6

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
Furore answered 1/2, 2015 at 12:5 Comment(2)
Nice addition! This is very handy.Lyndel
But not if its an empty dictionaryDeckert
D
0

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];
 };
Detrition answered 7/11, 2023 at 17:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.