1

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.

egor7
  • 4,678
  • 7
  • 31
  • 55

1 Answers1

3

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.

Igor Korkhov
  • 8,283
  • 1
  • 26
  • 31
  • Tricky thing, a temporary vector that is created implicitly. Now it's clear why it works with `x:1` or with the same length vector `x:1 2 3` initialized previously. Great thanks! – egor7 May 03 '20 at 13:59
  • Please take my words about implicit creation of a vector with a pinch of salt. Kdb may or may not use various optimisations depending on operators. I don't know what happens *internally* when kdb needs to extend an atom to a list but it *behaves* as if a temp object is created. – Igor Korkhov May 03 '20 at 15:17
  • Totally agree - kdb could be very tricky in its optimizations. With memory profiling I hope it could be possible to indirectly confirm some of assumptions. But a question how to profile q programs is still open for me. – egor7 May 03 '20 at 16:00