# Problem in evaluating nested anonymous functions [duplicate]

It seems that I have found a bug (or a fundamental problem in the design of the programming language of Mathematica) with functions defined as rules. Define the function g as g(1)=2 and g(2)=1. We can do it by

g[1]:=2
g[2]:=1


We can also define it as a list of rules by

g:=Replace[#,{1->2,2->1}]&


Indeed, when we evaluate the followings

g[1]
g[2]


after defining g using any of the two ways given above, we get

2
1


However, if we evaluate the following:

Replace[#,{{x_,y_}->{y,g[x]}}]&/@{{1,a},{2,b}}


the first definition of g leads to the following result:

{{a, 2}, {b, 1}}


while the second definition leads to the following (incorrect) result:

{{a, 1}, {b, 2}}


It seems that Mathematica gets confused when handling nested anonymous function. That is, the above Map expression is first transformed by substituting for g:

Replace[#,{{x_,y_}->{y,(Replace[#,{1->2,2->1}]&)[x]}}]&/@{{1,a},{2,b}}


(whose evaluation indeed gives the incorrect result above) and then Mathematica doesn't understand that the inner # and the outer # should be treated differently, because they belong to different anonymous functions.

Of course, this is undesirable for a functional programming language, and thus I think this is a bug.

• in the second case the g[x] is first evaluated to x (as the symbol x is neither 1 or 2 ) before the outer Replace function even gets applied.. You can fix with RuleDelayed : Replace[#,{{x_,y_} :> {y,g[x]}}]& Its not a bug, just a matter of understanding order of evaluation. – george2079 Jun 14 '17 at 12:26
• Anticipating future interaction with Mathematica you may find this question of interest: (69590) – Mr.Wizard Jun 14 '17 at 12:35
• Upon replacing -> with :>, now it works! Thank you! Sorry for being new to Mathematica programming... – Mauri Ericson Sombowadile Jun 14 '17 at 13:48
• I'm sorry for also being new to StackExchange... Why was my question marked as an "exact" duplicate? Is there a way to see that existing question? – Mauri Ericson Sombowadile Jun 14 '17 at 13:52
• @Mauri No need to apologize for either situation. :-) Please do try to read the documentation on your own and/or other resources listed here, but we all need help from time to time and that's what this site is for after all. Your question was clear and well written and that is exactly what we need here. The issue is nontrivial even if it is a common one with an easy solution. (continued) – Mr.Wizard Jun 14 '17 at 20:25