Search code examples
kdb+k

Applying adverb to colon operator


Please help me with colon : operator, I'm stuck on how it works. It works as an assignment, assignment through x+:1, global assignment/view ::, I/O 0:, 1:, to return value from the middle of the function :r, and to get an unary form of operator #:.

But what happend if one apply an adverb to it? I tried this way:

$ q
KDB+ 3.6 2019.04.02 Copyright (C) 1993-2019 Kx Systems
q)(+')[100;2 3 4]
102 103 104
q)(:')[x;2 3 4]
'x
  [0]  (:')[x;2 3 4]
            ^
q)(:')[100;2 3 4]
2 3 4

I expect evaluations in order: x:2, then x:3, then x:4. To get x:4 as a result. But I've got an error. And also :' works with a number 100 for some unknown reason.

What :' is actually doing?

q)parse "(:')[100;2 3 4]"
(';:)
100
2 3 4

Parsing didn't shed much light to me, so I'm asking for your help.


Solution

  • When modified by an iterator (also known as an adverb in q speak), : behaves just like any other binary operator. In your example

    q)(:')[100;2 3 4]
    2 3 4
    

    an atom 100 is extended to a conformant list 100 100 100 and then : is applied to elements of the two lists pairwise. The final result is returned. It might look confusing (: tries to modify a constant value, really?) but if you compare this to any other binary operator and notice that they never modify their operands but return a result of expression everything should click into place.

    For example, compare

    q)+'[100; 2 3 4]
    102 103 104
    

    and

    q)(:')[100;2 3 4]
    2 3 4
    

    In both cases an a temporary vector 100 100 100 is created implicitly and an operator is applied to it and 2 3 4. So the former is semantically equivalent to

    (t[0]+2;t[1]+2;t[2]+4)
    

    and the latter to

    (t[0]:2;t[1]:2;t[2]:4)
    

    where t is that temporary vector.

    This explains why (:')[x;2 3 4] gives an error -- if x doesn't exist kdb can't extend it to a list.