Struggling to understand two statements

https://learninghub.kx.com/forums/topic/struggling-to-understand-two-statements

I am studying the official example code from here: https://github.com/kxcontrib/websocket/blob/master/AppendixB/pubsub.q and after thinking for a while I still don’t understand what exactly a few lines do:

 

trade:flip `time`sym`price`size!"nsfi"$:(); 
subs:2!flip `handle`func`params!"is*"$:();

 

The following is the things I already know:

  1. Q generally read from right to left;
  2. We assign the results to trade/subs;
  3. flip is used to transpose an input
  4. `time `sym are "symbols"
  5. "nsfi" is used to specify the type of columns
Then here comes the things I don't know...
  1. What does $:() do?
  2. How about the bang between symbols and "nsfi"?
  3. What does 2!flip mean?..
 

Thanks!

Yes, it is creating a table schema of specific type for the cols. So when you are manipulating the table, it throws a type error if the type is not of that defined in the schema.

https://code.kx.com/q/ref/insert/#type

More information here: https://code.kx.com/q4m3/8_Tables/#82-empty-tables-and-schema

  1. : represents each left and $ is casting.

https://code.kx.com/q/ref/maps/#each-left-and-each-right

https://code.kx.com/q4m3/7_Transforming_Data/#72-cast

So for the line “nsfi”$:() it is actually casting an empty list with every type on the left (hence each left) so that it creates a list of that specific type. You can use .Q.s1 to view the string representation of the object.

https://code.kx.com/q/ref/dotq/#qs1-string-representation

q)"n"$() 
`timespan$() 
q).Q.s1 "nsfi"$:() 
"(`timespan$();`symbol$();`float$();`int$())"
  1. bang (!) is used to create a dictionay with the keys on the left and values on the right with the correct length of list. Then flipping a dict will turn it into a tbl.

https://code.kx.com/q/ref/dict/

https://code.kx.com/q/kb/faq/#flip-a-column-dictionary

  1. 2! enkeys the table by the first 2 cols.

https://code.kx.com/q/ref/enkey/

Hope this helps!

Hi mauricelim, thanks for the quick help! Can I say that the big picture is to define two empty tables called trade and subs here?