Variable visibility when defining functions inside functions with q
Asked Answered
G

2

6

I am defining a function that contains another function inside:

find_badTicks:{ [tab;sec] // dummy function, for debug..
  Ndays: 10i ;
  dates: select distinct date from tab where sym = sec ;
  closures: select last price by date from tab where sym = sec ;
  returns: 1 _ select ( (price)-(prev price) )%(prev price)  from closures  ;
  stdevs: {[x;y] sd[ (Ndays-1)#y _ x ] } [ (returns)[;`price] ] each til ( (1 - (Ndays-1)) + count (returns)[;`price] ) ;
  :tab 
}

If I compile the function it works. If I run the lines one by one it works. However, if I try to call the function I get an error:

  q)testTab: find_badTicks [testTab ; `ENI.IM.Equity] ;
  'Ndays

If I remove Ndays in the nested function, writing explicitly 10, it works. Si I guess it's a problem of local variable visibility inside nested functions, in function execution: i.e. the nested function cannot see Ndays, which is a local variable of the function find_badTicks. Do you know how I can make Ndays visible inside inner functions? Thanks Marco

Gyrfalcon answered 30/5, 2013 at 8:2 Comment(1)
I've solved the issue re-defining the inner functions to take as input parameters the lvariables. In this case Ndays: stdevs: {[Ndays;x;y] sd[ (Ndays-1)#y _ x ] } [ Ndays ; (returns)[;price] ] each til ( (1 - (Ndays-1)) + count (returns)[;price] ) ;Gyrfalcon
M
4

@user2242865 is right. Lexical scoping in q is somewhat limited. You can only reference globals (with the appropriate namespace) and variables defined within the function itself, but not anything defined outside of its immediate context.

Maharanee answered 4/6, 2013 at 14:40 Comment(0)
O
4

From within a function you can refer to variables defined within that function, and also to globally defined variables (either in the main namespace or others).

Variables defined in intermediate functions are not visible within another function, and will cause a value error - as you saw.

Orta answered 30/5, 2013 at 17:21 Comment(0)
M
4

@user2242865 is right. Lexical scoping in q is somewhat limited. You can only reference globals (with the appropriate namespace) and variables defined within the function itself, but not anything defined outside of its immediate context.

Maharanee answered 4/6, 2013 at 14:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.