Search code examples
kdb

How do I assign the values of a dictionary to the current scope?


Let's say I have a dictionary:

x:(`a`b`c)!(1 2 3)

What are more elegant ways of doing:

a:x`a; b:x`b; c:x`c

I'm looking at both destructuring methods, of the form (a;b;c):value x

and functional methods, of the form : each x (where : refers to the assignment operator).


Solution

  • Is your goal in a local scope only?

       q){[x]
         someCode x;
         (a;b;c);/ Now exist as locals
        } (`a`b`c)!(1 2 3)
       q)a / Global scope not effected.
         'a
    

    It's not something the language caters for.

    + Functions have limits to the number of local variables:

    https://code.kx.com/q/basics/function-notation/#variables-and-constants

    Running value on a function shows information including a list of locals.

    Knowing this in advance likely could help with: (my guesses)

    1. Scope .i.e the interpreter knowing the difference between the local x and a possible global x
    2. Performance
    3. The debugger

    https://code.kx.com/q/ref/value/#lambda

    q)func:{[x;y] a:1;b:2;c:3}
    
    q)value func
    0x0d030902a0030a02a1030b0004
    `x`y
    `a`b`c
    ,`
    2
    3
    14 0 13 0 18 0 17 0 22 0 21 5 5
    "..func"
    ""
    -1
    "{[x;y] a:1;b:2;c:3}"
    

    If you mean in the global scope use set

    q)x:(`a`b`c)!(1 2 3)
    q)set'[key x;value x]
    `a`b`c
    q)a
    1