Variable visibility when defining functions inside functions with q

I define a function containing 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 a function, it works. If I run the lines one by one, it works. However, if I try to call a function, I get an error message:

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

If I remove Ndays in a nested function by writing explicitly 10, it works. Si I assume that the problem of local visibility of variables inside nested functions when executing a function: i.e. The nested function cannot see Ndays, which is the local variable of the find_badTicks function. Do you know how I can make Ndays visible inside internal functions? thanks Marco

+4
source share
2 answers

@ user2242865 is correct. The lexical scale in q is somewhat limited. You can only refer to global variables (with the appropriate namespace) and variables defined within the function itself, but not everything that is specified outside its immediate context.

+2
source

Inside a function, you can refer to variables defined inside this function, as well as globally defined variables (either in the main namespace or in others).

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

+2
source

Source: https://habr.com/ru/post/1483534/


All Articles