Swapping two variables in Synergy/DE
Sterling Camden
Swapping the contents of two variables is a common programming task that should be easy to perform. In scripting languages of the Perl tradition it’s dead simple, using simultaneous assignment:
Perl: ($a,$b) = ($b,$a);
Python: (a,b) = (b,a)
Ruby: a,b = b,a
Common Lisp has a macro for the purpose:
(rotatef a b)
Most other languages require more than one statement. For instance, in C (assuming that a and b are integers):
{ int swap = a; a = b; b = swap; }
which isn’t bad – after all, you could define it as a macro (although you’d have to make the type an argument as well if you wanted to support multiple types).
In Synergy/DE, you can’t put it all on one line, so you can’t define it as a macro:
begin
data swap, int, a
a = b
b = swap
end
Well, actually, now you can define it as a macro, by using Let and Progn. The downloadable code below does just that, in an include file named swap.def. The following macros are defined therein:
swap(obj1, obj2, type) – swap two objects, casting as type.
swapi(int1, int2) – swap two integers
swapd(dec1, dec2) – swap two decimal values
swapa(a1, a2) – swap two alphanumeric values (or strings)
swapv(var1, var2) – swap two Vars
Note that you can swap different types as long as both the variables and the objects they contain are compatible with the specified type. The type you specify will be used to cast both operands, so it can either be a common ancestor or one of the objects has to provide an op_Explicit conversion. In the case of primitives, “type” will specify the type of conversion you want performed, via Var.
The “type” parameter must be enclosed in parentheses, if it is a type. If parentheses are omitted, type will be treated as a function, method, or macro name, to which will be passed an object parameter (either a Var or some other class). This gives you a way to insert your own conversion routine if you need it. Or you can omit type entirely, if both operands are just object variables (@*).
The test routine test_swap.dbl provides some tests, using assertions. As you can see from the commented out code at the end, the swap macro does not work for properties (including indexer properties). That’s because Synergy/DE does not return a value from an assignment to a property. This issue has already been reported as tracker 23837, so hopefully it will be fixed soon. Because of that limitation, you can’t use these macros to swap elements of an ArrayList. But I have even bigger plans for extending ArrayList that will include a method for swapping elements, among other things.
UPDATE 2009-09-13: for Synergy/DE 9.3
Posted in SynergyDE |
No Comments » RSS 2.0 | Sphere it!




