# Why does the delayed functional assignment evaluate to 5=6? [closed]

Why is it that

x=5
x=x+1


nicely evaluates to 6, but the following

Remove[a,f,x]
a=5;
f[x_] := x = x+1
f[a]


evaluates to 5=6?

To my understanding, the only way I can get the result I'm getting would if when I call f[a], instead of first evaluating the LHS of from the "bottom to top", namely <x> -> <5+1> -> <x=6> -> f[5] = 6 (while setting x=6), but it seems this is not what is happening. Is it because function substitution preceded over delayed assignment, namely it is substituting the value of a before evaluating x=x+1?

• Because Mathematica evaluates eagerly rather than lazily. Arguments are always evaluated before passed to function, unless the function has a Hold attribute. Try SetAttributes[f, HoldFirst]. Also try inspecting functions that modify variables, for example Attributes[Increment]. Dec 21, 2020 at 20:19
• With version 12.2, I get two error messages (Set::setraw: Cannot assign to raw object 5.) followed by True. To see the evaluation sequence with your version, add // Trace to the last line Dec 21, 2020 at 20:22
• Have a look here, I was describing parameter-passing there in a rather detailed manner. Dec 21, 2020 at 20:57
• @LeonidShifrin thanks a lot! I'm actually following that very same book to study mathematica, but haven't reach the section 4.4 :)
– Our
Dec 21, 2020 at 21:14
• Have a look also at this Q/A. Dec 21, 2020 at 21:38

Writing f[x_] := x = x + 1 doesn't really make much sense. The assignment will always fail, but x + 1 will be returned. So f[x_] := x + 1 produces the same result without issuing warnings.
• İf you look at the trace of f[a], you will see that it tries to evaluate 5=6. Note that, I get the same error as you do, and my question is rather why it evaluates to this (I'm not trying to get around a problem, just trying to understand how mathematica works)
• @onurcanbkts. Trace tries to evaluate 5=6, but, of course it does't succeed. It considers that expression because you write x = x + 1 on the rhs of your definition of f. Dec 21, 2020 at 21:21