Why is it that


nicely evaluates to 6, but the following

f[x_] := x = x+1

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?

  • 3
    $\begingroup$ 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]. $\endgroup$ Dec 21, 2020 at 20:19
  • 1
    $\begingroup$ 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 $\endgroup$
    – Bob Hanlon
    Dec 21, 2020 at 20:22
  • 1
    $\begingroup$ Have a look here, I was describing parameter-passing there in a rather detailed manner. $\endgroup$ Dec 21, 2020 at 20:57
  • $\begingroup$ @LeonidShifrin thanks a lot! I'm actually following that very same book to study mathematica, but haven't reach the section 4.4 :) $\endgroup$
    – Our
    Dec 21, 2020 at 21:14
  • 1
    $\begingroup$ Have a look also at this Q/A. $\endgroup$ Dec 21, 2020 at 21:38

1 Answer 1


This is not an answer. It is a comment that contains an image that can't be put into a comment.

I can not reproduce your result. When I execute your code I get the result that I expected which is:


I did m y evaluation in V12.1.1 on MacOS 10.13.4.

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.

  • $\begingroup$ İ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) $\endgroup$
    – Our
    Dec 21, 2020 at 20:54
  • $\begingroup$ @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. $\endgroup$
    – m_goldberg
    Dec 21, 2020 at 21:21

Not the answer you're looking for? Browse other questions tagged or ask your own question.