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.
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.
q)doesExist:{x~key x}
q)a:2
q)doesExist`a
1b
q)doesExist`b
0b
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
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
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];
};
© 2022 - 2024 — McMap. All rights reserved.
value x
is a keyed table,key x
will return a table, not the symbol x. – Meat