The mathematica front-end colors x
on the right hand side of x_ :> x
and f[x_] := x
but not with x_ -> x
and f[x_] = x
.
But, at least if x
is not defined at the time the replacement rule is created, the x
in the latter cases also refers to whatever matched the labeled pattern, e.g. in
f@x_ = Integrate[y^2, {y, 0, x}]
f@3
or even
ClearAll@x
f@x_ = Integrate[y^2, {y, 0, x}]
x = 10;
f@3
with the same result. And (9 /. x_ -> x^2) === 81
.
I always felt the syntax highlighting suggested that this is not possible, that somehow the pattern name would be ignored, such that 9 /. x_ -> x^2
would give x^2
, symbolically.
Certainly it is not very safe in many cases, but still.
Bottom line is, we can sometimes use e.g. f@x_ = Integrate[y^2, {y, 0, x}]
instead of f@x_ := Evaluate@Integrate[y^2, {y, 0, x}]
.
Am I missing something or is this really how things work?
I would like to wrap such things as f@x_ = Integrate[y^2, {y, 0, x}]
in a Module
to make the x
a safe, unique label, but that doesn't seem to work for some reason.
That is, I would want to write
f@x_ := Evaluate@Integrate[y^2, {y, 0, x}]
as
x = 10;(*should not matter*)
Module[{x},
f@x_ = Integrate[
y^2, {y, 0, x}](*I would like this x to be the one from Module*)
]
f@0(*should give 0*)
See How to scope `Pattern` labels in rules/set?
Appendix
This makes the intended definition of f
, regardless of whether x
is already set or not:
ClearAll[f, x];
x = 10;
ReleaseHold[Hold[
f@x_ = Integrate[y^2, {y, 0, x}]
] /. HoldPattern@x -> Unique[Unevaluated@x]]
?f
Note also that
f@x_ = Unevaluated@Integrate[y^2, {y, 0, x}];
is effectively equivalent to
f@x_ := Integrate[y^2, {y, 0, x}];
But these definitions will recompute the integral every time.