关于K语言新版本变量作用域传播失效及是否禁用的咨询
{[k]{x*x+k}k}3 fail in kdb+ 3.6? Great question—this comes down to a deliberate change in how function scoping works between early K implementations and modern kdb+. Let's break it down:
First, your working example {[k]{x*x}k}3 works fine because the inner function {x*x} only uses its implicit parameter x—which gets set to the value of k (3) when you call the inner function with k. No external variables are being referenced here, so no issues.
The error in {[k]{x*x+k}k}3 happens because:
- Early K (like K2/K3) supported lexical closures: inner functions could automatically "see" variables from the outer function's scope, even if they weren't passed as explicit parameters. That's why the old example you mentioned worked.
- Modern kdb+ (starting with K4, including 3.6) tightened up scoping rules for performance and clarity. Now, inner functions only have access to:
- Their own explicit or implicit parameters
- Global variables (prefixed with
., e.g.,.myGlobal) - Variables explicitly passed to them as arguments
In your failing code, the inner function {x*x+k} tries to reference k, but k is only a parameter of the outer function—not a global variable, nor a parameter of the inner function. Since modern kdb+ doesn't automatically pull variables from the outer scope into the inner one, it throws a 'k error because it can't find that variable.
Does modern Q block this kind of scope propagation?
Yep, Q (the high-level language built on kdb+) follows exactly the same scoping rules. Automatic lexical closure-style scope propagation isn't allowed by default.
How to get the old behavior in modern kdb+/Q?
If you need an inner function to use a variable from the outer scope, you have to pass it explicitly as a parameter. For example:
{[k]{[x;k] x*x + k}[k;k]}3 // Returns 12 (3*3+3)
Or, if you want to define the inner function first and reuse it with the outer variable:
{[k] f:{[x;k] x*x + k}; f[k;k]}3 // Same result
Steer clear of global variables for this (like setting .k:k in the outer function) unless you have no other option—globals can lead to messy, hard-to-debug side effects.
内容的提问来源于stack exchange,提问作者egor7

