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.

Viriya
  • 167
  • 3
  • 7

3 Answers3

11
q)doesExist:{x~key x}
q)a:2
q)doesExist`a
    1b
q)doesExist`b
    0b
MdSalih
  • 1,978
  • 10
  • 16
  • 3
    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. – pamphlet Sep 11 '14 at 15:39
  • Thank you! this is an extremely useful command also for checking whether a table exists! – SkyWalker May 29 '15 at 08:12
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

Manish Patel
  • 4,411
  • 4
  • 25
  • 48
5

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