expression manipulation - What are the scoping rules for function parameters shadowing System` symbols?
Here are some very contrived code snippets, highly unlikely to appear in real code, but still I am curious why they behave like this:
Function[List, {1, 2, 3}][Hold]
(* Hold[1, 2, 3] *)
Function[Function, Function[Slot[1]]][Hold]
(* Hold[#1] *)
Function[Slot, Function[Slot[1]]][Hold]
(* Hold[1] & *)
Function[Function, Function[x, 1]][Hold]
(* Function[x, 1] *) (* Why not Hold[x, 1]? *)
{Function[Null, Null][1]}
(* {Null} *) (* Why not {1}? *)
I think I understand the first 3 cases.
Could you please explain the last 2 results?
Answer
For the first puzzle, I can only guess. The idea is that Function
with named variables is a true lexical scoping construct, in that it cares about the possible name collisions inside the inner scoping constructs, including another Function
-s (this is where it is different from Slot
- based functions, which are not like that. The price to pay is that Slot
-based functions can not be non-trivially nested). This name collision analysis and variable renaming is happening before the variable binding - this is important. Another important point is that generally the renaming is excessive - it is often performed even when not strictly necessary.
So, when you enter
Function[Function, Function[x, 1]][Hold]
the following should (according to my guess) roughly happen:
- The inner scoping constructs are analyzed. The named function
Function[x,1]
is detected. - The
Function
variable inFunction[Function,...]
is renamed (just in case). We end up with something likeFunction[$Function,Function[x,1]][Hold]
. - The variable binding is performed. Effectively we have now a constant function that returns
Function[x,1]
regardless of the input. This happens because the renaming ofFunction
(as a variable) to$Function
happened before the binding stage, and therefore did not affect the body (Function[x,1]
). - The resulting function is called on
Hold
, and returnsFunction[x,1]
, as it now should.
Now, here is how you can fool the detection mechanism (just one way out of many):
Function[Function,Function@@Hold[x,1]][Hold]
(* Hold[x,1] *)
Now the inner Function
is not detected as a scoping construct, renaming is not performed, then the Function
as a variable is lexically bound to the Function
in the body, and we get the expected result.
The second case is simpler. Note that there is an undocumented way to enter Slot
-based functions, such as:
Function[Null, body]
which is interpreted as body&
. This form is needed to be able to define Slot
-based pure functions with attributes, such as
Function[Null, #=1,HoldAll]
Now, in your case, your function is interpreted as Null&
, so it will return Null
on all inputs.
Comments
Post a Comment