Home › Forums › kdb+ › How can i understand the code below › Re: How can i understand the code below
-
A lot to unpack here but lets break it down.
.quantQ.IO.SAVEsPLAYtAB:{[tabPath;pvar;table] // tabPath -- path where to store the table // pvar -- variable to sort and index on for fast querying // table -- name of the table to save @[;pvar;`p#] pvar xasc (`sv (tabPath; ` ; table; `)) set .Q.en[tabPath] get table}
The three arguments are all symbols: respectively a file path, a table column name, and a table name. (It were best to state that in the comments.) Ill come to how we see that.
Lets set up a small table so we can watch what happens.
q)atable:([]ab:til 3;cd:`x`y`z;de:string`tom`**bleep**`harry) q)get `atable ab cd de ------------- 0 x "tom" 1 y "**bleep**" 2 z "harry" q)tabPath:`:path/to/table
The argument to
get
is the name of the table; the result is the table, which becomes the argument to.Q.en[tabPath]
.That is, binary
.Q.en
is projected ontotabPath
to make a unary. The effect is the same as if we had assigned the result ofget table
tot
and then called.Q.en[tabPath;t]
. What.Q.en
does is too extensive to discuss here but you can read up on it. The work it does is side effects; its result is the table.Which then gets passed as the right argument to
set
, which is quite a workhorse. Its syntax is overloaded, so we examine its left argument(` sv (tabPath; ` ; table; ` ) )
to see howset
is used here.The
sv
keyword is being called in this form, which is how we know thattabPath
andtable
must both be symbols. It returns a filehandle symbol as the left argument ofset
.From this we see that
set
is being called with syntaxtil set y // serialize y to fil
. It returns its left argument: the symbol filepath to which it has written the table; this becomes the right argument toxasc
, which will sort the table on disc by the column named bypvar
.The result is again a reference to the table, which becomes the argument to
@[;pvar;`p#]
, a projection of Apply At onto second and third argumentspvar
and`p#
. The effect is to set the partitioned attribute on the column named bypvar
. The result of Apply At is the table reference. Your code uses Explicit return:
to make that the result of.quantQ.IO.SAVEsPLAYtAB
. That is unnecessary: a functions result is the result of evaluating its last (here the single) expression.