3

I have found a strange issue in q, a possible bug I suppose. I have defined a simple function that returns a float, given a date as input:

give_dummy:{[the_date] 
   /// give_dummy[2013.05.10]  // <- if u wanna test
   :$[ the_date > 2013.01.01 ; 0.001 ; 0.002] ;
 }

It works without problems if called stand-alone:

q)give_dummy[2013.05.10]
0.001

Nevertheless, if I try to call it in a query I get an error:

q)select  give_dummy[date] from tab where sym = sec, i >= first_i  , i < 4000
'type

If I simplify the function to just return the input date (identity function), it works in the query. If I simplify the function to just return a float, without comparing the dates, it works in the query. The problem arises when I USE the input date to compare it in the if-statement: $[ the_date > 2013.01.01 ; 0.001 ; 0.002]

The same happens if I re-define the function taking a float as input, instead than a date, and then I try to give the price as input in the query:

 give_dummy:{[the_price] 
    /// give_dummy[12]  // <- if u wanna test
   :$[ the_price > 20 ; 0.001 ; 0.002] ;
 }
 q) give_dummy[12]
 0.002
 q)select  give_dummy[price] from tab where sym = sec, i >= first_i  , i < 4000
 'type

Do you have any idea of why this happens? I tried everything. Thanks Marco

chrisaycock
  • 36,470
  • 14
  • 88
  • 125
Marco Mene
  • 397
  • 2
  • 6
  • 11
  • I add that if I try to insert a trivial if-statement in a query, id doesn't work: select ($[1>0;1;0]),date,price,volume from tab where sym = sec 'rank – Marco Mene May 29 '13 at 12:17
  • If I use the ?[;;] statement, instead of the $[;;] one. It works.. O_o – Marco Mene May 29 '13 at 12:28

1 Answers1

4

You need to either:

select give_dummy each date from tab where ...

Or:

give_dummy:{[the_date] :?[ the_date > 2013.01.01 ; 0.001 ; 0.002]; }
select give_dummy[date] from tab where ...

? is the vector conditional. See here for more details: http://code.kx.com/q4m3/10_Execution_Control/

Thomas Smyth - Treliant
  • 4,993
  • 6
  • 25
  • 36
mnestor
  • 319
  • 1
  • 3
  • Thanks! I had already found out that with the ? it works. So the conclusion is that I have to consider each column selected in a query as a vector, when I use it in a function, and not the function as acting on single entries.. I'll keep in mind – Marco Mene May 29 '13 at 15:09
  • There is no need for the `:` You could just have the function be `give_dummy:{[the_date] ?[the_date>2013.01.01;0.001;0.002]}` as long as you omit the last `;`, which otherwise suppresses the output As a side note, columns shouldn't be considered vectors, they ARE vectors. It is clear to see when defining a table `([] c1:`a`b`c; c2:1 2 3)` c1 and c2 are both simple vectors (one of symbols and the other of ints). Internalizing this will make life a lot easier and your code a lot clearer. – JPC Aug 13 '13 at 21:03