According to the Help
lhs->rhs evaluates rhs immediately.
How to understand the output of the following code?
ClearAll@x;
{1, 3.5} /. x_?IntegerQ -> {x}
Output is
{{1},3.5}
Since Mathematica
evaluate the rhs immediately, I think the “correct” output should be this
{{x},3.5}
And of course, if x has OwnValues
, the output will be changed.
x=”why”;
{1, 3.5} /. x_?IntegerQ -> {x}
Output is
{{"why"},3.5}
As expected.
In my opinion, the two examples expose the contradictions.
In the first one, Rule
behaves like RuleDelayed
; it relates the local x with global x. (The color of the two variables in front-end tells me this.) But in the second one, Rule
makes a clear distinction between the local and global.
(There are also something similar between Set
and SetDelayed
)
Why does this happen? Did I misunderstand the mechanism?
Update
What I'm really confusing is Why sometimes Mathematica does not distinguish the global x and the local x in Rule.
Solution
As Aky has metioned in his comments and answer. The documentiation says,
Symbols that occur as pattern names in lhs are treated as local to the rule. This is true when the symbols appear on the right-hand side of
/;
conditions in lhs , and when the symbols appear anywhere in rhs , even inside other scoping constructs.
So if x
doesn't have OwnValues
, then the Head
of x
is Symbol
and the name of x is the same as pattern name, as the documentation said , Mathematica will treat the two 'x's as the same. If x
has OwnValues
,take x=y
for example, (Head
of y
is also Symbol
) Even if x
(actually y) is Symbol
, the "name" of x is y which is different from the pattern name.
So in the following case,
x=y;
{1,3.5}/.x_?IntegerQ->{x}
Mathematica will return {{y},3.5}
not {{1},3.5}
.
Thanks for everyone's attention:)
DownValues
toOwnValues
asx = "why"
sets anOwnValue
not aDownValue
. $\endgroup$:>
will behave as expected, but I just want to figure out the mechanism of->
. $\endgroup$