This line returns 3
:
x = 1; ++++x
However, the value of x
after the increment is only 2. Similarly, this line returns 5
, while the value of x
is again only 2.
x = 1; ++++++++x
Why does it return 3
and 5
respectively in the above examples?
(This question is intended as a puzzle, and to encourage people to think through an opaque evaluation chain.)
Answer
TracePrint
will show you what happens:
PreIncrement
takes it's argument x
, evaluates it (let's call the result result
), then evaluates x = result+1
. Note that PreIncrement
has HoldFirst
.
Now ++(++x)
evaluates ++x
first yielding 2
, then evaluates (++x) = 2+1
resulting in an error (trying to assign to PreIncrement
) and returning 3
.
This also explains why adding yet another layer of PreIncrement
will increment the result again.
Here's a self-implemented ++
to make the above more clear. The behaviour is exactly the same:
Comments
Post a Comment