1

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?

Our
  • 229
  • 1
  • 6
  • 3
    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]. – Sjoerd Smit Dec 21 '20 at 20:19
  • 1
    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 – Bob Hanlon Dec 21 '20 at 20:22
  • 1
    Have a look here, I was describing parameter-passing there in a rather detailed manner. – Leonid Shifrin Dec 21 '20 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 '20 at 21:14
  • @onurcanbkts Well, that should mean that the way I laid out the material was not ideal - something to look into if I ever make a second edition :) – Leonid Shifrin Dec 21 '20 at 21:33
  • 1
    Have a look also at this Q/A. – Leonid Shifrin Dec 21 '20 at 21:38

1 Answers1

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:

eval

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.

m_goldberg
  • 107,779
  • 16
  • 103
  • 257
  • İ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) – Our Dec 21 '20 at 20:54
  • @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. – m_goldberg Dec 21 '20 at 21:21