Search code examples
kdb+k

Create single-row table by enlisting only one column


In a wp/rt-tick I saw a technique to create a single-row table by giving enlisted element to only one column:

/single-row update for the trade table
(`upd;
  `trade;
  ([]time:enlist 0D10:30:59.5; / <- enlist is only here
    sym:`IBM.N;
    price:183.1;
    size:1000))

Is this a standard approach? Should we rely on this feature, and are there other cases when the same works?


Solution

  • Table columns can only be made of lists. For a single row table, only one column must be a list, as the others will automatically be promoted to lists in this case. Atoms being promoted to lists is a common feature in q, for example the below two statements give the same result, as the atom 1 is extended to match the length of the list

    update col2:3#1 from ([]col1:1 2 3)
    update col2:1 from ([]col1:1 2 3)
    

    We can see the other columns have been promoted to lists from,

    q)type each value flip ([]col1:enlist 1;col2:2)
    7 7h
    

    The type of the col2 values is 7h as opposed to -7h.

    Enlist is a standard way to achieve this, but you can also use 1#, or join the empty list on to an element, which is often done in practice to create one element lists

    ([]col1:(),1;col2:2)
    ([]col1:1#1;col2:2)
    

    To create a table from a dictionary which has atoms as values, you can also use enlist, as flip will fail with a rank error

    enlist `a`b!1 2    /works
    flip `a`b!1 2      /fails
    flip `a`b!(1;2,()) /works
    

    Single row tables can obviously be achieved by using 1# on an already created table, but to create a single row table from scratch the enlist method is standard, and can be relied on.

    You can initialise a zero row table using the empty list

    ([]col1:())