Question
How to make the replacement $f[x] \to f[y]$ for an abitrary function $f$ if $x$ was assigned a value before?
Example 1
How can I make the replacement $x +1 \to y + 1$ if I have assigned the variable $x$ a value before?
Problematic attempts
A first guess would be
x = 1;
x + 1 /. x -> y
4
This does not give $y + 1$ because $x + 1$ is evaluated to 4
before the replacement is attempted. I expected this would give $y+1$:
Unevaluated[1 + x] /. x -> y
4
My reasoning was that the replacement of $x$ with $y$ in
x + 1 // FullForm
Unevaluated[1 + x] // FullForm
4
Unevaluated[Plus[1,x]]
gives '4' and Unevaluated[Plus[1,y]]
, but it does not. Why? Is there a solution that works in this spirit?
Working Solution
In the post Symbolic computations with already assigned variables, I found the suggestion to use block. Indeed it works
Block[{x}, x + 1 /. x -> y]
y + 1
Example 2
Let
x = {1, 3, 4};
f[x_] := Length[x];
How to replace x
in f[x]
with {1, 2}
? We allready saw that f[x] /. x -> {1, 2}
will not work. Here the construction with Block
does not work either
Block[{x}, f[x] /. x -> {3, 2}
0
It gives 0 since the lefthand side of the rule is evaluated first, and gives 'Length[x] = 0'. Only then the rule is applied. I guess I need a rule in the spirit of the 'problematic attempts' in order to make the desired replacement.