[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Let's talk about order of assignment
- From: Coda Highland <chighland@...>
- Date: Sun, 14 Sep 2014 22:53:42 -0700
On Sun, Sep 14, 2014 at 10:48 PM, Oliver Kroth <oliver.kroth@nec-i.de> wrote:
>
>>> Does anyone have an example of using the pathological case
>>>
>>> a,a,a=1,2,3
>>>
>>> or similar in real code (except as a coding error)? I can't think of a
>>> use
>>> case for using the same variable more then once
>>> on the left side of a multiple assignment.
>>>
>>> -- Mike
>>
>>
> I had, although... One may say it was an coding error:
>
> Coding an event queue using a binary heap, I wanted to to pick the first one
> (into node) andmove the last position into first while clearing the last
> position ( node <- self[1} <- self[last] <- nil) in one statement:
>
> node, self[1], self[last], last = self[1], self[last], nil,
> last-1
>
> The code worked, funny enough, as long as more than one event was in the
> queue.
> It did work better after I made four single assignments from it to enforce
> the execution order:
>
> node = self[1]
> self[1] = self[last]
> self[last] = nil
> last = last-1
>
> --
> Oliver
>
With the exception of last==1, this is actually well-defined behavior.
All of the right-side values are evaluated before assignment. This
allows you to express a swap as "x, y = y, x".
/s/ Adam