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


We can also define it as a list of rules by


Indeed, when we evaluate the followings


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


However, if we evaluate the following:


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:


(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.

  • 1
    $\begingroup$ 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. $\endgroup$ – george2079 Jun 14 '17 at 12:26
  • $\begingroup$ Anticipating future interaction with Mathematica you may find this question of interest: (69590) $\endgroup$ – Mr.Wizard Jun 14 '17 at 12:35
  • $\begingroup$ Upon replacing -> with :>, now it works! Thank you! Sorry for being new to Mathematica programming... $\endgroup$ – Mauri Ericson Sombowadile Jun 14 '17 at 13:48
  • $\begingroup$ 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? $\endgroup$ – Mauri Ericson Sombowadile Jun 14 '17 at 13:52
  • $\begingroup$ @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) $\endgroup$ – Mr.Wizard Jun 14 '17 at 20:25