Skip to main content

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 in Function[Function,...] is renamed (just in case). We end up with something like Function[$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 of Function (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 returns Function[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

Popular posts from this blog

functions - Get leading series expansion term?

Given a function f[x] , I would like to have a function leadingSeries that returns just the leading term in the series around x=0 . For example: leadingSeries[(1/x + 2)/(4 + 1/x^2 + x)] x and leadingSeries[(1/x + 2 + (1 - 1/x^3)/4)/(4 + x)] -(1/(16 x^3)) Is there such a function in Mathematica? Or maybe one can implement it efficiently? EDIT I finally went with the following implementation, based on Carl Woll 's answer: lds[ex_,x_]:=( (ex/.x->(x+O[x]^2))/.SeriesData[U_,Z_,L_List,Mi_,Ma_,De_]:>SeriesData[U,Z,{L[[1]]},Mi,Mi+1,De]//Quiet//Normal) The advantage is, that this one also properly works with functions whose leading term is a constant: lds[Exp[x],x] 1 Answer Update 1 Updated to eliminate SeriesData and to not return additional terms Perhaps you could use: leadingSeries[expr_, x_] := Normal[expr /. x->(x+O[x]^2) /. a_List :> Take[a, 1]] Then for your examples: leadingSeries[(1/x + 2)/(4 + 1/x^2 + x), x] leadingSeries[Exp[x], x] leadingSeries[(1/x + 2 + (1 - 1/x...

How to thread a list

I have data in format data = {{a1, a2}, {b1, b2}, {c1, c2}, {d1, d2}} Tableform: I want to thread it to : tdata = {{{a1, b1}, {a2, b2}}, {{a1, c1}, {a2, c2}}, {{a1, d1}, {a2, d2}}} Tableform: And I would like to do better then pseudofunction[n_] := Transpose[{data2[[1]], data2[[n]]}]; SetAttributes[pseudofunction, Listable]; Range[2, 4] // pseudofunction Here is my benchmark data, where data3 is normal sample of real data. data3 = Drop[ExcelWorkBook[[Column1 ;; Column4]], None, 1]; data2 = {a #, b #, c #, d #} & /@ Range[1, 10^5]; data = RandomReal[{0, 1}, {10^6, 4}]; Here is my benchmark code kptnw[list_] := Transpose[{Table[First@#, {Length@# - 1}], Rest@#}, {3, 1, 2}] &@list kptnw2[list_] := Transpose[{ConstantArray[First@#, Length@# - 1], Rest@#}, {3, 1, 2}] &@list OleksandrR[list_] := Flatten[Outer[List, List@First[list], Rest[list], 1], {{2}, {1, 4}}] paradox2[list_] := Partition[Riffle[list[[1]], #], 2] & /@ Drop[list, 1] RM[list_] := FoldList[Transpose[{First@li...

front end - keyboard shortcut to invoke Insert new matrix

I frequently need to type in some matrices, and the menu command Insert > Table/Matrix > New... allows matrices with lines drawn between columns and rows, which is very helpful. I would like to make a keyboard shortcut for it, but cannot find the relevant frontend token command (4209405) for it. Since the FullForm[] and InputForm[] of matrices with lines drawn between rows and columns is the same as those without lines, it's hard to do this via 3rd party system-wide text expanders (e.g. autohotkey or atext on mac). How does one assign a keyboard shortcut for the menu item Insert > Table/Matrix > New... , preferably using only mathematica? Thanks! Answer In the MenuSetup.tr (for linux located in the $InstallationDirectory/SystemFiles/FrontEnd/TextResources/X/ directory), I changed the line MenuItem["&New...", "CreateGridBoxDialog"] to read MenuItem["&New...", "CreateGridBoxDialog", MenuKey["m", Modifiers-...