Search code examples
kdb

KDB '.' operator


The . operator in the simplest form is used to index a list. How would you explain its use in english in this code?

if[x~"last";upd:{[t;x].[t;();,;r::select by sym from x]}]

I also don't understand the empty list and the :: operator in this line, but maybe they will make sense once the . is cleared up.


Solution

  • In plain english I would explain it as: modify the table t at all () indices by applying the append/comma function with the value r.

    First consider a few simpler cases of @:

    q)l:3 5 7 9
    q)l:1.1 2.2 3.3
    q)@[l; 0 2; +; 10]
    11.1 2.2 13.3
    
    q)d:`p`o`i!4.4 5.5 6.6
    q)@[d; `p`i; -; 10]
    p| -5.6
    o| 5.5
    i| -3.4
    

    As you can see the format is @[dataStructure; indices; function; y-arg]

    means to the dataStructure at indices apply the function with the given y-arguments. Notice for the list l the indices 0 2 meant index both 0 and 2 at the topmost level. There's no way using @ to index at depth. e.g. given matrix m:(1 2 3; 4 5 6; 7 8 9) how can we use this format to modify just the values 4 and 6?

    q)/ @ indexes repeatedly at topmost level
    q)/ definitely not what we want
    q)@[m;(1;0 2);+;100]
    101 102 103
    104 105 106
    107 108 109
    
    q)/ **. indexes into the data structure**
    
    q).[m;1 2;+;100]
    1 2 3
    4 5 106
    7 8 9
    
    q).[m;(1;0 2);+;100]
    1   2 3
    104 5 106
    7   8 9
    

    Lastly the empty list () is a short way of saying, apply to all indices:

    q).[m;();+;100]
    101 102 103
    104 105 106
    107 108 109