[Gambas-user] Swap expressions with side effects

Tobias Boege taboege at ...626...
Sat Jan 11 19:43:08 CET 2014


On Sat, 11 Jan 2014, Beno?t Minisini wrote:
> Le 11/01/2014 19:05, Tobias Boege a ?crit :
> > Hi,
> >
> > I just spent two good hours over my implementation of an algorithm to
> > arrange some PointFs in an array so that the distance between P[i] and
> > P[i+1] is the smallest possible among all points P[j], j > i. I don't
> > want to bother you with details (well, I think I already did, sorry) but
> > the comparison of two points is not only a function of these two points
> > but also of some other reference point. So I used a line like this:
> >
> >    Swap $aPoints[iInd + 1], $aPoints[GetNearest(iInd)]
> >
> > which means: get me the index of the nearest point to $aPoints[iInd] and
> > swap $aPoints[iInd + 1] with the value there. This effectively sorts my
> > array into the desired order (For iInd = 0 To $aPoints.Max - 1).
> >
> > Well, not really. Because Swap is not immune to side effects induced by
> > the expressions to swap. The wiki states that implicitly by saying that
> >
> >    Swap A, B
> >
> > is equivalent to
> >
> >    tmp = A
> >    A = B
> >    B = tmp
> >
> > So my code really was:
> >
> >    tmp = $aPoints[iInd + 1]
> >    $aPoints[iInd + 1] = $aPoints[GetNearest(iInd)]
> >    $aPoints[GetNearest(iInd)] = tmp
> >
> > which leads to an erroneous array because GetNearest() is a function of
> > $aPoints[iInd + 1] which changed between the two invocations. [ The funny
> > thing is that, due to the nature of GetNearest(), the result of the above
> > three lines for all iInd is that the array remains unchanged. ]
> >
> > To cut a long story short, is this by design? Do you think it's worth
> > changing that behaviour (it wouldn't break any sane use of Swap)? If not
> > it's equivalently fine. I'll add a clear warning to the wiki, then.
> >
> > Regards,
> > Tobi
> >
> 
> As stated by the documentation, 'Swap' is just syntactic sugar for:
> 
>    tmp = A
>    A = B
>    B = tmp
> 
> Each Swap expression will be evaluated twice (once as an expression, and 
> once as an assignment). It's like a C macro.
> 
> So I'm afraid it won't change!
> 

OK, I wrote an explicit warning into the wiki.

-- 
"There's an old saying: Don't change anything... ever!" -- Mr. Monk




More information about the User mailing list