Re: Swap and pass-by-reference
- Posted by DerekParnell (admin) Jan 28, 2011
- 1577 views
a <=> b
{a,b} = {b,a}
(or whatever syntax you lot settle on for multiple assignment) would be a more useful addition to the language.
The 'multiple assignment' (also known as de-sequencing) idea is a more generic one; the swap operator is a subset of that, but one which can provide better performance.
The difference is that the de-sequence operator requires a list of variables (lvalues) on the left-hand side and a list of values on the right-hand side (rvalues). It is a natural fit for a list of values in Euphoria to be represented by a sequence. The lvalue for this operation is not a sequence but a list of assignable identifiers, which is not the same as a sequence. The lvalue is a parsing issue and not a run-time issue.
When the de-sequence operation is implemented, one could use it to implement a swap operation, but it would not be as efficient as a purpose-built swap operation because the rvalue would have to construct a sequence at run-time (though a smart optimising parser might be able to improve this in some circumstances). For example ...
@(a,b) = {b,a}
(N.B: I'm using here a possible syntax @( ... ) to denote a list of variables.)
The right-hand side would create a temporary sequence containing the values inside 'b' and 'a', then the assignment of those values would be made to 'a' and 'b' respectively, thus effectively swapping them. The temporary sequence would then be deleted.
But by using a swap operator, there is no temporary sequence created and deleted, instead the values are swapped in the most efficient way for the data-types involved.
There is certainly a place for a de-sequence operator in Euphoria, and I would support its implementation, but I also think that a purpose built swap operator is also a useful construct in the language.
I am surprised no-one has suggested swap(a,b) be implemented via a pre-processor.
I think I do remember a brief discussion about that. A problem with the pre-processor is that it is not designed to handle multiple pre-processing tasks. For example, the Euphoria programs that create these web pages were run through a specific pre-processor that knows about web-stuff (webclay). Now if someone uses a swap operator in the webclay code, the output of the webclay preprocessor would then have to go through the 'swap' pre-processor as well, and I'm not sure if that is even feasible or desirable.
A pre-processor is designed to implement one specific transformation. If your code has multiple 'pre-processor' elements, it needs to be run through multiple pre-processors so that all the transformations are done. The management and performance of such a set of operations may not be so desirable.
This might be one reason that some form of built-in text-macro processing might be a useful (but dangerous?) addition to the language.