Generic swap: Difference between revisions
PascalABC.NET |
|||
(144 intermediate revisions by 67 users not shown) | |||
Line 1: | Line 1: | ||
{{task|Basic language learning}} |
{{task|Basic language learning}} |
||
;Task: |
|||
The task is to write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. |
|||
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. |
|||
If your solution language is statically typed please describe the way your language provides genericity. |
If your solution language is statically typed please describe the way your language provides genericity. |
||
Line 16: | Line 18: | ||
Do your best! |
Do your best! |
||
<br><br> |
|||
=={{header|11l}}== |
|||
<syntaxhighlight lang="11l">F swap(&a, &b) |
|||
(a, b) = (b, a)</syntaxhighlight> |
|||
=={{header|360 Assembly}}== |
=={{header|360 Assembly}}== |
||
Three consecutive exclusive OR's swap variable contents |
Three consecutive exclusive OR's swap variable contents |
||
<syntaxhighlight lang="360 assembly"> |
|||
<lang 360 Assembly> |
|||
SWAP CSECT , control section start |
SWAP CSECT , control section start |
||
BAKR 14,0 stack caller's registers |
BAKR 14,0 stack caller's registers |
||
Line 40: | Line 47: | ||
B DS CL8 field B, 8 bytes |
B DS CL8 field B, 8 bytes |
||
END SWAP program end |
END SWAP program end |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|6502 Assembly}}== |
|||
There are no atomic swap operations in [[6502 Assembly]] but there are a few slower ways of doing it, using the stack. The 65c02 and 65816 revisions added a few commands which make swapping easier. The need for atomic swapping isn't really an issue since most 6502-based computers didn't use parallel processing; the biggest concern for registers or memory getting clobbered was from interrupts, which can be easily avoided by restricting the registers and/or memory they use, and using the stack to back up and restore their values at the beginning and end. |
|||
===NMOS 6502=== |
|||
The original 6502 can't push X or Y onto the stack directly, and must do so through the accumulator. The most common way of swapping values is by pushing them onto the stack and popping them in the "wrong" order on purpose. |
|||
<syntaxhighlight lang="6502asm">;swap X with Y |
|||
pha ;push accumulator |
|||
txa |
|||
pha ;push x |
|||
tya |
|||
pha ;push y |
|||
pla |
|||
tax ;pop y into x |
|||
pla |
|||
tay ;pop x into y |
|||
pla ;pop accumulator</syntaxhighlight> |
|||
Swapping A with X or Y is easiest with using zero page memory as a temporary store, or with self-modifying code. |
|||
<syntaxhighlight lang="6502asm"> |
|||
sta temp ;a label representing a zero page memory address |
|||
txa |
|||
pha ;push x |
|||
ldx temp |
|||
pla ;pop x into accumulator</syntaxhighlight> |
|||
Swapping memory locations is fairly straightforward on all versions of the 6502: |
|||
<syntaxhighlight lang="6502asm"> |
|||
temp equ $00 |
|||
temp2 equ $01 ;these values don't matter. |
|||
lda temp |
|||
pha ;push temp |
|||
lda temp2 |
|||
pha ;push temp2 |
|||
pla |
|||
sta temp ;pop temp2 into temp |
|||
pla |
|||
sta temp2 ;pop temp into temp2</syntaxhighlight> |
|||
===CMOS 65c02=== |
|||
This revision of the 6502 can push X and Y onto the stack directly. The above code can be condensed quite a bit. This is a different example that better illustrates how swapping can be done: |
|||
<syntaxhighlight lang="6502asm">lda #$33 |
|||
ldx #$44 |
|||
ldy #$55 |
|||
pha |
|||
phx |
|||
phy |
|||
pla ;a=#$55 |
|||
ply ;y=#$44 |
|||
plx ;x=#$33</syntaxhighlight> |
|||
=={{header|68000 Assembly}}== |
|||
Two registers can be swapped with <code>EXG</code>: |
|||
<syntaxhighlight lang="68000devpac">EXG D0,D1 ;swap the contents of D0 and D1 |
|||
EXG A0,A1 ;swap the contents of A0 and A1</syntaxhighlight> |
|||
However, these commands cannot be used with memory. If you want to do that you'll need to use the stack or a data register. |
|||
<syntaxhighlight lang="68000devpac">MOVE.L ($00FF0000),D0 |
|||
MOVE.L ($00FF1000),D1 |
|||
MOVE.L D0,($00FF1000) |
|||
MOVE.L D1,($00FF0000)</syntaxhighlight> |
|||
The <code>SWAP</code> switches the high and low words of a data register. It can't be used with memory either. |
|||
<syntaxhighlight lang="68000devpac">MOVE.L #$1234ABCD,D0 |
|||
SWAP D0 ;now D0 = #$ABCD1234</syntaxhighlight> |
|||
=={{header|8086 Assembly}}== |
|||
The <code>XCHG</code> command swaps two registers' values. It can also work with memory that is pointed to by an index register such as <code>SI</code>, <code>DI</code>,or <code>BP</code>. Both registers must be the same size, which enforces type matching. You cannot <code>XCHG AX,CL</code> for example since <code>AX</code> is 16-bit and <code>CL</code> is only 8-bit. |
|||
Here are some examples of the <code>XCHG</code> command in action: |
|||
<syntaxhighlight lang="asm">xchg ax,bx ;exchanges ax with bx |
|||
xchg ah,al ;swap the high and low bytes of ax |
|||
;XCHG a register with memory |
|||
mov dx,0FFFFh |
|||
mov word ptr [ds:userRam],dx |
|||
mov si,offset userRam |
|||
mov ax,1234h |
|||
xchg ax,[si] ;exchange ax with the value stored at userRam. Now, ax = 0FFFFh and the value stored at userRam = 1234h |
|||
;XCHG a register with a value on the stack. |
|||
mov ax,1234h |
|||
mov bx,4567h |
|||
push bx |
|||
push bp |
|||
mov bp,sp ;using [sp] as an operand for XCHG will not work. You need to use bp instead. |
|||
xchg ax,[2+bp] ;exchanges AX with the value that was pushed from BX onto the stack. Now, AX = 4567h, |
|||
;and the entry on the stack just underneath the top of the stack is 1234h.</syntaxhighlight> |
|||
=={{header|8th}}== |
=={{header|8th}}== |
||
< |
<syntaxhighlight lang="forth"> |
||
swap |
swap |
||
</syntaxhighlight> |
|||
</lang> |
|||
Or to swap between the stack and a var: |
Or to swap between the stack and a var: |
||
< |
<syntaxhighlight lang="forth"> |
||
dup @ -rot ! |
dup @ -rot ! |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|ACL2}}== |
=={{header|ACL2}}== |
||
< |
<syntaxhighlight lang="lisp">(defun swap (pair) |
||
(cons (cdr pair) |
(cons (cdr pair) |
||
(car pair))) |
(car pair))) |
||
(let ((p (cons 1 2))) |
(let ((p (cons 1 2))) |
||
(cw "Before: ~x0~%After: ~x1~%" p (swap p)))</ |
(cw "Before: ~x0~%After: ~x1~%" p (swap p)))</syntaxhighlight> |
||
=={{header|Action!}}== |
|||
{{libheader|Action! Tool Kit}} |
|||
<syntaxhighlight lang="action!">INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit |
|||
PROC Swap(BYTE POINTER ptr1,ptr2 INT size) |
|||
BYTE tmp |
|||
INT i |
|||
FOR i=0 TO size-1 |
|||
DO |
|||
tmp=ptr1^ ptr1^=ptr2^ ptr2^=tmp |
|||
ptr1==+1 ptr2==+1 |
|||
OD |
|||
RETURN |
|||
PROC Main() |
|||
BYTE b1=[13],b2=[56] |
|||
INT i1=[65234],i2=[534] |
|||
REAL r1,r2 |
|||
CHAR ARRAY s1="abcde",s2="XYZ" |
|||
Put(125) PutE() ;clear the screen |
|||
ValR("32.5",r1) ValR("-0.63",r2) |
|||
Print("Swap bytes: ") |
|||
PrintB(b1) Put(32) PrintB(b2) Print(" -> ") |
|||
Swap(@b1,@b2,1) |
|||
PrintB(b1) Put(32) PrintBE(b2) |
|||
Print("Swap integers: ") |
|||
PrintI(i1) Put(32) PrintI(i2) Print(" -> ") |
|||
Swap(@i1,@i2,2) |
|||
PrintI(i1) Put(32) PrintIE(i2) |
|||
Print("Swap floats: ") |
|||
PrintR(r1) Put(32) PrintR(r2) Print(" -> ") |
|||
Swap(r1,r2,6) |
|||
PrintR(r1) Put(32) PrintRE(r2) |
|||
Print("Swap strings: ") |
|||
Print(s1) Put(32) Print(s2) Print(" -> ") |
|||
Swap(@s1,@s2,2) |
|||
Print(s1) Put(32) PrintE(s2) |
|||
RETURN</syntaxhighlight> |
|||
{{out}} |
|||
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Generic_swap.png Screenshot from Atari 8-bit computer] |
|||
<pre> |
|||
Swap bytes: 13 56 -> 56 13 |
|||
Swap integers: -302 534 -> 534 -302 |
|||
Swap floats: 32.5 -0.63 -> -0.63 32.5 |
|||
Swap strings: abcde XYZ -> XYZ abcde |
|||
</pre> |
|||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
The generic parameters for an Ada generic procedure are defined in a procedure specification, while the algorithm is defined in a procedure body. The first code snippet is the procedure specification. The second code snippet is the procedure body. |
The generic parameters for an Ada generic procedure are defined in a procedure specification, while the algorithm is defined in a procedure body. The first code snippet is the procedure specification. The second code snippet is the procedure body. |
||
< |
<syntaxhighlight lang="ada">generic |
||
type Swap_Type is private; -- Generic parameter |
type Swap_Type is private; -- Generic parameter |
||
procedure Generic_Swap(Left |
procedure Generic_Swap (Left, Right : in out Swap_Type); |
||
procedure Generic_Swap(Left |
procedure Generic_Swap (Left, Right : in out Swap_Type) is |
||
Temp : Swap_Type := Left; |
Temp : constant Swap_Type := Left; |
||
begin |
begin |
||
Left := Right; |
Left := Right; |
||
Right := Temp; |
Right := Temp; |
||
end Generic_Swap;</ |
end Generic_Swap;</syntaxhighlight> |
||
===usage=== |
===usage=== |
||
To use the generic swap procedure, you need to instantiate the procedure for each type that you intend to use. |
To use the generic swap procedure, you need to instantiate the procedure for each type that you intend to use. |
||
< |
<syntaxhighlight lang="ada"> |
||
with Generic_Swap; |
with Generic_Swap; |
||
... |
... |
||
type T is ... |
type T is ... |
||
procedure T_Swap is new Generic_Swap (Swap_Type => T); |
|||
A,B:T; |
A, B : T; |
||
... |
... |
||
T_Swap(A,B); |
T_Swap (A, B); |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Aime}}== |
=={{header|Aime}}== |
||
Aime is statically typed. A generic swap utility may nonetheless be defined in terms of parameters of unspecified type and pass by reference. |
Aime is statically typed. A generic swap utility may nonetheless be defined in terms of parameters of unspecified type and pass by reference. |
||
< |
<syntaxhighlight lang="aime">void |
||
__swap(&, &,,) |
__swap(&, &,,) |
||
{ |
{ |
||
Line 98: | Line 255: | ||
{ |
{ |
||
xcall(xcall, __swap); |
xcall(xcall, __swap); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|ALGOL 68}}== |
=={{header|ALGOL 68}}== |
||
Line 109: | Line 266: | ||
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d]}} |
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d]}} |
||
< |
<syntaxhighlight lang="algol68">MODE GENMODE = STRING; |
||
GENMODE v1:="Francis Gary Powers", v2:="Vilyam Fisher"; |
GENMODE v1:="Francis Gary Powers", v2:="Vilyam Fisher"; |
||
Line 121: | Line 278: | ||
v1 =:= v2; |
v1 =:= v2; |
||
print(("v1: ",v1, ", v2: ", v2, new line))</ |
print(("v1: ",v1, ", v2: ", v2, new line))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 130: | Line 287: | ||
ReadLock(a,b) functioned by reading ''a'' and writing its value to ''b'', but also, recovering the value that was in ''b'' which it returns as the result of the function - which is written to ''a'' by the assignment, completing the swap. The ReadLock part is "atomic" or not interruptable, so it is used in semaphores and the like, but was available for other use. It swapped a single word, so could swap types such as integers or floating-point numbers (single precision) thus being somewhat generic. |
ReadLock(a,b) functioned by reading ''a'' and writing its value to ''b'', but also, recovering the value that was in ''b'' which it returns as the result of the function - which is written to ''a'' by the assignment, completing the swap. The ReadLock part is "atomic" or not interruptable, so it is used in semaphores and the like, but was available for other use. It swapped a single word, so could swap types such as integers or floating-point numbers (single precision) thus being somewhat generic. |
||
=={{header|Amazing Hopper}}== |
|||
<syntaxhighlight lang="amazing hopper"> |
|||
#include <flow.h> |
|||
DEF-MAIN(argv,argc) |
|||
DIM(10) AS-INT-RAND( 10, random array ) |
|||
SET( single var, 0.5768 ) |
|||
PRNL( "SINGLE VAR: ", single var, "\nRANDOM ARRAY: ", random array ) |
|||
single var <-> random array |
|||
PRNL( "SINGLE VAR: ", single var, "\nRANDOM ARRAY: ", random array ) |
|||
END |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
$ hopper swap.flw |
|||
SINGLE VAR: 0.5768 |
|||
RANDOM ARRAY: 4,2,5,10,8,3,4,8,3,5 |
|||
SINGLE VAR: 4,2,5,10,8,3,4,8,3,5 |
|||
RANDOM ARRAY: 0.5768 |
|||
$ |
|||
</pre> |
|||
=={{header|AmigaE}}== |
=={{header|AmigaE}}== |
||
The simpler way to write a swap is to use the Amiga E ability to return multiple values. All basic data type in Amiga E can be held by its LONG type, and complex data type (like lists) are indeed pointers (which fits into a LONG too); so, because of the fact that Amiga E is not strongly typed, this solution works for any type. |
The simpler way to write a swap is to use the Amiga E ability to return multiple values. All basic data type in Amiga E can be held by its LONG type, and complex data type (like lists) are indeed pointers (which fits into a LONG too); so, because of the fact that Amiga E is not strongly typed, this solution works for any type. |
||
< |
<syntaxhighlight lang="amigae">PROC swap(a,b) IS b,a |
||
PROC main() |
PROC main() |
||
Line 148: | Line 330: | ||
ForAll({x}, v2, `WriteF('\d ',x)) -> 10 20 30 40 |
ForAll({x}, v2, `WriteF('\d ',x)) -> 10 20 30 40 |
||
WriteF('\n') |
WriteF('\n') |
||
ENDPROC</ |
ENDPROC</syntaxhighlight> |
||
=={{header|AppleScript}}== |
=={{header|AppleScript}}== |
||
AppleScript has built-in support for swapping. This is generic and works for all combinations of data types. |
AppleScript has built-in support for swapping. This is generic and works for all combinations of data types. |
||
< |
<syntaxhighlight lang="applescript">set {x,y} to {y,x}</syntaxhighlight> |
||
=={{header|Arc}}== |
=={{header|Arc}}== |
||
< |
<syntaxhighlight lang="arc">(mac myswap (a b) |
||
(w/uniq gx |
(w/uniq gx |
||
`(let ,gx a |
`(let ,gx a |
||
Line 165: | Line 347: | ||
(myswap a b) |
(myswap a b) |
||
(prn "a:" a #\Newline "b:" b)) |
(prn "a:" a #\Newline "b:" b)) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Arturo}}== |
|||
{{trans|Ruby}} |
|||
===Using multi-assignment=== |
|||
<syntaxhighlight lang="rebol">swap: function [a,b]-> @[b,a] |
|||
c: 1 |
|||
d: 2 |
|||
print [c d] |
|||
[c,d]: swap c d |
|||
print [c d]</syntaxhighlight> |
|||
{{out}} |
|||
<pre>1 2 |
|||
2 1</pre> |
|||
===In-place modification=== |
|||
<syntaxhighlight lang="rebol">swap: function [a,b].exportable [ |
|||
tmp: var b |
|||
let b var a |
|||
let a tmp |
|||
] |
|||
c: 1 |
|||
d: 2 |
|||
print [c d] |
|||
swap 'c 'd |
|||
print [c d]</syntaxhighlight> |
|||
{{out}} |
|||
<pre>1 2 |
|||
2 1</pre> |
|||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
< |
<syntaxhighlight lang="autohotkey">Swap(ByRef Left, ByRef Right) |
||
{ |
{ |
||
temp := Left |
temp := Left |
||
Left := Right |
Left := Right |
||
Right := temp |
Right := temp |
||
}</ |
}</syntaxhighlight> |
||
=={{header|AWK}}== |
=={{header|AWK}}== |
||
<syntaxhighlight lang="awk"> |
|||
<lang AWK> |
|||
# syntax: GAWK -f GENERIC_SWAP.AWK |
# syntax: GAWK -f GENERIC_SWAP.AWK |
||
BEGIN { |
BEGIN { |
||
Line 202: | Line 421: | ||
return(0) |
return(0) |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 216: | Line 435: | ||
=={{header|Axe}}== |
=={{header|Axe}}== |
||
The Exch() command can swap data of any size at any two addresses. This example swaps two 2-byte variables. |
The Exch() command can swap data of any size at any two addresses. This example swaps two 2-byte variables. |
||
<lang |
<syntaxhighlight lang="axe">Exch(°A,°B,2)</syntaxhighlight> |
||
=={{header| |
=={{header|BASIC}}== |
||
==={{header|Applesoft BASIC}}=== |
|||
<syntaxhighlight lang="applesoft basic">A=43:B=47:H=A:A=B:B=H:?" A="A" B="B;</syntaxhighlight> |
|||
<pre> A=47 B=43</pre> |
|||
==={{header|BaCon}}=== |
|||
Swap using pass-by-name |
|||
<syntaxhighlight lang="freebasic"> |
|||
x = 1 |
|||
y$ = "hello" |
|||
SWAP x, y$ |
|||
<lang dos>@echo off |
|||
PRINT y$ |
|||
setlocal enabledelayedexpansion |
|||
</syntaxhighlight> |
|||
set a=1 |
|||
set b=woof |
|||
echo %a% |
|||
echo %b% |
|||
call :swap a b |
|||
echo %a% |
|||
echo %b% |
|||
goto :eof |
|||
==={{header|BASIC256}}=== |
|||
:swap |
|||
<syntaxhighlight lang="basic256">global a, b |
|||
set temp1=!%1! |
|||
a = "one" |
|||
set temp2=!%2! |
|||
b = "two" |
|||
set %1=%temp2% |
|||
set %2=%temp1% |
|||
goto :eof</lang> |
|||
print a, b |
|||
=={{header|BBC BASIC}}== |
|||
call swap(a, b) |
|||
===Built-in function=== |
|||
print a, b |
|||
<lang bbcbasic> a = 1.23 : b = 4.56 |
|||
end |
|||
subroutine swap(a, b) |
|||
temp = a : a = b : b = temp |
|||
end subroutine</syntaxhighlight> |
|||
==={{header|BBC BASIC}}=== |
|||
====Built-in function==== |
|||
<syntaxhighlight lang="bbcbasic"> a = 1.23 : b = 4.56 |
|||
SWAP a,b |
SWAP a,b |
||
PRINT a,b |
PRINT a,b |
||
Line 248: | Line 473: | ||
a$ = "Hello " : b$ = "world!" |
a$ = "Hello " : b$ = "world!" |
||
SWAP a$,b$ |
SWAP a$,b$ |
||
PRINT a$,b$</ |
PRINT a$,b$</syntaxhighlight> |
||
===Custom function=== |
====Custom function==== |
||
< |
<syntaxhighlight lang="bbcbasic"> a = 1.23 : b = 4.56 |
||
PROCswap(^a,^b, 5) |
PROCswap(^a,^b, 5) |
||
PRINT a,b |
PRINT a,b |
||
Line 264: | Line 489: | ||
SWAP a%?i%,b%?i% |
SWAP a%?i%,b%?i% |
||
NEXT |
NEXT |
||
ENDPROC</ |
ENDPROC</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 270: | Line 495: | ||
world! Hello |
world! Hello |
||
</pre> |
</pre> |
||
==={{header|Chipmunk Basic}}=== |
|||
The [[#GW-BASIC|GW-BASIC]] solution works without any changes. |
|||
==={{header|FreeBASIC}}=== |
|||
FreeBASIC already has a built-in generic Swap procedure but a macro can be used to build another one: |
|||
<syntaxhighlight lang="freebasic">' FB 1.05.0 |
|||
#Macro Declare_Swap(T) |
|||
Sub Swap_##T(ByRef t1 As T, ByRef t2 As T) |
|||
Dim temp As T = t2 |
|||
t2 = t1 |
|||
t1 = temp |
|||
End Sub |
|||
#EndMacro |
|||
Dim As Integer i, j |
|||
i = 1 : j = 2 |
|||
Declare_Swap(Integer) ' expands the macro |
|||
Swap_Integer(i, j) |
|||
Print i, j |
|||
Dim As String s, t |
|||
s = "Hello" : t = "World" |
|||
Declare_Swap(String) |
|||
Swap_String(s, t) |
|||
Print s, t |
|||
Print |
|||
Print "Press any key to exit" |
|||
Sleep</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
2 1 |
|||
World Hello |
|||
</pre> |
|||
==={{header|FutureBasic}}=== |
|||
<syntaxhighlight lang="futurebasic">window 1, @"Generic Swap", (0,0,480,270) |
|||
text ,,,,, 60 |
|||
long i, j |
|||
double x, y |
|||
CFStringRef a, b |
|||
i = 1059 : j = 62 |
|||
print i, j |
|||
swap i, j |
|||
print i, j |
|||
print |
|||
x = 1.23 : y = 4.56 |
|||
print x, y |
|||
swap x, y |
|||
print x, y |
|||
print |
|||
a = @"Hello" : b = @"World!" |
|||
print a, b |
|||
swap a, b |
|||
print a, b |
|||
HandleEvents |
|||
</syntaxhighlight> |
|||
{{output}} |
|||
<pre> |
|||
1059 62 |
|||
62 1059 |
|||
1.23 4.56 |
|||
4.56 1.23 |
|||
Hello World! |
|||
World! Hello |
|||
</pre> |
|||
==={{header|Gambas}}=== |
|||
'''[https://gambas-playground.proko.eu/?gist=b746e857f6f280fb92c204795f6053be Click this link to run this code]''' |
|||
<syntaxhighlight lang="gambas">Public Sub Main() |
|||
Dim vA As Variant = " World" |
|||
Dim vB As Variant = 1 |
|||
Swap vA, vB |
|||
Print vA; vB |
|||
End</syntaxhighlight> |
|||
Output: |
|||
<pre> |
|||
1 World |
|||
</pre> |
|||
==={{header|GW-BASIC}}=== |
|||
{{works with|Applesoft BASIC}} |
|||
{{works with|Chipmunk Basic}} |
|||
{{works with|MSX_BASIC}} |
|||
{{works with|PC-BASIC|any}} |
|||
{{works with|QBasic}} |
|||
<syntaxhighlight lang="qbasic">10 CLS : REM 10 HOME for Applesoft BASIC |
|||
20 A = 1 : B = 2 |
|||
30 PRINT " A=";A," B=";B |
|||
40 T = A : A = B : B = T |
|||
50 PRINT " A=";A," B=";B |
|||
60 END</syntaxhighlight> |
|||
{{out}} |
|||
<pre> A=1 B=2 |
|||
A=2 B=1</pre> |
|||
==={{header|IS-BASIC}}=== |
|||
<syntaxhighlight lang="is-basic">100 DEF SWAP(REF A,REF B) |
|||
110 LET T=A:LET A=B:LET B=T |
|||
120 END DEF |
|||
130 LET A=1:LET B=2 |
|||
140 PRINT A,B |
|||
150 CALL SWAP(A,B) |
|||
160 PRINT A,B</syntaxhighlight> |
|||
==={{header|Minimal BASIC}}=== |
|||
{{works with|QBasic}} |
|||
{{works with|QuickBasic}} |
|||
{{works with|Applesoft BASIC}} |
|||
{{works with|BASICA}} |
|||
{{works with|Chipmunk Basic}} |
|||
{{works with|GW-BASIC}} |
|||
{{works with|IS-BASIC}} |
|||
{{works with|MSX_Basic}} |
|||
{{works with|Just BASIC}} |
|||
{{works with|Liberty BASIC}} |
|||
{{works with|Run BASIC}} |
|||
<syntaxhighlight lang="qbasic">10 LET A = 1 |
|||
20 LET B = 2 |
|||
30 PRINT " A=";A;" B=";B |
|||
40 LET T = A |
|||
50 LET A = B |
|||
60 LET B = T |
|||
70 PRINT " A=";A;" B=";B |
|||
80 END</syntaxhighlight> |
|||
==={{header|MSX Basic}}=== |
|||
The [[#GW-BASIC|GW-BASIC]] solution works without any changes. |
|||
==={{header|OxygenBasic}}=== |
|||
<syntaxhighlight lang="text"> |
|||
macro Swap(a,b, c) |
|||
typeof(a) c |
|||
c=a |
|||
a=b |
|||
b=c |
|||
end macro |
|||
'demo with compound types: |
|||
'========================= |
|||
type point { float x,y} |
|||
point p={1,2} |
|||
point q={3,4} |
|||
swap p,q |
|||
print "p: " p.x "," p.y 'p: 3,4 |
|||
print "q: " q.x "," q.y 'q: 1,2 |
|||
</syntaxhighlight> |
|||
==={{header|PureBasic}}=== |
|||
Built in function: |
|||
<syntaxhighlight lang="purebasic">Swap a, b</syntaxhighlight> |
|||
==={{header|QBasic}}=== |
|||
QBasic already has a generic swap procedure built in, but a new subroutine can be defined: |
|||
<syntaxhighlight lang="qbasic">SUB nswap (a, b) |
|||
temp = a: a = b: b = temp |
|||
END SUB |
|||
a = 1 |
|||
b = 2 |
|||
PRINT a, b |
|||
CALL nswap(a, b) |
|||
PRINT a, b</syntaxhighlight> |
|||
==={{header|Quite BASIC}}=== |
|||
The [[#Minimal _BASIC|Minimal BASIC]] solution works without any changes. |
|||
==={{header|Run BASIC}}=== |
|||
Run BASIC does not have support for swapping built in: |
|||
<syntaxhighlight lang="runbasic">a = 1 |
|||
b = 2 |
|||
'----- swap ---- |
|||
tmp = a |
|||
a = b |
|||
b = tmp |
|||
end</syntaxhighlight> |
|||
==={{header|ThinBASIC}}=== |
|||
Generic function, swap the content of two variables. |
|||
<syntaxhighlight lang="thinbasic">Swap Var1, Var2</syntaxhighlight> |
|||
==={{header|TI-89 BASIC}}=== |
|||
TI-89 BASIC is dynamically typed, so the genericity is implicit. It has no pass by reference, so we must pass the variable names as strings. It is dynamically scoped, so we must choose hopefully distinct names for the variables. |
|||
<syntaxhighlight lang="ti89b">Define swap(swapvar1, swapvar2) = Prgm |
|||
Local swaptmp |
|||
#swapvar1 → swaptmp |
|||
#swapvar2 → #swapvar1 |
|||
swaptmp → #swapvar2 |
|||
EndPrgm |
|||
1 → x |
|||
2 → y |
|||
swap("x", "y") |
|||
x |
|||
2 |
|||
y |
|||
1</syntaxhighlight> |
|||
==={{Header|Tiny BASIC}}=== |
|||
<syntaxhighlight lang="tiny basic"> LET a = 11 |
|||
LET b = 22 |
|||
PRINT a, " ", b |
|||
GOSUB 100 |
|||
PRINT a, " ", b |
|||
END |
|||
100 REM swap(a, b) |
|||
LET t = a |
|||
LET a = b |
|||
LET b = t |
|||
RETURN</syntaxhighlight> |
|||
==={{header|True BASIC}}=== |
|||
<syntaxhighlight lang="qbasic">SUB swap(a, b) |
|||
LET temp = a |
|||
LET a = b |
|||
LET b = temp |
|||
END SUB |
|||
LET a = 1 |
|||
LET b = 2 |
|||
PRINT a, b |
|||
CALL swap(a, b) |
|||
PRINT a, b |
|||
END</syntaxhighlight> |
|||
==={{header|uBasic/4tH}}=== |
|||
Since uBasic/4tH has a stack (just like [[Forth]]) and it is an integer BASIC only, this is quite trivial. However, making a function or procedure with the same functionality is impossible, because there is no way to pass variables by reference. |
|||
<syntaxhighlight lang="text">a = 5 : b = 7 |
|||
Print a,b |
|||
Push a,b : a = Pop() : b = Pop() |
|||
Print a,b</syntaxhighlight> |
|||
==={{header|VBScript}}=== |
|||
This works for everything: strings, dates, booleans ... The fact is, with everything being a Variant, it's always generic. |
|||
<syntaxhighlight lang="vb">sub swap( byref x, byref y ) |
|||
dim temp |
|||
temp = x |
|||
x = y |
|||
y = temp |
|||
end sub</syntaxhighlight> |
|||
Usage: |
|||
<syntaxhighlight lang="vb">dim a |
|||
a = "woof" |
|||
dim b |
|||
b = now() |
|||
swap a,b |
|||
wscript.echo a |
|||
wscript.echo b</syntaxhighlight> |
|||
{{out}} |
|||
<syntaxhighlight lang="vb">5/02/2010 2:35:36 PM |
|||
woof</syntaxhighlight> |
|||
==={{header|Visual Basic}}=== |
|||
Visual Basic can use the [[#VBScript|VBScript]] example above, with the caveat that it won't work if any <code>DEFtype</code> (except <code>DefVar</code>) has been used. (The default data type is <code>Variant</code>, which can be used as a stand-in for any variable type.) |
|||
Also, the sub will fail if one arg is a string containing non-numeric data and the other arg is numeric. |
|||
==={{header|Visual Basic .NET}}=== |
|||
Semantically identical to [[#C#|C#]] |
|||
<syntaxhighlight lang="vbnet">Sub Swap(Of T)(ByRef a As T, ByRef b As T) |
|||
Dim temp = a |
|||
a = b |
|||
b = temp |
|||
End Sub</syntaxhighlight> |
|||
Usage: |
|||
<syntaxhighlight lang="vbnet">Dim a = 1, b = 2 |
|||
Swap(a, b)</syntaxhighlight> |
|||
==={{header|XBasic}}=== |
|||
{{works with|Windows XBasic}} |
|||
XBasic already has a generic swap procedure built in, but a new subroutine can be defined: |
|||
<syntaxhighlight lang="qbasic"> |
|||
PROGRAM "nswap" |
|||
VERSION "0.0000" |
|||
DECLARE FUNCTION Entry () |
|||
FUNCTION Entry () |
|||
a = 1 |
|||
b = 2 |
|||
PRINT a, b |
|||
GOSUB nswap |
|||
PRINT a, b |
|||
SUB nswap |
|||
temp = a: a = b: b = temp |
|||
END SUB |
|||
END FUNCTION |
|||
END PROGRAM</syntaxhighlight> |
|||
==={{header|Yabasic}}=== |
|||
Yabasic already has a generic swap procedure built in. |
|||
<syntaxhighlight lang="yabasic">a = 1 |
|||
b = 2 |
|||
print a, b |
|||
//----- swap ---- |
|||
temp = a : a = b : b = temp |
|||
print a, b</syntaxhighlight> |
|||
=={{header|Batch File}}== |
|||
Swap using pass-by-name |
|||
<syntaxhighlight lang="dos">@echo off |
|||
setlocal enabledelayedexpansion |
|||
set a=1 |
|||
set b=woof |
|||
echo %a% |
|||
echo %b% |
|||
call :swap a b |
|||
echo %a% |
|||
echo %b% |
|||
goto :eof |
|||
:swap |
|||
set temp1=!%1! |
|||
set temp2=!%2! |
|||
set %1=%temp2% |
|||
set %2=%temp1% |
|||
goto :eof</syntaxhighlight> |
|||
=={{header|Beads}}== |
|||
<syntaxhighlight lang="beads">beads 1 program 'Generic swap' |
|||
var |
|||
a = [1 2 "Beads" 3 4] |
|||
b = [1 2 "Language" 4 5] |
|||
calc main_init |
|||
swap a[4] <=> b[3]</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
A = [1, 2, "Beads", 3, 4] |
|||
B = [1, 2, "Language", 4, 5] |
|||
------------------------------------------------- |
|||
A = [1, 2, "Beads", "Language", 4] |
|||
B = [1, 2, 3, 4, 5] |
|||
</pre> |
|||
=={{header|Binary Lambda Calculus}}== |
|||
From https://github.com/tromp/AIT/blob/master/rosetta/swap.lam we get the 25-bit swap function |
|||
<pre>0001100000000101101101110</pre> |
|||
=={{header|BQN}}== |
|||
Two variables can be exchanged with modified assignment: |
|||
<syntaxhighlight lang="bqn">a‿b ⌽↩</syntaxhighlight> |
|||
With no right-hand side, this expands to a one-argument call <code>a‿b ↩ ⌽ a‿b</code>. BQN doesn't make variable names or references first-class, so it wouldn't make sense to make this generic over variable names. |
|||
=={{header|Bracmat}}== |
=={{header|Bracmat}}== |
||
< |
<syntaxhighlight lang="bracmat">(!a.!b):(?b.?a)</syntaxhighlight> |
||
=={{header|Burlesque}}== |
=={{header|Burlesque}}== |
||
< |
<syntaxhighlight lang="burlesque"> |
||
\/ |
\/ |
||
</syntaxhighlight> |
|||
</lang> |
|||
Stack-based swap. |
Stack-based swap. |
||
Line 285: | Line 888: | ||
This has a restriction that a and b must be the same size. |
This has a restriction that a and b must be the same size. |
||
< |
<syntaxhighlight lang="c">void swap(void *va, void *vb, size_t s) |
||
{ |
{ |
||
char t, *a = (char*)va, *b = (char*)vb; |
char t, *a = (char*)va, *b = (char*)vb; |
||
while(s--) |
while(s--) |
||
t = a[s], a[s] = b[s], b[s] = t; |
t = a[s], a[s] = b[s], b[s] = t; |
||
}</ |
}</syntaxhighlight> |
||
{{works with|gcc}} |
{{works with|gcc}} |
||
Line 297: | Line 900: | ||
* ''Caution:'' <tt>__typeof__</tt> is a gcc extension, not part of standard C. <tt>__typeof__</tt> does not conflict with C89 because the standard allows compilers to add keywords with underscores like <tt>__typeof__</tt>. |
* ''Caution:'' <tt>__typeof__</tt> is a gcc extension, not part of standard C. <tt>__typeof__</tt> does not conflict with C89 because the standard allows compilers to add keywords with underscores like <tt>__typeof__</tt>. |
||
< |
<syntaxhighlight lang="c">#define Swap(X,Y) do{ __typeof__ (X) _T = X; X = Y; Y = _T; }while(0)</syntaxhighlight> |
||
Usage examples are: |
Usage examples are: |
||
< |
<syntaxhighlight lang="c">#include <stdio.h> |
||
#define Swap(X,Y) do{ __typeof__ (X) _T = X; X = Y; Y = _T; }while(0) |
#define Swap(X,Y) do{ __typeof__ (X) _T = X; X = Y; Y = _T; }while(0) |
||
Line 332: | Line 935: | ||
Swap(pt, th); |
Swap(pt, th); |
||
printf("%d\n", pt->a); |
printf("%d\n", pt->a); |
||
}</ |
}</syntaxhighlight> |
||
This is tested with GCC with <tt>-std=c89</tt> option. |
This is tested with GCC with <tt>-std=c89</tt> option. |
||
=={{header|C sharp|C#}}== |
|||
===C#: Using a generic method=== |
|||
{{works with|C sharp|C#|2.0+}} |
|||
C# 2.0 introduced the concept of generics to the language. Generics are outwardly |
|||
similar to C++ templates, but are implemented quite differently: generics are |
|||
maintained generically at runtime rather than being substitued with definite types |
|||
by the compiler. Generics are intended to promote reusable, efficient, type-safe |
|||
code, and are used widely throughout the .NET framework and 3rd party libraries, |
|||
especially in collections. C# generics are less flexible than C++ templates, but |
|||
are more strongly typed and arguably easier to work with. |
|||
<syntaxhighlight lang="csharp">static void Swap<T>(ref T a, ref T b) |
|||
{ |
|||
T temp = a; |
|||
a = b; |
|||
b = temp; |
|||
}</syntaxhighlight> |
|||
Usage: |
|||
<syntaxhighlight lang="csharp">int a = 1; |
|||
int b = 2; |
|||
Swap(ref a, ref b); // Type parameter is inferred.</syntaxhighlight> |
|||
===C#: Using tuple syntax=== |
|||
{{works with|C sharp|C#|7.0+}} |
|||
C# 7.0 introduced language support for tuples, which are implemented using the <code>ValueTuple</code> family of structs. The example below creates a tuple with the values of <code>b</code> and <code>a</code> and uses deconstructing assignment to assign the members of the tuple back to the variables. |
|||
<syntaxhighlight lang="csharp">int a = 1; |
|||
int b = 2; |
|||
(a, b) = (b, a);</syntaxhighlight> |
|||
=={{header|C++}}== |
=={{header|C++}}== |
||
Line 343: | Line 978: | ||
The implementation of the swap function template is straightforward: |
The implementation of the swap function template is straightforward: |
||
< |
<syntaxhighlight lang="cpp">template<typename T> void swap(T& left, T& right) |
||
{ |
{ |
||
T tmp(left); |
T tmp(left); |
||
left = right; |
left = right; |
||
right = tmp; |
right = tmp; |
||
}</ |
}</syntaxhighlight> |
||
Note that this function requires that the type T has an accessible copy constructor and assignment operator. |
Note that this function requires that the type T has an accessible copy constructor and assignment operator. |
||
Line 354: | Line 989: | ||
The standard utility 'swap' can be used to swap two values: |
The standard utility 'swap' can be used to swap two values: |
||
<lang |
<syntaxhighlight lang="cpp">std::swap(x,y);</syntaxhighlight> |
||
It will work with any types. |
It will work with any types. |
||
Line 360: | Line 995: | ||
===C++11=== |
===C++11=== |
||
C++11 adds move constructors which can be more efficient than copy constructors. |
C++11 adds move constructors which can be more efficient than copy constructors. |
||
< |
<syntaxhighlight lang="cpp">template<class T> |
||
void swap(T &lhs, T &rhs){ |
void swap(T &lhs, T &rhs){ |
||
T tmp = std::move(lhs); |
T tmp = std::move(lhs); |
||
lhs = std::move(rhs); |
lhs = std::move(rhs); |
||
rhs = std::move(tmp); |
rhs = std::move(tmp); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|C sharp|C#}}== |
|||
{{works with|C sharp|C#|2.0+}} |
|||
C# 2.0 introduced the concept of generics to the language. Generics are outwardly |
|||
similar to C++ templates, but are implemented quite differently: generics are |
|||
maintained generically at runtime rather than being substitued with definite types |
|||
by the compiler. Generics are intended to promote reusable, efficient, type-safe |
|||
code, and are used widely throughout the .NET framework and 3rd party libraries, |
|||
especially in collections. C# generics are less flexible than C++ templates, but |
|||
are more strongly typed and arguably easier to deal with. |
|||
<lang csharp>static void Swap<T>(ref T a, ref T b) |
|||
{ |
|||
T temp = a; |
|||
a = b; |
|||
b = temp; |
|||
}</lang> |
|||
=={{header|Chapel}}== |
=={{header|Chapel}}== |
||
Chapel includes a swap operator: |
Chapel includes a swap operator: |
||
< |
<syntaxhighlight lang="chapel">a <=> b</syntaxhighlight> |
||
and supports swapping directly via tuples and destructuring: |
and supports swapping directly via tuples and destructuring: |
||
< |
<syntaxhighlight lang="chapel">(a, b) = (b, a)</syntaxhighlight> |
||
Both variables must be of the same type. |
Both variables must be of the same type. |
||
The [[Fibonacci sequence#Chapel|Fibonnacci implementation]] contains an example. |
The [[Fibonacci sequence#Chapel|Fibonnacci implementation]] contains an example. |
||
=={{header|Clojure}}== |
=={{header|Clojure}}== |
||
< |
<syntaxhighlight lang="lisp"> |
||
(defn swap [pair] (reverse pair)) ; returns a list |
(defn swap [pair] (reverse pair)) ; returns a list |
||
(defn swap [[a b]] '(b a)) ; returns a list |
(defn swap [[a b]] '(b a)) ; returns a list |
||
(defn swap [[a b]] [b a]) ; returns a vector |
(defn swap [[a b]] [b a]) ; returns a vector |
||
</syntaxhighlight> |
|||
</lang> |
|||
The latter two implementations use destructured binding to define local names for the two elements. |
The latter two implementations use destructured binding to define local names for the two elements. |
||
Line 405: | Line 1,022: | ||
CMake has only one data type: the string. |
CMake has only one data type: the string. |
||
< |
<syntaxhighlight lang="cmake">function(swap var1 var2) |
||
set(_SWAP_TEMPORARY "${${var1}}") |
set(_SWAP_TEMPORARY "${${var1}}") |
||
set(${var1} "${${var2}}" PARENT_SCOPE) |
set(${var1} "${${var2}}" PARENT_SCOPE) |
||
set(${var2} "${_SWAP_TEMPORARY}" PARENT_SCOPE) |
set(${var2} "${_SWAP_TEMPORARY}" PARENT_SCOPE) |
||
endfunction(swap)</ |
endfunction(swap)</syntaxhighlight> |
||
< |
<syntaxhighlight lang="cmake">set(x 42) |
||
set(y "string") |
set(y "string") |
||
swap(x y) |
swap(x y) |
||
message(STATUS ${x}) # -- string |
message(STATUS ${x}) # -- string |
||
message(STATUS ${y}) # -- 42</ |
message(STATUS ${y}) # -- 42</syntaxhighlight> |
||
Because of limitations in CMake, there are a few specific situations where swap() will fail to swap the variables. |
Because of limitations in CMake, there are a few specific situations where swap() will fail to swap the variables. |
||
# When ''_SWAP_TEMPORARY'' is the name of the second variable: < |
# When ''_SWAP_TEMPORARY'' is the name of the second variable: <syntaxhighlight lang="cmake">set(x 42) |
||
set(_SWAP_TEMPORARY "string") |
set(_SWAP_TEMPORARY "string") |
||
swap(x _SWAP_TEMPORARY) |
swap(x _SWAP_TEMPORARY) |
||
message(STATUS ${x}) # -- 42 |
message(STATUS ${x}) # -- 42 |
||
message(STATUS ${_SWAP_TEMPORARY}) # -- 42</ |
message(STATUS ${_SWAP_TEMPORARY}) # -- 42</syntaxhighlight> Inside swap(), its local variable ''_SWAP_TEMPORARY'' shadows the original ''_SWAP_TEMPORARY'' from the parent scope, preventing access to the original value. |
||
# When value of either variable is "CACHE" or "PARENT_SCOPE": < |
# When value of either variable is "CACHE" or "PARENT_SCOPE": <syntaxhighlight lang="cmake">string(TOUPPER CACHE x) |
||
set(y "string") |
set(y "string") |
||
swap(x y) # CMake Error... set given invalid arguments for CACHE mode.</ |
swap(x y) # CMake Error... set given invalid arguments for CACHE mode.</syntaxhighlight> swap() can never set a variable to "CACHE" or "PARENT_SCOPE", because these are keywords of set() command. |
||
=={{header| |
=={{header|COBOL}}== |
||
<syntaxhighlight lang="cobol"> |
|||
<lang lisp>(rotatef a b) |
|||
PROGRAM-ID. SWAP-DEMO. |
|||
AUTHOR. Bill Gunshannon. |
|||
INSTALLATION. Home. |
|||
DATE-WRITTEN. 16 December 2021. |
|||
************************************************************ |
|||
** Program Abstract: |
|||
** A simple program to demonstrate the SWAP subprogram. |
|||
** |
|||
************************************************************ |
|||
DATA DIVISION. |
|||
WORKING-STORAGE SECTION. |
|||
01 Val1 PIC X(72). |
|||
01 Val2 PIC X(72). |
|||
PROCEDURE DIVISION. |
|||
Main-Program. |
|||
DISPLAY 'Enter a Value: ' WITH NO ADVANCING. |
|||
(psetq a b b a)</lang> |
|||
ACCEPT Val1. |
|||
DISPLAY 'Enter another Value: ' WITH NO ADVANCING. |
|||
ACCEPT Val2. |
|||
DISPLAY ' ' . |
|||
DISPLAY 'First value: ' FUNCTION TRIM(Val1) . |
|||
DISPLAY 'Second value: ' FUNCTION TRIM(Val2) . |
|||
CALL "SWAP" USING BY REFERENCE Val1, BY REFERENCE Val2. |
|||
DISPLAY ' '. |
|||
DISPLAY 'After SWAP '. |
|||
DISPLAY ' '. |
|||
DISPLAY 'First value: ' FUNCTION TRIM(Val1). |
|||
DISPLAY 'Second value: ' FUNCTION TRIM(Val2). |
|||
STOP RUN. |
|||
END PROGRAM SWAP-DEMO. |
|||
IDENTIFICATION DIVISION. |
|||
PROGRAM-ID. SWAP. |
|||
AUTHOR. Bill Gunshannon. |
|||
INSTALLATION. Home. |
|||
DATE-WRITTEN. 16 December 2021. |
|||
************************************************************ |
|||
** Program Abstract: |
|||
** SWAP any Alphanumeric value. Only limit is 72 |
|||
** character size. But that can be adjusted for |
|||
** whatever use one needs. |
|||
************************************************************ |
|||
DATA DIVISION. |
|||
WORKING-STORAGE SECTION. |
|||
01 TEMP PIC X(72). |
|||
LINKAGE SECTION. |
|||
01 Field1 PIC X(72). |
|||
01 Field2 PIC X(72). |
|||
PROCEDURE DIVISION |
|||
USING BY REFERENCE Field1, BY REFERENCE Field2. |
|||
MOVE Field1 to TEMP. |
|||
MOVE Field2 to Field1. |
|||
MOVE TEMP to Field2. |
|||
GOBACK. |
|||
END PROGRAM SWAP. |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Enter a Value: 33 |
|||
Enter another Value: 77 |
|||
First value: 33 |
|||
Second value: 77 |
|||
After SWAP |
|||
First value: 77 |
|||
Second value: 33 |
|||
-------------------------------- |
|||
Enter a Value: Hello World |
|||
Enter another Value: Good Bye |
|||
First value: Hello World |
|||
Second value: Good Bye |
|||
After SWAP |
|||
First value: Good Bye |
|||
Second value: Hello World |
|||
</pre> |
|||
=={{header|ColdFusion}}== |
=={{header|ColdFusion}}== |
||
This is another standard swap. |
This is another standard swap. |
||
< |
<syntaxhighlight lang="cfm"><cfset temp = a /> |
||
<cfset a = b /> |
<cfset a = b /> |
||
<cfset b = temp /></ |
<cfset b = temp /></syntaxhighlight> |
||
=={{header|Common Lisp}}== |
|||
<syntaxhighlight lang="lisp">(rotatef a b) |
|||
(psetq a b b a)</syntaxhighlight> |
|||
=={{header|Computer/zero Assembly}}== |
|||
<syntaxhighlight lang="6502asm">LDA 29 |
|||
STA 31 |
|||
LDA 30 |
|||
STA 29 |
|||
LDA 31 |
|||
STA 30 |
|||
STP |
|||
--- |
|||
org 29 |
|||
byte $0F |
|||
byte $E0 |
|||
byte $00</syntaxhighlight> |
|||
{{out}} |
|||
[http://www.edmundgriffiths.com/czero.html?hexdump=3d5f3e5d3f5ee0000000000000000000000000000000000000000000000fe000 Emulator with program loaded] |
|||
Hexdump of address 29-31 after running: |
|||
<pre>E0 0F 0F</pre> |
|||
=={{header|Crystal}}== |
|||
Crystal directly supports swapping: |
|||
<syntaxhighlight lang="ruby">a, b = b, a</syntaxhighlight> |
|||
=={{header|D}}== |
=={{header|D}}== |
||
< |
<syntaxhighlight lang="d">import std.algorithm: swap; // from Phobos standard library |
||
// The D solution uses templates and it's similar to the C++ one: |
// The D solution uses templates and it's similar to the C++ one: |
||
Line 464: | Line 1,211: | ||
mySwap(a[0], a[1]); |
mySwap(a[0], a[1]); |
||
writeln(a); |
writeln(a); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>[10, 20] |
<pre>[10, 20] |
||
Line 472: | Line 1,219: | ||
=={{header|dc}}== |
=={{header|dc}}== |
||
We use two registers to swap in POSIX dc. |
We use two registers to swap in POSIX dc. |
||
< |
<syntaxhighlight lang="dc">1 2 SaSbLaLb f |
||
=2 1</ |
=2 1</syntaxhighlight> |
||
Reverse (r) is a built-in stack command available as a GNU extension for dc. |
Reverse (r) is a built-in stack command available as a GNU extension for dc. |
||
< |
<syntaxhighlight lang="dc">1 2 r f |
||
=2 1</ |
=2 1</syntaxhighlight> |
||
=={{header|DCL}}== |
=={{header|DCL}}== |
||
symbols do not have to be declared, they can be integers or strings, they can change type on the fly |
symbols do not have to be declared, they can be integers or strings, they can change type on the fly |
||
< |
<syntaxhighlight lang="dcl">$ a1 = 123 |
||
$ a2 = "hello" |
$ a2 = "hello" |
||
$ show symbol a* |
$ show symbol a* |
||
Line 490: | Line 1,238: | ||
$ a1 = a2 |
$ a1 = a2 |
||
$ a2 = t |
$ a2 = t |
||
$ return</ |
$ return</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>$ @generic_swap |
<pre>$ @generic_swap |
||
Line 497: | Line 1,245: | ||
A1 = "hello" |
A1 = "hello" |
||
A2 = 123 Hex = 0000007B Octal = 00000000173</pre> |
A2 = 123 Hex = 0000007B Octal = 00000000173</pre> |
||
=={{header|Déjà Vu}}== |
|||
To swap the two top-most items on the stack: |
|||
<lang dejavu>swap</lang> |
|||
To swap two variables without needing a third name, using the stack for temporary storage: |
|||
<lang dejavu>set :a set :b @a @b</lang> |
|||
=={{header|Delphi}}== |
=={{header|Delphi}}== |
||
Delphi does not have generics as such. The following code must be copied for each type that a swap is required. T should be changed to the required type. |
Delphi does not have generics as such. The following code must be copied for each type that a swap is required. T should be changed to the required type. |
||
<syntaxhighlight lang="delphi"> |
|||
<lang Delphi> |
|||
procedure Swap_T(var a, b: T); |
procedure Swap_T(var a, b: T); |
||
var |
var |
||
Line 515: | Line 1,257: | ||
b := temp; |
b := temp; |
||
end; |
end; |
||
</syntaxhighlight> |
|||
</lang> |
|||
Generics were introduced with Delphi 2009 |
Generics were introduced with Delphi 2009 |
||
<syntaxhighlight lang="delphi"> |
|||
<lang Delphi> |
|||
program GenericSwap; |
program GenericSwap; |
||
Line 545: | Line 1,287: | ||
writeln('After swap: a=', a, ' b=', b); |
writeln('After swap: a=', a, ' b=', b); |
||
end. |
end. |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Déjà Vu}}== |
|||
To swap the two top-most items on the stack: |
|||
<syntaxhighlight lang="dejavu">swap</syntaxhighlight> |
|||
To swap two variables without needing a third name, using the stack for temporary storage: |
|||
<syntaxhighlight lang="dejavu">set :a set :b @a @b</syntaxhighlight> |
|||
=={{header|E}}== |
=={{header|E}}== |
||
(slots) |
(slots) |
||
< |
<syntaxhighlight lang="e">def swap(&left, &right) { |
||
def t := left |
def t := left |
||
left := right |
left := right |
||
right := t |
right := t |
||
}</ |
}</syntaxhighlight> |
||
(functional) |
(functional) |
||
< |
<syntaxhighlight lang="e">def swap([left, right]) { |
||
return [right, left] |
return [right, left] |
||
}</ |
}</syntaxhighlight> |
||
=={{header|EchoLisp}}== |
=={{header|EchoLisp}}== |
||
< |
<syntaxhighlight lang="lisp"> |
||
;; 1) |
;; 1) |
||
;; a macro will do it, as shown in Racket (same syntax) |
;; a macro will do it, as shown in Racket (same syntax) |
||
Line 584: | Line 1,332: | ||
(list-swap! L 1 ' 🎩 ) |
(list-swap! L 1 ' 🎩 ) |
||
→ (🎩 2 3 4 1) |
→ (🎩 2 3 4 1) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Elena}}== |
|||
ELENA 4.1 : |
|||
<syntaxhighlight lang="elena">import extensions; |
|||
swap(ref object v1, ref object v2) |
|||
{ |
|||
var tmp := v1; |
|||
v1 := v2; |
|||
v2 := tmp |
|||
} |
|||
public program() |
|||
{ |
|||
var n := 2; |
|||
var s := "abc"; |
|||
console.printLine(n," ",s); |
|||
swap(ref n, ref s); |
|||
console.printLine(n," ",s) |
|||
}</syntaxhighlight> |
|||
<pre> |
|||
2 abc |
|||
abc 2 |
|||
</pre> |
|||
=={{header|Elixir}}== |
=={{header|Elixir}}== |
||
Elixir provides a robust mechanism of pattern matching; the <code>=</code> operator is actually the match operator. Using the match operator, values can be assigned and variables can be bound or unbound, but only on the left (<code>=:</code>). |
Elixir provides a robust mechanism of pattern matching; the <code>=</code> operator is actually the match operator. Using the match operator, values can be assigned and variables can be bound or unbound, but only on the left (<code>=:</code>). |
||
<syntaxhighlight lang="elixir"> |
|||
<lang Elixir> |
|||
x = 4 |
x = 4 |
||
y = 5 |
y = 5 |
||
Line 599: | Line 1,375: | ||
x # => 4 |
x # => 4 |
||
y # => 5 |
y # => 5 |
||
</syntaxhighlight> |
|||
</lang> |
|||
Data structures can be used both for matching and for generally destructuring complex data. We can use anonymous functions to create a generic swap in iex. Note: using multiple value requires a data construct on which to match (as opposed to, say, Ruby's <code>a,b = 1,2</code>), but we can use a list: |
Data structures can be used both for matching and for generally destructuring complex data. We can use anonymous functions to create a generic swap in iex. Note: using multiple value requires a data construct on which to match (as opposed to, say, Ruby's <code>a,b = 1,2</code>), but we can use a list: |
||
<syntaxhighlight lang="elixir"> |
|||
<lang Elixir> |
|||
swap = fn x,y -> [y|x] end |
swap = fn x,y -> [y|x] end |
||
[x|y] = swap.(1,2) |
[x|y] = swap.(1,2) |
||
x # => 2 |
x # => 2 |
||
y # => 1 |
y # => 1 |
||
</syntaxhighlight> |
|||
</lang> |
|||
Variables can be bound and rebound regardless of type |
Variables can be bound and rebound regardless of type |
||
<syntaxhighlight lang="elixir"> |
|||
<lang Elixir> |
|||
swap_tuple = fn {x,y} -> {y,x} end |
swap_tuple = fn {x,y} -> {y,x} end |
||
{a,b} = swap_tuple.({1,:ok}) |
{a,b} = swap_tuple.({1,:ok}) |
||
Line 620: | Line 1,396: | ||
a # => "2" |
a # => "2" |
||
b # => 1 |
b # => 1 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Emacs Lisp}}== |
=={{header|Emacs Lisp}}== |
||
< |
<syntaxhighlight lang="lisp">(defun swap (a-sym b-sym) |
||
"Swap values of the variables given by A-SYM and B-SYM." |
"Swap values of the variables given by A-SYM and B-SYM." |
||
(let ((a-val (symbol-value a-sym))) |
(let ((a-val (symbol-value a-sym))) |
||
(set a-sym (symbol-value b-sym)) |
(set a-sym (symbol-value b-sym)) |
||
(set b-sym a-val))) |
(set b-sym a-val))) |
||
(swap 'a 'b)</ |
(swap 'a 'b)</syntaxhighlight> |
||
A macro can take variable names unquoted. Here <code>prog1</code> eliminates the temporary variable above so as to avoid any chance of a name clash between the two variables and the temporary. |
A macro can take variable names unquoted. Here <code>prog1</code> eliminates the temporary variable above so as to avoid any chance of a name clash between the two variables and the temporary. |
||
< |
<syntaxhighlight lang="lisp">(defmacro swap (a b) |
||
`(setq ,b (prog1 ,a (setq ,a ,b))))</ |
`(setq ,b (prog1 ,a (setq ,a ,b))))</syntaxhighlight> |
||
A macro could use the <code>cl |
A macro could use the <code>cl-lib</code> <code>psetf</code> which can store to various kinds of expressions as locations, for example list elements. <code>psetf</code> evaluates all its values before storing (like the [[#Common Lisp|Common Lisp example]]). |
||
< |
<syntaxhighlight lang="lisp">(require 'cl-lib) |
||
(defmacro swap (a b) |
(defmacro swap (a b) |
||
`(psetf ,a ,b |
`(cl-psetf ,a ,b |
||
,b ,a)) |
,b ,a)) |
||
(setq lst (list 123 456)) |
(setq lst (list 123 456)) |
||
(swap (car lst) (cadr lst)) |
(swap (car lst) (cadr lst)) |
||
;; now lst is '(456 123)</ |
;; now lst is '(456 123)</syntaxhighlight> |
||
=={{header|EMal}}== |
|||
<syntaxhighlight lang="emal"> |
|||
fun swap = Pair by var a, var b do return var%var(b => a) end |
|||
int a = 1 |
|||
int b = 2 |
|||
writeLine("before swap: a=" + a + ", b=" + b) |
|||
Pair pair = swap(a, b) |
|||
a = pair[0] |
|||
b = pair[1] |
|||
writeLine(" after swap: a=" + a + ", b=" + b) |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
before swap: a=1, b=2 |
|||
after swap: a=2, b=1 |
|||
</pre> |
|||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
Line 652: | Line 1,445: | ||
The closest thing would be to swap the items in a list (shown in the shell). |
The closest thing would be to swap the items in a list (shown in the shell). |
||
<syntaxhighlight lang="erlang"> |
|||
<lang Erlang> |
|||
1> L = [a, 2]. |
1> L = [a, 2]. |
||
[a,2] |
[a,2] |
||
2> lists:reverse(L). |
2> lists:reverse(L). |
||
[2,a] |
[2,a] |
||
</syntaxhighlight> |
|||
</lang> |
|||
Or swap the items in a tuple (also shown in the shell). |
Or swap the items in a tuple (also shown in the shell). |
||
<syntaxhighlight lang="erlang"> |
|||
<lang Erlang> |
|||
1> T = {2,a}. |
1> T = {2,a}. |
||
{2,a} |
{2,a} |
||
2> list_to_tuple(lists:reverse(tuple_to_list(T))). |
2> list_to_tuple(lists:reverse(tuple_to_list(T))). |
||
{a,2} |
{a,2} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{omit from|Euphoria}} |
{{omit from|Euphoria}} |
||
=={{header|Euphoria}}== |
|||
<syntaxhighlight lang="euphoria"> |
|||
include std/console.e -- for display |
|||
object x = 3.14159 |
|||
object y = "Rosettacode" |
|||
{y,x} = {x,y} |
|||
display("x is now []",{x}) |
|||
display("y is now []",{y}) |
|||
</syntaxhighlight> |
|||
<pre> |
|||
x is now Rosettacode |
|||
y is now 3.14159 |
|||
</pre> |
|||
objects are generic, and can accept any type. |
|||
More strongly-typed variables can be swapped, if their types match or if the value is "acceptable" to the declared type. |
|||
In the above example, if we declared y as an integer, the swap would fail, pi is not an integer. |
|||
If we declare y as an atom, it would succeed, as atoms can contain any valid number. |
|||
If we declare y as a sequence or string, it would fail, because x is atomic. |
|||
=={{header|F_Sharp|F#}}== |
=={{header|F_Sharp|F#}}== |
||
< |
<syntaxhighlight lang="fsharp">let swap (a,b) = (b,a)</syntaxhighlight> |
||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
Depending on how you look at it: this task doesn't apply, or it's trivial: |
Depending on how you look at it: this task doesn't apply, or it's trivial: |
||
<lang |
<syntaxhighlight lang="factor">swap</syntaxhighlight> |
||
=={{header|Falcon}}== |
=={{header|Falcon}}== |
||
< |
<syntaxhighlight lang="falcon"> |
||
a = 1 |
a = 1 |
||
b = 2 |
b = 2 |
||
a,b = arr = b,a |
a,b = arr = b,a |
||
</syntaxhighlight> |
|||
</lang> |
|||
Reading right to left: Assign b & a into an array variable called arr, then assign into a & b |
Reading right to left: Assign b & a into an array variable called arr, then assign into a & b |
||
=={{header|Fish}}== |
|||
Swap the top two values on the stack: |
|||
<syntaxhighlight lang="fish">$</syntaxhighlight> |
|||
=={{header|Forth}}== |
|||
Since the Forth stack can contain pointers to any data type all we need is... |
|||
<!-- if this is deemed unworthy, then the Factor, Postscript, and Retro examples should also be removed --> |
|||
<syntaxhighlight lang="forth">swap</syntaxhighlight> |
|||
=={{header|Fortran}}== |
=={{header|Fortran}}== |
||
{{works with|Fortran|90 and later}} |
{{works with|Fortran|90 and later}} |
||
< |
<syntaxhighlight lang="fortran">MODULE Genericswap |
||
IMPLICIT NONE |
IMPLICIT NONE |
||
Line 728: | Line 1,557: | ||
WRITE(*,*) r1, r2 ! Prints 2.0 and 1.0 |
WRITE(*,*) r1, r2 ! Prints 2.0 and 1.0 |
||
WRITE(*,*) s1, s2 ! Prints xyz and abc |
WRITE(*,*) s1, s2 ! Prints xyz and abc |
||
END PROGRAM EXAMPLE</ |
END PROGRAM EXAMPLE</syntaxhighlight> |
||
=={{header| |
=={{header|Free Pascal}}== |
||
<syntaxhighlight lang="pascal">{$ifdef fpc}{$mode delphi}{$H+}{$endif} |
|||
Since the Forth stack can contain pointers to any data type all we need is... |
|||
{ note this is compiled with delphi mode but will only compile in Free Pascal } |
|||
<!-- if this is deemed unworthy, then the Factor, Postscript, and Retro examples should also be removed --> |
|||
{ Delphi doesn't support this syntax } |
|||
<lang forth>swap</lang> |
|||
procedure swap<T>(var left,right:T); |
|||
var |
|||
temp:T; |
|||
begin |
|||
temp:=left; |
|||
left:=right; |
|||
right:=temp; |
|||
end; |
|||
var |
|||
a:string = 'Test'; |
|||
b:string = 'me'; |
|||
begin |
|||
writeln(a:6,b:6); |
|||
swap<string>(a,b); |
|||
writeln(a:6,b:6); |
|||
end.</syntaxhighlight> |
|||
<pre> |
|||
Output: |
|||
Test me |
|||
me Test</pre> |
|||
=={{header|Frink}}== |
=={{header|Frink}}== |
||
The following example will work on all Frink data types: |
The following example will work on all Frink data types: |
||
< |
<syntaxhighlight lang="frink"> |
||
[b,a] = [a,b] |
[b,a] = [a,b] |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Fōrmulæ}}== |
|||
{{FormulaeEntry|page=https://formulae.org/?script=examples/Generic_swap}} |
|||
'''Solution''' |
|||
Fōrmulæ supports assignments of several symbols (provided as a list) from an expression that reduces to a list of the same cardinality (the expression is first reduced before the actual assignment). |
|||
This can be used to do a generic swap as follows: |
|||
[[File:Fōrmulæ - Generic swap 01.png]] |
|||
'''Test case''' |
|||
[[File:Fōrmulæ - Generic swap 02.png]] |
|||
[[File:Fōrmulæ - Generic swap 03.png]] |
|||
=={{header|Gecho}}== |
=={{header|Gecho}}== |
||
< |
<syntaxhighlight lang="gecho"> |
||
1 !0 2 !1 |
1 !0 2 !1 |
||
</syntaxhighlight> |
|||
</lang> |
|||
Now tape[0] and tape[1] are set to 1 and 2, respectively. |
Now tape[0] and tape[1] are set to 1 and 2, respectively. |
||
< |
<syntaxhighlight lang="gecho"> |
||
&0 &1 !0 pop !1 |
&0 &1 !0 pop !1 |
||
</syntaxhighlight> |
|||
</lang> |
|||
This pushes the value of tape[0] to the stack, tape[1] to the stack, sets tape[0] to the top element, and then pops it, then tape[1] to the top element. |
This pushes the value of tape[0] to the stack, tape[1] to the stack, sets tape[0] to the top element, and then pops it, then tape[1] to the top element. |
||
Line 755: | Line 1,622: | ||
===Built in=== |
===Built in=== |
||
Not a valid solution, since the task requires writing a function or operator, but it is worth mentioning that Go's built in assignment operator does generic swap. The following swaps the values of a and b as long as they are of identical type. |
Not a valid solution, since the task requires writing a function or operator, but it is worth mentioning that Go's built in assignment operator does generic swap. The following swaps the values of a and b as long as they are of identical type. |
||
< |
<syntaxhighlight lang="go">a, b = b, a</syntaxhighlight> |
||
===Pass interfaces=== |
===Pass interfaces=== |
||
A generic swap function can easily be written however, if you require the caller to use variables of the empty interface type. The empty interface can hold a value of any type. |
A generic swap function can easily be written however, if you require the caller to use variables of the empty interface type. The empty interface can hold a value of any type. |
||
< |
<syntaxhighlight lang="go">package main |
||
import "fmt" |
import "fmt" |
||
Line 771: | Line 1,638: | ||
swap(&a, &b) |
swap(&a, &b) |
||
fmt.Println(a, b) |
fmt.Println(a, b) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 780: | Line 1,647: | ||
===Pass pointers=== |
===Pass pointers=== |
||
Somewhat less restrictive, this version allows pointers of any type to be passed, as long as they are the same type. |
Somewhat less restrictive, this version allows pointers of any type to be passed, as long as they are the same type. |
||
< |
<syntaxhighlight lang="go">package main |
||
import ( |
import ( |
||
Line 830: | Line 1,697: | ||
swap(&g, &h) |
swap(&g, &h) |
||
fmt.Println("g h:", g, h) |
fmt.Println("g h:", g, h) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 849: | Line 1,716: | ||
Putting <code>&</code> in a call makes the parameter "call by reference", giving a command the opportunity to modify a variable in the caller. So to swap variables, |
Putting <code>&</code> in a call makes the parameter "call by reference", giving a command the opportunity to modify a variable in the caller. So to swap variables, |
||
< |
<syntaxhighlight lang="gri">`Swap Vars &.a. &.b.' |
||
{ |
{ |
||
new .temp. |
new .temp. |
||
Line 863: | Line 1,730: | ||
show .foo. " " .bar. |
show .foo. " " .bar. |
||
# prints "456 123"</ |
# prints "456 123"</syntaxhighlight> |
||
Or similar to swap synonyms (strings), |
Or similar to swap synonyms (strings), |
||
< |
<syntaxhighlight lang="gri">`Swap Syns &\a &\b' |
||
{ |
{ |
||
new \temp |
new \temp |
||
Line 881: | Line 1,748: | ||
show "\quux \xyzzy" |
show "\quux \xyzzy" |
||
# prints "two one"</ |
# prints "two one"</syntaxhighlight> |
||
=={{header|Groovy}}== |
=={{header|Groovy}}== |
||
Line 887: | Line 1,754: | ||
Groovy has support for swapping built in: |
Groovy has support for swapping built in: |
||
< |
<syntaxhighlight lang="groovy">(a, b) = [b, a]</syntaxhighlight> |
||
But the task calls for a "generic swap method" to be written, so here it is: |
But the task calls for a "generic swap method" to be written, so here it is: |
||
< |
<syntaxhighlight lang="groovy">def swap(a, b) { |
||
[b, a] |
[b, a] |
||
}</ |
}</syntaxhighlight> |
||
This function doesn't mutate anything, but simply returns a new list with the order of the elements switched. It can be used like shown below: |
This function doesn't mutate anything, but simply returns a new list with the order of the elements switched. It can be used like shown below: |
||
< |
<syntaxhighlight lang="groovy">def (x, y) = swap(1, 3) |
||
assert x == 3 |
assert x == 3 |
||
assert y == 1</ |
assert y == 1</syntaxhighlight> |
||
Some examples here show an in-place swap of indexed elements in an array or collection, so for completeness here is an in-place swap of arbitrary indexed elements in a list: |
Some examples here show an in-place swap of indexed elements in an array or collection, so for completeness here is an in-place swap of arbitrary indexed elements in a list: |
||
< |
<syntaxhighlight lang="groovy">def listSwap = { a, i, j -> |
||
assert (0..<(a.size())).containsAll([i,j]); |
assert (0..<(a.size())).containsAll([i,j]); |
||
a[[j,i]] = a[[i,j]] |
a[[j,i]] = a[[i,j]] |
||
Line 907: | Line 1,774: | ||
def list = [2,4,6,8] |
def list = [2,4,6,8] |
||
listSwap(list, 1, 3) |
listSwap(list, 1, 3) |
||
assert list == [2,8,6,4]</ |
assert list == [2,8,6,4]</syntaxhighlight> |
||
=={{header|Harbour}}== |
|||
Harbour has no build-in swap function, however, implemention of a UDF is a fairly easy task. And since it's a dynamic typed lang, there won't be problem while swapping different value types. |
|||
Implementation: (We exploit "pass by reference" method on the parameters used) |
|||
<syntaxhighlight lang="visualfoxpro">PROCEDURE Swap( /*@*/v1, /*@*/v2 ) |
|||
LOCAL xTmp |
|||
xTmp := v1 |
|||
v1 := v2 |
|||
v2 := xTmp |
|||
RETURN |
|||
</syntaxhighlight> |
|||
Sample code: |
|||
<syntaxhighlight lang="visualfoxpro"> FUNCTION Main() |
|||
LOCAL v1 := "World!", v2 := "Hello" |
|||
? v1, v2 // --> World! Hello |
|||
Swap( @v1, @v2 ) |
|||
? v1, v2 // --> Hello World! |
|||
RETURN 0 |
|||
</syntaxhighlight> |
|||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
=== Pure swap === |
|||
Like everything else in Haskell, tuples are immutable. This function doesn't mutate anything, but simply returns a new pair with the order of the elements switched. |
|||
Usually Haskellers prefer to work with immutable data. The following function doesn't mutate anything, but simply returns a new pair with the order of the elements switched. |
|||
The type signature, the first line, is optional; it may be inferred. |
The type signature, the first line, is optional; it may be inferred. |
||
< |
<syntaxhighlight lang="haskell">swap :: (a, b) -> (b, a) |
||
swap (x, y) = (y, x)</ |
swap (x, y) = (y, x)</syntaxhighlight> |
||
This <code>swap</code> function is available in the <code>Data.Tuple</code> standard library module in GHC 7.0+ |
This <code>swap</code> function is available in the <code>Data.Tuple</code> standard library module in GHC 7.0+ |
||
=== Swap mutable variables === |
|||
The following function swaps the contents of two mutable references. Again the type signature is optional. |
|||
<syntaxhighlight lang="haskell">import Control.Monad.Ref |
|||
swap :: MonadRef r m => r a -> r a -> m () |
|||
swap xRef yRef = do |
|||
x<-readRef xRef |
|||
y<-readRef yRef |
|||
writeRef xRef y |
|||
writeRef yRef x</syntaxhighlight> |
|||
=={{header|Icon}} and {{header|Unicon}}== |
=={{header|Icon}} and {{header|Unicon}}== |
||
Icon provides a :=: operator for this. Additionally, there is a reversible exchange operator <-> that reverses the exchange if resumed. |
Icon provides a :=: operator for this. Additionally, there is a reversible exchange operator <-> that reverses the exchange if resumed. |
||
< |
<syntaxhighlight lang="icon">procedure main() |
||
x := 1 |
x := 1 |
||
y := 2 |
y := 2 |
||
Line 928: | Line 1,826: | ||
if x <-> y & x < y then write(x, " ", y) |
if x <-> y & x < y then write(x, " ", y) |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|IDL}}== |
=={{header|IDL}}== |
||
IDL is dynamically typed and array-centric, so swapping is quite easy for any data type. The TEMPORARY function sets its argument to "undefined", and allows us to swap without any large copying. |
IDL is dynamically typed and array-centric, so swapping is quite easy for any data type. The TEMPORARY function sets its argument to "undefined", and allows us to swap without any large copying. |
||
< |
<syntaxhighlight lang="idl">pro swap, a, b |
||
c = temporary(a) |
c = temporary(a) |
||
a = temporary(b) |
a = temporary(b) |
||
b = temporary(c) |
b = temporary(c) |
||
end</ |
end</syntaxhighlight> |
||
=={{header|J}}== |
=={{header|J}}== |
||
Line 944: | Line 1,842: | ||
Shown here are a list of prime numbers and the result of J's parser on some random text (inverting the parsing process on the swapped result): |
Shown here are a list of prime numbers and the result of J's parser on some random text (inverting the parsing process on the swapped result): |
||
< |
<syntaxhighlight lang="j"> (<2 4) C. 2 3 5 7 11 13 17 19 |
||
2 3 11 7 5 13 17 19 |
2 3 11 7 5 13 17 19 |
||
(<0 3)&C.&.;:'Roses are red. Violets are blue.' |
(<0 3)&C.&.;:'Roses are red. Violets are blue.' |
||
Violets are red. Roses are blue.</ |
Violets are red. Roses are blue.</syntaxhighlight> |
||
Also, if the argument list can be guaranteed to be a pair, J's reverse primitive will swap the pair. |
Also, if the argument list can be guaranteed to be a pair, J's reverse primitive will swap the pair. |
||
< |
<syntaxhighlight lang="j"> |.2 3 |
||
3 2 |
3 2 |
||
|.&.;:'one two' |
|.&.;:'one two' |
||
two one</ |
two one</syntaxhighlight> |
||
A generic destructive swap of named values would instead require reference to the locations being destroyed. Here's an implementation of that: |
A generic destructive swap of named values would instead require reference to the locations being destroyed. Here's an implementation of that: |
||
< |
<syntaxhighlight lang="j">destructiveSwap=: {{ EMPTY[ (m;n)=: n ,&<&do m }}</syntaxhighlight> |
||
t=. do y |
|||
(y)=: do x |
|||
(x)=: t |
|||
i.0 0 NB. result is meaningless |
|||
)</lang> |
|||
Example use: |
Example use: |
||
< |
<syntaxhighlight lang="j"> V1=: 'cat' |
||
V2=: 7 |
V2=: 7 |
||
'V1' destructiveSwap 'V2' |
'V1' destructiveSwap 'V2' |
||
Line 973: | Line 1,866: | ||
7 |
7 |
||
V2 |
V2 |
||
cat</ |
cat</syntaxhighlight> |
||
=={{header|Jakt}}== |
|||
<syntaxhighlight lang="jakt"> |
|||
fn swap<T>(anon a: &mut T, anon b: &mut T) { |
|||
let temporary = *a |
|||
*a = *b |
|||
*b = temporary |
|||
} |
|||
fn main() { |
|||
mut a = "Hello" |
|||
mut b = "World" |
|||
println("{} {}", a, b) |
|||
swap(&mut a, &mut b) |
|||
println("{} {}", a, b) |
|||
mut c = 1 |
|||
mut d = 2 |
|||
println("{} {}", c, d) |
|||
swap(&mut c, &mut d) |
|||
println("{} {}", c, d) |
|||
} |
|||
</syntaxhighlight> |
|||
=={{header|Java}}== |
=={{header|Java}}== |
||
Line 980: | Line 1,898: | ||
Java uses references, so it can't swap the values of two variables that don't belong to a class. |
Java uses references, so it can't swap the values of two variables that don't belong to a class. |
||
< |
<syntaxhighlight lang="java">class Pair<T> { |
||
T first; |
T first; |
||
T second; |
T second; |
||
Line 988: | Line 1,906: | ||
p.first = p.second; |
p.first = p.second; |
||
p.second = temp; |
p.second = temp; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
Line 997: | Line 1,915: | ||
The below function expects an array of length 2 (or longer), and switches the first two values in place, in the same array. This is closely related to how the Java solution works. |
The below function expects an array of length 2 (or longer), and switches the first two values in place, in the same array. This is closely related to how the Java solution works. |
||
< |
<syntaxhighlight lang="javascript">function swap(arr) { |
||
var tmp = arr[0]; |
var tmp = arr[0]; |
||
arr[0] = arr[1]; |
arr[0] = arr[1]; |
||
arr[1] = tmp; |
arr[1] = tmp; |
||
}</ |
}</syntaxhighlight> |
||
Also there is metaprogramming solution. It uses code generation and <tt>eval</tt>. To avoid naming conflicts(user can pass <tt>'tmp'</tt>, which causes <tt>var tmp = tmp</tt>) it uses buildin, per activation context (thats why it is enclosed into self executing lambda), var <tt>arguments</tt> for temp storage. |
Also there is metaprogramming solution. It uses code generation and <tt>eval</tt>. To avoid naming conflicts(user can pass <tt>'tmp'</tt>, which causes <tt>var tmp = tmp</tt>) it uses buildin, per activation context (thats why it is enclosed into self executing lambda), var <tt>arguments</tt> for temp storage. |
||
< |
<syntaxhighlight lang="javascript">function swap(aName, bName) { |
||
eval('(function(){ arguments[0] = aName; aName = bName; bName = arguments[0] })()' |
|||
.replace(/aName/g, aName) |
.replace(/aName/g, aName) |
||
.replace(/bName/g, bName) |
.replace(/bName/g, bName) |
||
Line 1,012: | Line 1,930: | ||
var x = 1 |
var x = 1 |
||
var y = 2 |
var y = 2 |
||
swap('x', 'y') |
|||
</syntaxhighlight> |
|||
</lang> |
|||
Solution without <tt>eval()</tt>, assuming that the code is running in the browser (<tt>window</tt> is the global object) |
|||
<syntaxhighlight lang="javascript">function swap(a, b) { |
|||
var tmp = window[a]; |
|||
window[a] = window[b]; |
|||
window[b] = tmp; |
|||
} |
|||
var x = 1; |
|||
var y = 2; |
|||
swap('x', 'y'); |
|||
</syntaxhighlight> |
|||
Another solution for swapping array items using destructing assignment: |
|||
<syntaxhighlight lang="javascript">const arr = [1, 2, 3, 4, 5]; |
|||
[arr[0], arr[1]] = [arr[1], arr[0]] |
|||
</syntaxhighlight> |
|||
=={{header|Joy}}== |
=={{header|Joy}}== |
||
Provided that the stack contains at least two elements |
Provided that the stack contains at least two elements: |
||
<lang |
<syntaxhighlight lang="joy">swap</syntaxhighlight> |
||
changes the order of those elements |
changes the order of those elements. |
||
=={{header|jq}}== |
=={{header|jq}}== |
||
jq is a functional language, so one is more likely to want to swap the two elements of an array than to swap the values of two variables, but jq does have variables and their values can be swapped, for example, using an intermediate variable, say $tmp, as illustrated here:< |
jq is a functional language, so one is more likely to want to swap the two elements of an array than to swap the values of two variables, but jq does have variables and their values can be swapped, for example, using an intermediate variable, say $tmp, as illustrated here:<syntaxhighlight lang="jq">jq -n '1 as $a | 2 as $b | $a as $tmp | $b as $a | $tmp as $b | [$a,$b]'</syntaxhighlight> |
||
Here is a filter that will swap the elements of a two-element array: |
Here is a filter that will swap the elements of a two-element array: |
||
<lang |
<syntaxhighlight lang="jq">reverse</syntaxhighlight> |
||
And here is a filter that, if presented with an array, will in effect copy it and then swap the i-th and j-th items, it being understood that if a is an array and k < 0 or k >= (a|length), then a[k] will evaluate to null: |
And here is a filter that, if presented with an array, will in effect copy it and then swap the i-th and j-th items, it being understood that if a is an array and k < 0 or k >= (a|length), then a[k] will evaluate to null: |
||
< |
<syntaxhighlight lang="jq">def swap(i;j): .[i] as $t | .[i] = .[j] | .[j] = $t;</syntaxhighlight> |
||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
Similar to Python, Julia has built-in support for swapping: |
Similar to Python, Julia has built-in support for swapping: |
||
< |
<syntaxhighlight lang="julia">a, b = b, a</syntaxhighlight> |
||
=={{header|Kotlin}}== |
|||
As Kotlin does not support passing parameters by reference and tuples cannot be destructured automatically to pre-existing variables, it's just as easy to swap variable values 'inline' rather than using a function. However, here's one of way of doing it generically using the latter: |
|||
<syntaxhighlight lang="kotlin"> |
|||
fun <T> swap(t1: T, t2: T) = Pair(t2, t1) |
|||
fun main() { |
|||
var a = 3 |
|||
var b = 4 |
|||
val c = swap(a, b) // infers that swap<Int> be used |
|||
a = c.first |
|||
b = c.second |
|||
println("a = $a") |
|||
println("b = $b") |
|||
var d = false |
|||
var e = true |
|||
val f = swap(d, e) // infers that swap<Boolean> be used |
|||
d = f.first |
|||
e = f.second |
|||
println("d = $d") |
|||
println("e = $e") |
|||
}</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
a = 4 |
|||
b = 3 |
|||
d = true |
|||
e = false |
|||
</pre> |
|||
You can also explicitly create a container class and swap the value that it contains (but this is a bad idea in practice): |
|||
<syntaxhighlight lang="kotlin"> |
|||
data class Ref<T>(var value: T) { |
|||
fun swap(other: Ref<T>) { |
|||
val tmp = this.value |
|||
this.value = other.value |
|||
other.value = tmp |
|||
} |
|||
override fun toString() = "$value" |
|||
} |
|||
|
|||
fun main() { |
|||
val a = Ref(1) |
|||
val b = Ref(2) |
|||
a.swap(b) |
|||
println(a) |
|||
println(b) |
|||
} |
|||
</syntaxhighlight> |
|||
=={{header|Lambdatalk}}== |
|||
<syntaxhighlight lang="scheme"> |
|||
1) using an Immediately Invoked Function Expression: |
|||
{{lambda {:x :y} :y :x} hello world} |
|||
-> world hello |
|||
2) or user defined function |
|||
{def swap {lambda {:x :y} :y :x}} |
|||
-> swap |
|||
3) applied on words (which can be numbers) |
|||
{swap hello world} |
|||
-> world hello |
|||
{swap hello brave new world} |
|||
-> brave new hello world |
|||
{swap {cons hello brave} {cons new world}} |
|||
-> (new world) (hello brave) |
|||
</syntaxhighlight> |
|||
=={{header|Lang}}== |
|||
<syntaxhighlight lang="lang"> |
|||
# Swap function with call-by-pointer |
|||
fp.swap = ($[aPtr], $[bPtr]) -> { |
|||
$tmp = $*aPtr |
|||
$*aPtr = $*bPtr |
|||
$*bPtr = $tmp |
|||
} |
|||
$a = 42 |
|||
$b = A short text |
|||
fn.println($a, $b) |
|||
fp.swap($a, $b) |
|||
fn.println($a, $b) |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
42, A short text |
|||
A short text, 42 |
|||
</pre> |
|||
=={{header|Lang5}}== |
=={{header|Lang5}}== |
||
< |
<syntaxhighlight lang="lang5">swap # stack |
||
reverse # array</ |
reverse # array</syntaxhighlight> |
||
=={{header|langur}}== |
|||
Values can be swapped using multi-variable assignment. |
|||
<syntaxhighlight lang="langur"> |
|||
var abc = [1, 2, 3] |
|||
var def = [5, 6, 7] |
|||
abc[3], def[3] = def[3], abc[3] |
|||
writeln abc |
|||
writeln def |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre>[1, 2, 7] |
|||
[5, 6, 3]</pre> |
|||
=={{header|Lasso}}== |
=={{header|Lasso}}== |
||
< |
<syntaxhighlight lang="lasso">define swap(a, b) => (: #b, #a) |
||
local(a) = 'foo' |
local(a) = 'foo' |
||
Line 1,047: | Line 2,094: | ||
local(a,b) = swap(#a, #b) |
local(a,b) = swap(#a, #b) |
||
stdoutnl(#a) |
stdoutnl(#a) |
||
stdoutnl(#b)</ |
stdoutnl(#b)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,055: | Line 2,102: | ||
===Using Decompositional Assignment=== |
===Using Decompositional Assignment=== |
||
< |
<syntaxhighlight lang="lasso">local(a) = 'hair' |
||
local(b) = 'moose' |
local(b) = 'moose' |
||
local(a,b) = (: #b, #a) |
local(a,b) = (: #b, #a) |
||
stdoutnl(#a) |
stdoutnl(#a) |
||
stdoutnl(#b)</ |
stdoutnl(#b)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>moose |
<pre>moose |
||
hair</pre> |
hair</pre> |
||
=={{header|Lhogho}}== |
|||
Lhogho is very similar except that it does not have a localmake opcode. |
|||
<syntaxhighlight lang="logo"> |
|||
to swap :s1 :s2 |
|||
local "t |
|||
make "t thing :s1 |
|||
make :s1 thing :s2 |
|||
make :s2 :t |
|||
end |
|||
make "a 4 |
|||
make "b "dog |
|||
swap "a "b ; pass the names of the variables to swap |
|||
show list :a :b ; [dog 4] |
|||
</syntaxhighlight> |
|||
=={{header|Lingo}}== |
|||
A generic swap function is not possible in Lingo, since scalar values are passed by value. But the following solution shows how such generic swapping still can be achieved by executing a single line of code: |
|||
<syntaxhighlight lang="lingo">on swap (x, y) |
|||
return "tmp="&x&RETURN&x&"="&y&RETURN&y&"=tmp" |
|||
end</syntaxhighlight> |
|||
Usage: |
|||
<syntaxhighlight lang="lingo">x = 1 |
|||
y = 2 |
|||
do(swap("x","y")) |
|||
put x, y |
|||
-- 2 1</syntaxhighlight> |
|||
=={{header|Lisaac}}== |
=={{header|Lisaac}}== |
||
< |
<syntaxhighlight lang="lisaac">(a, b) := (b, a);</syntaxhighlight> |
||
=={{header|LiveCode}}== |
=={{header|LiveCode}}== |
||
< |
<syntaxhighlight lang="livecode">put "first" into a1 |
||
put "last" into b2 |
put "last" into b2 |
||
swap a1,b2 |
swap a1,b2 |
||
Line 1,078: | Line 2,154: | ||
put p1 into p2 |
put p1 into p2 |
||
put p3 into p1 |
put p3 into p1 |
||
end swap</ |
end swap</syntaxhighlight> |
||
=={{header|Logo}}== |
=={{header|Logo}}== |
||
< |
<syntaxhighlight lang="logo"> |
||
to swap :s1 :s2 |
to swap :s1 :s2 |
||
localmake "t thing :s1 |
localmake "t thing :s1 |
||
Line 1,092: | Line 2,168: | ||
swap "a "b ; pass the names of the variables to swap |
swap "a "b ; pass the names of the variables to swap |
||
show list :a :b ; [dog 4] |
show list :a :b ; [dog 4] |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Lhogho}}== |
|||
Lhogho is very similar except that it does not have a localmake opcode. |
|||
<lang logo> |
|||
to swap :s1 :s2 |
|||
local "t |
|||
make "t thing :s1 |
|||
make :s1 thing :s2 |
|||
make :s2 :t |
|||
end |
|||
make "a 4 |
|||
make "b "dog |
|||
swap "a "b ; pass the names of the variables to swap |
|||
show list :a :b ; [dog 4] |
|||
</lang> |
|||
=={{header|Logtalk}}== |
=={{header|Logtalk}}== |
||
< |
<syntaxhighlight lang="logtalk">:- object(paws). |
||
:- public(swap/4). |
:- public(swap/4). |
||
swap(First, Second, Second, First). |
swap(First, Second, Second, First). |
||
:- end_object.</ |
:- end_object.</syntaxhighlight> |
||
Usage examples: |
Usage examples: |
||
< |
<syntaxhighlight lang="logtalk">| ?- paws::swap(apples, oranges, X, Y). |
||
X = oranges |
X = oranges |
||
Y = apples |
Y = apples |
||
Line 1,126: | Line 2,185: | ||
| ?- paws::swap(3.14, ext(lgt), X, Y). |
| ?- paws::swap(3.14, ext(lgt), X, Y). |
||
X = ext(lgt) |
X = ext(lgt) |
||
Y = 3.14</ |
Y = 3.14</syntaxhighlight> |
||
yes |
yes |
||
Line 1,132: | Line 2,191: | ||
LOLCODE's dynamic typing makes generic swapping trivial. In addition, the special <tt>IT</tt> variable‒which contains the most recently evaluated expression‒permits doing so without explicitly creating a temporary variable. |
LOLCODE's dynamic typing makes generic swapping trivial. In addition, the special <tt>IT</tt> variable‒which contains the most recently evaluated expression‒permits doing so without explicitly creating a temporary variable. |
||
< |
<syntaxhighlight lang="lolcode">HAI 1.3 |
||
I HAS A foo ITZ "kittehz" |
I HAS A foo ITZ "kittehz" |
||
Line 1,142: | Line 2,201: | ||
VISIBLE bar BTW, kittehz |
VISIBLE bar BTW, kittehz |
||
KTHXBYE</ |
KTHXBYE</syntaxhighlight> |
||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
Lua evaluates the values on the right-hand side before assigning them to the variables on the left-hand side. This behaviour allows the following notation to be used to swap two values: |
Lua evaluates the values on the right-hand side before assigning them to the variables on the left-hand side. This behaviour allows the following notation to be used to swap two values: |
||
< |
<syntaxhighlight lang="lua"> |
||
x, y = y, x -- swap the values inside x and y |
x, y = y, x -- swap the values inside x and y |
||
t[1], t[2] = t[2], t[1] -- swap the first and second values inside table t |
t[1], t[2] = t[2], t[1] -- swap the first and second values inside table t |
||
</syntaxhighlight> |
|||
</lang> |
|||
Usage example: |
Usage example: |
||
< |
<syntaxhighlight lang="lua"> |
||
x, y = 3, 4 |
x, y = 3, 4 |
||
print(x, y) --> 3 4 |
print(x, y) --> 3 4 |
||
x, y = y, x -- swap |
x, y = y, x -- swap |
||
print(x, y) --> 4 3 |
print(x, y) --> 4 3 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|M2000 Interpreter}}== |
|||
Swap is a statement in M2000 which get two identifiers, variables or array items. Variables and Array items are all internal type of Variant. Normally a numeric variable hold the first type we assign to it. Numeric types are: Double, Single, Decimal, Currency, Decimal, Long, Integer. Boolean is also a type but true and false are not boolean, they are double -1 and 0). When we use Swap internal only variant swap happen, without check of type of variant. |
|||
Here we make a local Swap and pass by reference, numbers and strings. References created without testing what type of variant we use. So calling swap we make a swap moving bytes, and for strings this means moving pointers to BSTR type of strings. |
|||
<syntaxhighlight lang="m2000 interpreter"> |
|||
\\ programming again Swap (for local use) |
|||
Module Swap (&a, &b) { |
|||
\\ this call internal command - by default is by reference without using character & |
|||
Swap a, b |
|||
} |
|||
X=20 |
|||
Y=100 |
|||
Swap &x, &y |
|||
Print X, Y, Type$(X)="Double",Type$(Y)="Double" |
|||
A$="A$" |
|||
B$="B$" |
|||
Swap &A$, &B$ |
|||
Print A$="B$", B$="A$" |
|||
</syntaxhighlight> |
|||
Using Swap (internal command), for variables, groups (only for variables inside groups), pointers to groups, pointers to containers, etc. |
|||
<syntaxhighlight lang="m2000 interpreter"> |
|||
a=1000 |
|||
b=50 |
|||
Swap a,b |
|||
Print a, b |
|||
A$="Hello" |
|||
B$="There" |
|||
Swap A$, B$ |
|||
Print A$, B$ |
|||
Dim A(4) |
|||
A(0):=1,2,3,4 |
|||
Swap A(3), A(2) |
|||
Print A(3), A(2) |
|||
\\ Groups are Values |
|||
Group alfa { |
|||
x=10, y=20 |
|||
} |
|||
Group Beta { |
|||
x=40, y=50 |
|||
} |
|||
\\ with List we show the public variables |
|||
\\ so among other variables there are: |
|||
\\ alfa[Group], alfa.x=10, alfa.y=20, beta[group], beta.x=40, beta.y=50 |
|||
\\ So Alfa.x and Beta.x are simple variables, we can use swap |
|||
Swap Alfa.x, Beta.x |
|||
Print Alfa.x, Beta.x |
|||
Swap Alfa.x, Beta.x |
|||
List |
|||
\\ We have to use a third variable to hold value |
|||
For This { |
|||
\\ Local always make a new variable, and shadow any same local variable |
|||
Local M=alfa |
|||
alfa=beta |
|||
beta=m |
|||
} |
|||
\\ Now M erased (defined in For This block) |
|||
Print Alfa.x=40, Alfa.y=50 |
|||
Print Beta.x=10, Beta.y=20 |
|||
\\ Using -> we make pointers to Alfa, and Beta |
|||
\\ These pointers are valid until Alfa and Beta erased, or get Empty Group (->0) |
|||
pA->Alfa |
|||
pB->Beta |
|||
Print pA=>x=40, pA=>y=50 |
|||
Print pB=>x=10, pB=>y=20 |
|||
Swap pA,pB |
|||
Print pA=>x=10, pA=>y=20 ' pA point to beta |
|||
Print pB=>x=40, pB=>y=50 'pB point to alfa |
|||
Print type$(pA)="Group",Valid(pA=>X)=True |
|||
pA->0 |
|||
pB->0 |
|||
Print type$(pA)="Group",Valid(pA=>X)=False |
|||
\\ These pointers are valid until get Empty Group (->0), they point to a copy of Alfa and Beta |
|||
\\ both are in heap as "closed groups" |
|||
pA->(Alfa) |
|||
pB->(Beta) |
|||
Print pA=>x, pA=>y |
|||
\\ swap need variables or arrays |
|||
\\ pA=>x are closed to object so we have to open the object, and use the open one, where all public variables of group can be used |
|||
For pA, pB { |
|||
Swap .x, .y |
|||
} |
|||
Print pA=>x, pA=>y |
|||
For pA, pB { |
|||
Swap .x, .y |
|||
} |
|||
Print pA=>x, pA=>y |
|||
Print pB=>x, pB=>y |
|||
Swap pA,pB |
|||
Print pA=>x, pA=>y |
|||
Print pB=>x, pB=>y |
|||
L1=lambda x=1->{=x : x++} |
|||
L2=lambda x=100->{=x : x--} |
|||
Print L1()=1, L2()=100 |
|||
Swap L1, L2 |
|||
Print L1()=99, L2()=2 |
|||
Swap L1, L2 |
|||
Print L1()=3, L2()=98 |
|||
\\ swap change pointers to containers (here pointers to arrays) |
|||
A=(1,2,3,4,5) |
|||
B=(6,7,8,9,10) |
|||
Swap A, B |
|||
Print A |
|||
Print B |
|||
\\ Arrays with () in names are values |
|||
Dim A(10)=1, B(10)=2 |
|||
For This { |
|||
Dim C() |
|||
C()=A() |
|||
A()=B() |
|||
B()=C() |
|||
} |
|||
Print A() |
|||
Print B() |
|||
</syntaxhighlight> |
|||
=={{header|M4}}== |
=={{header|M4}}== |
||
< |
<syntaxhighlight lang="m4">define(`def2', `define(`$1',`$2')define(`$3',`$4')')dnl |
||
define(`swap', `def2(`$1',defn(`$2'),`$2',defn(`$1'))')dnl |
define(`swap', `def2(`$1',defn(`$2'),`$2',defn(`$1'))')dnl |
||
dnl |
dnl |
||
Line 1,167: | Line 2,346: | ||
a b |
a b |
||
swap(`a',`b') |
swap(`a',`b') |
||
a b</ |
a b</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,178: | Line 2,357: | ||
=={{header|Maple}}== |
=={{header|Maple}}== |
||
The assignment operator in Maple can swap values, since the right hand side is evaluated before the assignment occurs. |
The assignment operator in Maple can swap values, since the right hand side is evaluated before the assignment occurs. |
||
<syntaxhighlight lang="maple"> |
|||
<lang Maple> |
|||
> a, b := 2, "foo": |
> a, b := 2, "foo": |
||
> a; |
> a; |
||
Line 1,192: | Line 2,371: | ||
> b; |
> b; |
||
2 |
2 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
||
Mathematica functions are generic by default; however, it has to be told not to evaluate the arguments before executing the function. |
Mathematica functions are generic by default; however, it has to be told not to evaluate the arguments before executing the function. |
||
< |
<syntaxhighlight lang="mathematica">swap[a_, b_] := {a, b} = {b, a} |
||
SetAttributes[swap, HoldAll]</ |
SetAttributes[swap, HoldAll]</syntaxhighlight> |
||
=={{header|MATLAB}} / {{header|Octave}}== |
=={{header|MATLAB}} / {{header|Octave}}== |
||
Numercial swaps are trivial operations. In fact, they are so natural to the language that multiple swaps can be performed simultaneously. |
|||
Example: |
Example: |
||
< |
<syntaxhighlight lang="matlab">>> a = [30 40 50 60 70] |
||
a = |
a = |
||
Line 1,220: | Line 2,399: | ||
a = |
a = |
||
40 30 60 50 70</ |
40 30 60 50 70</syntaxhighlight> |
||
A generic swap (compatible with any variable type) can be performed with the ''deal'' command: |
|||
<syntaxhighlight lang="matlab"> |
|||
>> a = 12 |
|||
a = 12 |
|||
>> b = 'foo' |
|||
b = foo |
|||
>> [b, a] = deal (a, b) |
|||
b = 12 |
|||
a = foo |
|||
</syntaxhighlight> |
|||
=={{header|Maxima}}== |
=={{header|Maxima}}== |
||
< |
<syntaxhighlight lang="maxima">a: 10$ |
||
b: |
b: foo$ |
||
/* A simple way to swap values */ |
/* A simple way to swap values */ |
||
[a, b]: [b, a]$ |
[a, b]: [b, a]$ |
||
a; /* |
a; /* foo */ |
||
b; /* 10 */ |
b; /* 10 */ |
||
Line 1,238: | Line 2,432: | ||
a; /* 10 */ |
a; /* 10 */ |
||
b; /* |
b; /* foo */</syntaxhighlight> |
||
=={{header|MAXScript}}== |
=={{header|MAXScript}}== |
||
<lang |
<syntaxhighlight lang="maxscript">swap a b</syntaxhighlight> |
||
=={{header|Metafont}}== |
=={{header|Metafont}}== |
||
In Metafont, only <tt>numeric</tt> declarations can be omitted; any other type, must be explicitly given. So our swap, in order to declare and use a proper temporary variable(<tt>?</tt> in this code), must check the type of the variable passed (we check only for a; if b is of another kind, an error will occur) |
In Metafont, only <tt>numeric</tt> declarations can be omitted; any other type, must be explicitly given. So our swap, in order to declare and use a proper temporary variable(<tt>?</tt> in this code), must check the type of the variable passed (we check only for a; if b is of another kind, an error will occur) |
||
< |
<syntaxhighlight lang="metafont">vardef swap(suffix a, b) = |
||
save ?; string s_; |
save ?; string s_; |
||
if boolean a: boolean ? |
if boolean a: boolean ? |
||
Line 1,257: | Line 2,451: | ||
elseif transform a: transform ? fi; |
elseif transform a: transform ? fi; |
||
? := a; a := b; b := ? |
? := a; a := b; b := ? |
||
enddef;</ |
enddef;</syntaxhighlight> |
||
''Examples'': |
''Examples'': |
||
< |
<syntaxhighlight lang="metafont">j := 10; |
||
i := 5; |
i := 5; |
||
show j, i; |
show j, i; |
||
Line 1,272: | Line 2,466: | ||
show truth1, truth2; |
show truth1, truth2; |
||
swap(truth1,truth2); |
swap(truth1,truth2); |
||
show truth1, truth2;</ |
show truth1, truth2;</syntaxhighlight> |
||
=={{header|min}}== |
|||
{{works with|min|0.19.3}} |
|||
Like many other stack languages, this is trivial. |
|||
<syntaxhighlight lang="min">swap</syntaxhighlight> |
|||
=={{header|MiniScript}}== |
|||
Like many other languages, MiniScript passes references by value, so a straightforward swap is impossible. However, there is a trick: given the map the variales are in (e.g. <code>locals</code>) and the ''names'' of the variables, we can swap them. |
|||
<syntaxhighlight lang="miniscript">swap = function(map, a, b) |
|||
temp = map[a] |
|||
map[a] = map[b] |
|||
map[b] = temp |
|||
end function |
|||
x = 1 |
|||
y = 2 |
|||
print "BEFORE: x=" + x + ", y=" + y |
|||
swap(locals, "x", "y") |
|||
print "AFTER: x=" + x + ", y=" + y</syntaxhighlight> |
|||
{{out}} |
|||
<pre>BEFORE: x=1, y=2 |
|||
AFTER: x=2, y=1</pre> |
|||
=={{header|Modula-3}}== |
=={{header|Modula-3}}== |
||
< |
<syntaxhighlight lang="modula3">GENERIC INTERFACE GenericSwap(Elem); |
||
PROCEDURE Swap(VAR left: Elem.T; VAR right: Elem.T); |
PROCEDURE Swap(VAR left: Elem.T; VAR right: Elem.T); |
||
END GenericSwap.</ |
END GenericSwap.</syntaxhighlight> |
||
< |
<syntaxhighlight lang="modula3">GENERIC MODULE GenericSwap(Elem); |
||
PROCEDURE Swap(VAR left: Elem.T; VAR right: Elem.T) = |
PROCEDURE Swap(VAR left: Elem.T; VAR right: Elem.T) = |
||
Line 1,290: | Line 2,506: | ||
BEGIN |
BEGIN |
||
END GenericSwap.</ |
END GenericSwap.</syntaxhighlight> |
||
Here is an example usage for integers: |
Here is an example usage for integers: |
||
< |
<syntaxhighlight lang="modula3">INTERFACE IntSwap = GenericSwap(Integer) END IntSwap.</syntaxhighlight> |
||
< |
<syntaxhighlight lang="modula3">MODULE IntSwap = GenericSwap(Integer) END IntSwap.</syntaxhighlight> |
||
< |
<syntaxhighlight lang="modula3">MODULE Main; |
||
IMPORT IntSwap, IO, Fmt; |
IMPORT IntSwap, IO, Fmt; |
||
Line 1,306: | Line 2,522: | ||
IntSwap.Swap(left, right); |
IntSwap.Swap(left, right); |
||
IO.Put("Left = " & Fmt.Int(left) & "\n"); |
IO.Put("Left = " & Fmt.Int(left) & "\n"); |
||
END Main.</ |
END Main.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,316: | Line 2,532: | ||
=={{header|Nemerle}}== |
=={{header|Nemerle}}== |
||
For pairs, namespace Nemerle.Utility.Pair contains Swap(): |
For pairs, namespace Nemerle.Utility.Pair contains Swap(): |
||
< |
<syntaxhighlight lang="nemerle">def coords = (1, -1); |
||
def invcoords = Swap(coords);</ |
def invcoords = Swap(coords);</syntaxhighlight> |
||
Or to swap two mutable variables of the same type:<lang |
Or to swap two mutable variables of the same type:<syntaxhighlight lang="nemerle">a <-> b;</syntaxhighlight> |
||
But, enough about built in functionality, let's demonstrate using generics: |
But, enough about built in functionality, let's demonstrate using generics: |
||
< |
<syntaxhighlight lang="nemerle">Swap[T, U] (a : T, b : U) : U * T |
||
{ |
{ |
||
(b, a) |
(b, a) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|NetRexx}}== |
=={{header|NetRexx}}== |
||
Values stored in the '''default''' <tt>Rexx</tt> data type are treated as typeless data; context is based on the contents. |
Values stored in the '''default''' <tt>Rexx</tt> data type are treated as typeless data; context is based on the contents. |
||
Swapping the contents of variables stored in <tt>Rexx</tt> object can be achieved via the <tt>PARSE</tt> instruction. |
Swapping the contents of variables stored in <tt>Rexx</tt> object can be achieved via the <tt>PARSE</tt> instruction. |
||
< |
<syntaxhighlight lang="netrexx">/* NetRexx */ |
||
options replace format comments java crossref symbols nobinary |
options replace format comments java crossref symbols nobinary |
||
Line 1,349: | Line 2,565: | ||
return |
return |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,358: | Line 2,574: | ||
After - <lval>This value started on the right</lval> <rval>This value started on the left </rval> |
After - <lval>This value started on the right</lval> <rval>This value started on the left </rval> |
||
</pre> |
</pre> |
||
=={{header|NewLISP}}== |
|||
<syntaxhighlight lang="newlisp">(swap a b)</syntaxhighlight> |
|||
=={{header|Nial}}== |
=={{header|Nial}}== |
||
Like J |
Like J |
||
< |
<syntaxhighlight lang="nial">|reverse 1 2 |
||
=2 1</ |
=2 1</syntaxhighlight> |
||
=={{header|NewLISP}}== |
|||
<lang NewLISP>(swap a b)</lang> |
|||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
Builtin procedure <code>swap</code>. Example usage: |
Builtin procedure <code>swap</code>. Example usage: |
||
<lang |
<syntaxhighlight lang="nim">swap(a, b)</syntaxhighlight> |
||
=={{header|OASYS Assembler}}== |
=={{header|OASYS Assembler}}== |
||
You can swap variable <tt>%A#</tt> with <tt>%B#</tt> by writing: |
You can swap variable <tt>%A#</tt> with <tt>%B#</tt> by writing: |
||
< |
<syntaxhighlight lang="oasys_oaa">%A#%B#<%B#%A#<>></syntaxhighlight> |
||
A method which can be called to implement it can be written like: |
A method which can be called to implement it can be written like: |
||
< |
<syntaxhighlight lang="oasys_oaa">[&SW,A^,B^],A^<,B^<<,B^<,A^<<>></syntaxhighlight> |
||
To call such method: |
To call such method: |
||
<lang |
<syntaxhighlight lang="oasys_oaa">+%A#%B#&SW</syntaxhighlight> |
||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
Tuples are immutable in OCaml. This function doesn't mutate anything, but simply returns a new pair with the order of the elements switched. |
Tuples are immutable in OCaml. This function doesn't mutate anything, but simply returns a new pair with the order of the elements switched. |
||
< |
<syntaxhighlight lang="ocaml">let swap (x, y) = (y, x)</syntaxhighlight> |
||
If the arguments are constrained to be reference values, a swap function is simple: |
If the arguments are constrained to be reference values, a swap function is simple: |
||
< |
<syntaxhighlight lang="ocaml">let swapref x y = |
||
let temp = !x in |
let temp = !x in |
||
x := !y; |
x := !y; |
||
y := temp</ |
y := temp</syntaxhighlight> |
||
=={{header|Oforth}}== |
=={{header|Oforth}}== |
||
<lang |
<syntaxhighlight lang="oforth">swap</syntaxhighlight> |
||
=={{header|Oz}}== |
=={{header|Oz}}== |
||
Line 1,396: | Line 2,612: | ||
We can write a swap procedure for cells, though. Cells are mutable references. |
We can write a swap procedure for cells, though. Cells are mutable references. |
||
< |
<syntaxhighlight lang="oz"> proc {SwapCells A B} |
||
Tmp = @A |
Tmp = @A |
||
in |
in |
||
A := @B |
A := @B |
||
B := Tmp |
B := Tmp |
||
end</ |
end</syntaxhighlight> |
||
Or shorter, if we exploit the fact that the assignment operator <code>:=</code> returns the old value of the cells: |
Or shorter, if we exploit the fact that the assignment operator <code>:=</code> returns the old value of the cells: |
||
< |
<syntaxhighlight lang="oz"> proc {SwapCells A B} |
||
B := A := @B |
B := A := @B |
||
end</ |
end</syntaxhighlight> |
||
A functional swap, operating on pairs: |
A functional swap, operating on pairs: |
||
< |
<syntaxhighlight lang="oz"> fun {SwapPair A#B} |
||
B#A |
B#A |
||
end</ |
end</syntaxhighlight> |
||
=={{header|PARI/GP}}== |
=={{header|PARI/GP}}== |
||
Pari is near-typeless—everything is a GEN. |
Pari is near-typeless—everything is a GEN. |
||
< |
<syntaxhighlight lang="parigp">my(tmp=a); |
||
a=b; |
a=b; |
||
b=tmp;</ |
b=tmp;</syntaxhighlight> |
||
{{works with|PARI/GP|2.6.0 and above}} |
{{works with|PARI/GP|2.6.0 and above}} |
||
< |
<syntaxhighlight lang="parigp">[a,b]=[b,a]</syntaxhighlight> |
||
=={{header|Pascal}}== |
=={{header|Pascal}}== |
||
{{works with|Free_Pascal|2.6.0}} |
{{works with|Free_Pascal|2.6.0}} |
||
Standard Pascal does not have generics, but FreePascal has a start: |
Standard Pascal does not have generics, but FreePascal has a start: |
||
< |
<syntaxhighlight lang="pascal">program generictest; |
||
{$mode objfpc} |
{$mode objfpc} |
||
Line 1,453: | Line 2,669: | ||
SwapInt(S, T); |
SwapInt(S, T); |
||
writeln(S, T:2); |
writeln(S, T:2); |
||
end.</ |
end.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
4 3 |
4 3 |
||
3 4 |
3 4 |
||
</pre> |
|||
'''since FreePascal version 3.2.0:''' |
|||
<syntaxhighlight lang="pascal">program generic_test; |
|||
{$mode objfpc}{H+} |
|||
uses |
|||
SysUtils; |
|||
generic procedure GSwap<T>(var L, R: T); |
|||
var |
|||
Tmp: T; |
|||
begin |
|||
Tmp := L; |
|||
L := R; |
|||
R := Tmp; |
|||
end; |
|||
var |
|||
I, J: Integer; |
|||
begin |
|||
I := 100; |
|||
J := 11; |
|||
WriteLn('I = ', I, ', J = ', J); |
|||
specialize GSwap<Integer>(I, J); |
|||
WriteLn('I = ', I, ', J = ', J); |
|||
end.</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
I = 100, J = 11 |
|||
I = 11, J = 100 |
|||
</pre> |
|||
=={{header|PascalABC.NET}}== |
|||
<syntaxhighlight lang="delphi"> |
|||
procedure Swap<T> (var a,b: T) := (a,b) := (b,a); |
|||
begin |
|||
var (i,j) := (1,2); |
|||
Swap(i,j); |
|||
Println(i,j); |
|||
var (s1,s2) := ('PascalABC.NET','Hello'); |
|||
Swap(s1,s2); |
|||
Println(s1,s2); |
|||
end. |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
2 1 |
|||
Hello PascalABC.NET |
|||
</pre> |
</pre> |
||
Line 1,463: | Line 2,727: | ||
Perl has support for swapping built-in |
Perl has support for swapping built-in |
||
< |
<syntaxhighlight lang="perl">($y, $x) = ($x, $y);</syntaxhighlight> |
||
Here's a generic swap routine: |
Here's a generic swap routine: |
||
< |
<syntaxhighlight lang="perl">sub swap {@_[0, 1] = @_[1, 0]}</syntaxhighlight> |
||
=={{header| |
=={{header|Phix}}== |
||
{{libheader|Phix/basics}} |
|||
As Perl 5. Perl 6 supports type constraints for variables and subroutines, unlike Perl 5, but the default is still to permit all values. |
|||
The following applies to any types. Subscripting and nesting may also be used freely on either side. |
|||
<!--<syntaxhighlight lang="phix">--> |
|||
<span style="color: #0000FF;">{</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">a</span><span style="color: #0000FF;">}</span> |
|||
<!--</syntaxhighlight>--> |
|||
=={{header|Phixmonti}}== |
|||
Alternatively, you can write it like this: |
|||
Applies to any types. |
|||
<syntaxhighlight lang="phixmonti">a b var a var b</syntaxhighlight> |
|||
<lang perl6>($x, $y) .= reverse;</lang> |
|||
=={{header|PHP}}== |
=={{header|PHP}}== |
||
< |
<syntaxhighlight lang="php">function swap(&$a, &$b) { |
||
list($a, $b) = array($b, $a); |
list($a, $b) = array($b, $a); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Picat}}== |
|||
Picat supports re-assignment (<code>:=</code>), but it is not possible to swap two variables like this: |
|||
<syntaxhighlight lang="picat">A = 1, |
|||
B = 2, |
|||
[A,B] := [B,A], |
|||
% ...</syntaxhighlight> |
|||
(This throws an error: "invalid left-hand side of assignment"). |
|||
The following works, but it's probably not general enough for this task: |
|||
<syntaxhighlight lang="picat">A = 1, |
|||
B = 2, |
|||
T = A, % Assuming that T is not used elsewhere in the clause |
|||
A := B, |
|||
B := T, |
|||
% ...</syntaxhighlight> |
|||
Instead swaps has to be done by some other means. |
|||
===Inline swapping in a list=== |
|||
One way is to place the values in a list (or array) and use inline swapping of the list. |
|||
<syntaxhighlight lang="picat">% Swapping positions in a list/array |
|||
swap2(L) => |
|||
swap_list(L,1,2). |
|||
% Swap two elements in a list |
|||
swap_list(L,I,J) => |
|||
T = L[I], |
|||
L[I] := L[J], |
|||
L[J] := T.</syntaxhighlight> |
|||
Usage: |
|||
<syntaxhighlight lang="picat">L = [1,2], |
|||
swap2(L), |
|||
% ...</syntaxhighlight> |
|||
L is now [2,1] |
|||
Note: Placing the variables A, B in swap2 |
|||
<syntaxhighlight lang="picat">swap2([A,B])</syntaxhighlight> |
|||
will NOT change the values of A and B. |
|||
===Using a second list=== |
|||
Another way is to place the swapped values in a second list: |
|||
<syntaxhighlight lang="picat">swap_pair([A,B],[B,A]).</syntaxhighlight> |
|||
Usage: |
|||
<syntaxhighlight lang="picat">A = 1, |
|||
B = 2, |
|||
swap_pair([A,B],X), |
|||
% ...</syntaxhighlight> |
|||
X is now [2,1]. A is still 1 and B is still 2. |
|||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
[http://software-lab.de/doc/refX.html#xchg xchg] works with any data type |
[http://software-lab.de/doc/refX.html#xchg xchg] works with any data type |
||
< |
<syntaxhighlight lang="picolisp">(let (A 1 B 2) |
||
(xchg 'A 'B) |
(xchg 'A 'B) |
||
(println A B) ) |
(println A B) ) |
||
Line 1,490: | Line 2,814: | ||
(let (Lst1 '(a b c) Lst2 '(d e f)) |
(let (Lst1 '(a b c) Lst2 '(d e f)) |
||
(xchg (cdr Lst1) (cdr Lst2)) |
(xchg (cdr Lst1) (cdr Lst2)) |
||
(println Lst1 Lst2) )</ |
(println Lst1 Lst2) )</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>2 1 |
<pre>2 1 |
||
(a e c) (d b f)</pre> |
(a e c) (d b f)</pre> |
||
=={{header|Pike}}== |
|||
<syntaxhighlight lang="pike">mixed first = 5; |
|||
mixed second = "foo"; |
|||
array pair = ({ 5, "foo" }); |
|||
void swapvars(string a, string b) |
|||
{ |
|||
[this[a], this[b]] = ({ this[b], this[a] }); |
|||
} |
|||
void swaparray(array swapit) |
|||
{ |
|||
[swapit[1], swapit[0]] = ({ swapit[0], swapit[1] }); |
|||
} |
|||
void main() |
|||
{ |
|||
write("swap variables:\n"); |
|||
write("%O, %O\n", first, second); |
|||
// we could just use [first, second] = ({ second, first }); |
|||
swapvars("first", "second"); |
|||
write("%O, %O\n", first, second); |
|||
write("swap array:\n"); |
|||
write("%{ %O %}\n", pair); |
|||
// we could just use [pair[1], pair[0]] = ({ pair[0], pair[1] }); |
|||
// directly, but since arrays are called by reference, |
|||
// it also works through a function |
|||
swaparray(pair); |
|||
write("%{%O %}\n", pair); |
|||
}</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
swap variables: |
|||
5, "foo" |
|||
"foo", 5 |
|||
swap array: |
|||
5 "foo" |
|||
"foo" 5 |
|||
</pre> |
|||
=={{header|PL/I}}== |
=={{header|PL/I}}== |
||
==== Using the preprocessor ==== |
==== Using the preprocessor ==== |
||
< |
<syntaxhighlight lang="pli"> |
||
%swap: procedure (a, b); |
%swap: procedure (a, b); |
||
declare (a, b) character; |
declare (a, b) character; |
||
return ( 't=' || a || ';' || a || '=' || b || ';' || b '=t;' ); |
return ( 't=' || a || ';' || a || '=' || b || ';' || b '=t;' ); |
||
%end swap; |
%end swap; |
||
%activate swap;</ |
%activate swap;</syntaxhighlight> |
||
The statement:- |
The statement:- |
||
Line 1,512: | Line 2,877: | ||
==== Using generic procedures ==== |
==== Using generic procedures ==== |
||
< |
<syntaxhighlight lang="pli">declare swap generic ( |
||
swapf when (float, float), |
swapf when (float, float), |
||
swapc when (char, char)); |
swapc when (char, char)); |
||
Line 1,527: | Line 2,892: | ||
declare (r, s) character (5); |
declare (r, s) character (5); |
||
call swap (r, s);</ |
call swap (r, s);</syntaxhighlight> |
||
Both of the above are not completely generic, but depend on either the presence of |
Both of the above are not completely generic, but depend on either the presence of |
||
Line 1,536: | Line 2,901: | ||
==== Completely generic code using the pre-processor ==== |
==== Completely generic code using the pre-processor ==== |
||
< |
<syntaxhighlight lang="pli">%swap: proc(x,y); |
||
dcl (x, y) char; |
dcl (x, y) char; |
||
Line 1,571: | Line 2,936: | ||
f1 = -656877352; /* '5a5a5a5a'x, aka 'QQQQ' */ |
f1 = -656877352; /* '5a5a5a5a'x, aka 'QQQQ' */ |
||
swapper(c1, f1); |
swapper(c1, f1); |
||
put data(c1,f1);</ |
put data(c1,f1);</syntaxhighlight> |
||
The code generated by 'swap(c1, c2);' looks like |
The code generated by 'swap(c1, c2);' looks like |
||
< |
<syntaxhighlight lang="pli"> |
||
begin; |
begin; |
||
dcl c char (1); |
dcl c char (1); |
||
Line 1,590: | Line 2,955: | ||
py = py + 1; |
py = py + 1; |
||
end; |
end; |
||
end;</ |
end;</syntaxhighlight> |
||
and, because declarations in PL/I begin blocks are local to that block, generating several blocks with the same variables will not cause any problems. |
and, because declarations in PL/I begin blocks are local to that block, generating several blocks with the same variables will not cause any problems. |
||
Line 1,610: | Line 2,975: | ||
Instead, the first example can be generalised via two steps. Firstly, it is possible to declare a variable to be of a type "like" some named variable (otherwise a third parameter naming the type could be supplied), and secondly, placing the in-line code between Begin ... End; means that any declaration is local to within that block only. Further, this bracketing allows a Swap to be invoked via an if-statement, as in <code>If ... then Swap(x,y);</code> - otherwise there would be a mess. Thus: |
Instead, the first example can be generalised via two steps. Firstly, it is possible to declare a variable to be of a type "like" some named variable (otherwise a third parameter naming the type could be supplied), and secondly, placing the in-line code between Begin ... End; means that any declaration is local to within that block only. Further, this bracketing allows a Swap to be invoked via an if-statement, as in <code>If ... then Swap(x,y);</code> - otherwise there would be a mess. Thus: |
||
< |
<syntaxhighlight lang="pli"> |
||
%Swap:Procedure(a,b); |
%Swap:Procedure(a,b); |
||
declare (a,b) character; /*These are proper strings of arbitrary length, pre-processor only.*/ |
declare (a,b) character; /*These are proper strings of arbitrary length, pre-processor only.*/ |
||
return ('Begin; declare t like '|| a ||'; t='|| a ||';'|| a ||'='|| b ||';'|| b ||'=t; End;'); |
return ('Begin; declare t like '|| a ||'; t='|| a ||';'|| a ||'='|| b ||';'|| b ||'=t; End;'); |
||
%End Swap;</ |
%End Swap;</syntaxhighlight> |
||
Whereupon a Swap(this,that); would generate a rather longer text of in-line source code. This and other text expansions caused odd difficulties, because the 1980s compiler replaced the invocation by the expansion and then reformatted the result into lines of 71 characters (not 72) as necessary, and then, since any additional lines were given the same source sequence number as the original line, added 100000 as needed to generate strictly increasing sequence numbers. If many lines overflowed, eventually the sequence field (eight digits) overflowed, and all following source lines thereby acquired the same source sequence number. For this and other reasons, one approach was two-stage compilation: the output from the pre-processor stage could be saved and further compilation cancelled. That file could then be resequenced and fed to the pl/i compiler afresh. |
Whereupon a Swap(this,that); would generate a rather longer text of in-line source code. This and other text expansions caused odd difficulties, because the 1980s compiler replaced the invocation by the expansion and then reformatted the result into lines of 71 characters (not 72) as necessary, and then, since any additional lines were given the same source sequence number as the original line, added 100000 as needed to generate strictly increasing sequence numbers. If many lines overflowed, eventually the sequence field (eight digits) overflowed, and all following source lines thereby acquired the same source sequence number. For this and other reasons, one approach was two-stage compilation: the output from the pre-processor stage could be saved and further compilation cancelled. That file could then be resequenced and fed to the pl/i compiler afresh. |
||
Such a file would have the expansion of Swap(this,that) as follows (but with added layout here): |
Such a file would have the expansion of Swap(this,that) as follows (but with added layout here): |
||
< |
<syntaxhighlight lang="pli"> |
||
Begin; |
Begin; |
||
declare t like this; |
declare t like this; |
||
Line 1,624: | Line 2,989: | ||
this = that; |
this = that; |
||
that = t; |
that = t; |
||
End;</ |
End;</syntaxhighlight> |
||
There would however be trouble if the type of ''this'' differed from the type of ''that'', and a pl/i compiler may not generate a warning because it handles many type conversions in an assignment without complaint. There are no pre-processor enquiry functions to inspect the types at pre-processor time - if there were, a more accomplished Swap procedure could produce suitable error reports, which can be classed as "warning" or "severe", etc. The "storage" function produces its result at run time, but, each invocation of Swap being compiled would have its actual parameters known as the compiler dealt with the code produced by that invocation of Swap, and so for each invocation, the results of "storage" would be constants - except for items that were allocated at run time. |
There would however be trouble if the type of ''this'' differed from the type of ''that'', and a pl/i compiler may not generate a warning because it handles many type conversions in an assignment without complaint. There are no pre-processor enquiry functions to inspect the types at pre-processor time - if there were, a more accomplished Swap procedure could produce suitable error reports, which can be classed as "warning" or "severe", etc. The "storage" function produces its result at run time, but, each invocation of Swap being compiled would have its actual parameters known as the compiler dealt with the code produced by that invocation of Swap, and so for each invocation, the results of "storage" would be constants - except for items that were allocated at run time. |
||
The bracketing could be via <code>DO; ... END;</code> instead of <code>BEGIN; ... END;</code> but in that case the declared temporary variable would be visible outside its fragment and there could be conflicts, either of differing type for the same name or of multiple declaration. This could be solved by adjusting Swap to generate a different name each time. One could try a prefix (or suffix) to the name of the first parameter (thus generating say <code>SwapTemp_this</code> or similar), but there would still be difficulty if there were multiple swaps involving the same variable. Instead, Swap could count its invocations and generate a name involving that. Temporary variables would then litter the storage area, and they could consume a lot of space. On the other hand, the <code>BEGIN; ... END;</code> arrangement, though typically involving temporary space on the data stack, could have its own constraints. In the 1980s, the IBM mainframe pl/i compiler had a limit of no more than 240 (or so) <code>BEGIN; ... END;</code> blocks, plus procedure blocks, plus a few other items, in any one compilation otherwise there would be a failure "in phase PI". Separate compilation and the linking of pieces introduced its own oddities, as when pieces had been compiled with different compiler options. |
The bracketing could be via <code>DO; ... END;</code> instead of <code>BEGIN; ... END;</code> but in that case the declared temporary variable would be visible outside its fragment and there could be conflicts, either of differing type for the same name or of multiple declaration. This could be solved by adjusting Swap to generate a different name each time. One could try a prefix (or suffix) to the name of the first parameter (thus generating say <code>SwapTemp_this</code> or similar), but there would still be difficulty if there were multiple swaps involving the same variable. Instead, Swap could count its invocations and generate a name involving that. Temporary variables would then litter the storage area, and they could consume a lot of space. On the other hand, the <code>BEGIN; ... END;</code> arrangement, though typically involving temporary space on the data stack, could have its own constraints. In the 1980s, the IBM mainframe pl/i compiler had a limit of no more than 240 (or so) <code>BEGIN; ... END;</code> blocks, plus procedure blocks, plus a few other items, in any one compilation otherwise there would be a failure "in phase PI". Separate compilation and the linking of pieces introduced its own oddities, as when pieces had been compiled with different compiler options. |
||
=={{header|Plain English}}== |
|||
Plain English includes a routine for swapping two values in its noodle. |
|||
<syntaxhighlight lang="text">Swap [a value] with [another value].</syntaxhighlight> |
|||
=={{header|Pop11}}== |
=={{header|Pop11}}== |
||
Line 1,634: | Line 3,003: | ||
Swap is easily done via multiple assignment: |
Swap is easily done via multiple assignment: |
||
< |
<syntaxhighlight lang="pop11">(a, b) -> (b, a);</syntaxhighlight> |
||
Pop11 is dynamically typed, so the code above is "generic". |
Pop11 is dynamically typed, so the code above is "generic". |
||
=={{header|PostScript}}== |
=={{header|PostScript}}== |
||
Works with anything you can put on the operand stack:<lang |
Works with anything you can put on the operand stack:<syntaxhighlight lang="postscript">exch</syntaxhighlight> |
||
=={{header|PowerShell}}== |
=={{header|PowerShell}}== |
||
PowerShell allows swapping directly, through tuple assignment: |
PowerShell allows swapping directly, through tuple assignment: |
||
< |
<syntaxhighlight lang="powershell">$b, $a = $a, $b</syntaxhighlight> |
||
But one can also define a function which swaps the values of two references: |
But one can also define a function which swaps the values of two references: |
||
< |
<syntaxhighlight lang="powershell">function swap ([ref] $a, [ref] $b) { |
||
$a.Value, $b.Value = $b.Value, $a.Value |
$a.Value, $b.Value = $b.Value, $a.Value |
||
}</ |
}</syntaxhighlight> |
||
When using this function the arguments have to be explicitly given as references: |
When using this function the arguments have to be explicitly given as references: |
||
< |
<syntaxhighlight lang="powershell">swap ([ref] $a) ([ref] $b)</syntaxhighlight> |
||
=={{header|Prolog}}== |
=={{header|Prolog}}== |
||
< |
<syntaxhighlight lang="prolog"> |
||
swap(A,B,B,A). |
swap(A,B,B,A). |
||
Line 1,660: | Line 3,028: | ||
X = 2, |
X = 2, |
||
Y = 1. |
Y = 1. |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|PureBasic}}== |
|||
Built in function: |
|||
<lang PureBasic>Swap a, b</lang> |
|||
=={{header|Python}}== |
=={{header|Python}}== |
||
Line 1,670: | Line 3,034: | ||
Python has support for swapping built in: |
Python has support for swapping built in: |
||
< |
<syntaxhighlight lang="python">a, b = b, a</syntaxhighlight> |
||
But the task calls for a "generic swap method" to be written, so here it is: |
But the task calls for a "generic swap method" to be written, so here it is: |
||
< |
<syntaxhighlight lang="python">def swap(a, b): |
||
return b, a</ |
return b, a</syntaxhighlight> |
||
Note that tuples are immutable in Python. This function doesn't mutate anything, but simply returns a new pair with the order of the elements switched. |
Note that tuples are immutable in Python. This function doesn't mutate anything, but simply returns a new pair with the order of the elements switched. |
||
=={{header|Quackery}}== |
|||
Quackery objects reside on the stack while in use. The word ''swap'' exchanges the top and second item on the stack. The closest thing Quackery has to variables are ancillary stacks. The word ''exchange'' defined here exchanges the top items on two ancillary stacks. |
|||
<syntaxhighlight lang="quackery">[ over take over take |
|||
2swap dip put put ] is exchange ( s s --> )</syntaxhighlight> |
|||
=={{header|R}}== |
=={{header|R}}== |
||
Line 1,682: | Line 3,054: | ||
R function arguments are passed by value, not by reference. You can work around this, however, by using their names and environment: |
R function arguments are passed by value, not by reference. You can work around this, however, by using their names and environment: |
||
< |
<syntaxhighlight lang="r">swap <- function(name1, name2, envir = parent.env(environment())) |
||
{ |
{ |
||
temp <- get(name1, pos = envir) |
temp <- get(name1, pos = envir) |
||
assign(name1, get(name2, pos = envir), pos = envir) |
assign(name1, get(name2, pos = envir), pos = envir) |
||
assign(name2, temp, pos = envir) |
assign(name2, temp, pos = envir) |
||
}</ |
}</syntaxhighlight> |
||
Usage: |
Usage: |
||
Line 1,700: | Line 3,072: | ||
A swap operation can be easily written as a macro in Racket. The macro will even work as expected in Typed Racket. |
A swap operation can be easily written as a macro in Racket. The macro will even work as expected in Typed Racket. |
||
< |
<syntaxhighlight lang="racket"> |
||
#lang racket/load |
#lang racket/load |
||
Line 1,725: | Line 3,097: | ||
(printf "x is ~a~n" x) |
(printf "x is ~a~n" x) |
||
(printf "y is ~a~n" y)) |
(printf "y is ~a~n" y)) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Raku}}== |
|||
(formerly Perl 6) |
|||
Similar to Perl 5. Raku supports type constraints for variables and subroutines, unlike Perl 5, but the default is still to permit all values. |
|||
Alternatively, you can write it like this: |
|||
<syntaxhighlight lang="raku" line>($x, $y) .= reverse;</syntaxhighlight> |
|||
=={{header|REBOL}}== |
=={{header|REBOL}}== |
||
< |
<syntaxhighlight lang="rebol">REBOL [ |
||
Title: "Generic Swap" |
Title: "Generic Swap" |
||
Author: oofoe |
|||
Date: 2009-12-06 |
|||
URL: http://rosettacode.org/wiki/Generic_swap |
URL: http://rosettacode.org/wiki/Generic_swap |
||
Reference: [http://reboltutorial.com/blog/rebol-words/] |
Reference: [http://reboltutorial.com/blog/rebol-words/] |
||
Line 1,747: | Line 3,126: | ||
answer: 42 ship: "Heart of Gold" |
answer: 42 ship: "Heart of Gold" |
||
swap 'answer 'ship ; Note quoted variables. |
swap 'answer 'ship ; Note quoted variables. |
||
print rejoin ["The answer is " answer ", the ship is " ship "."]</ |
print rejoin ["The answer is " answer ", the ship is " ship "."]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,754: | Line 3,133: | ||
=={{header|Retro}}== |
=={{header|Retro}}== |
||
<lang |
<syntaxhighlight lang="retro">swap</syntaxhighlight> |
||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
Line 1,760: | Line 3,139: | ||
(This is the slowest of the three versions.) |
(This is the slowest of the three versions.) |
||
===using temp=== |
===using temp=== |
||
< |
<syntaxhighlight lang="rexx">a = 'I see you.' |
||
b = -6 |
b = -6 |
||
_temp_ = a /*swap ··· */ |
_temp_ = a /*swap ··· */ |
||
a = b /* A ··· */ |
a = b /* A ··· */ |
||
b = _temp_ /* and B */ </ |
b = _temp_ /* and B */ </syntaxhighlight> |
||
===using VALUE=== |
===using VALUE=== |
||
This version will work with any values. |
This version will work with any values. |
||
< |
<syntaxhighlight lang="rexx">a = "bull feathers" |
||
b = 10 |
b = 10 |
||
a=value('b', a) |
a= value('b', a) /*swap A and B */</syntaxhighlight> |
||
===using PARSE=== |
===using PARSE=== |
||
Line 1,781: | Line 3,160: | ||
in the values, the following method can be used: |
in the values, the following method can be used: |
||
<br>(This is the fastest of the three versions.) |
<br>(This is the fastest of the three versions.) |
||
< |
<syntaxhighlight lang="rexx">a = -199e-12 |
||
b = 12. |
b = 12. |
||
parse value a b with b a /*swap A and B */</ |
parse value a b with b a /*swap A and B */</syntaxhighlight> |
||
Note that some REXX interpreters handle whitespace differently, some honor whitespace, |
Note that some REXX interpreters handle whitespace differently, some honor whitespace other than blanks, |
||
<br>others don't (particularly the older versions). |
<br>others don't (particularly the older versions). |
||
=={{header|Ring}}== |
=={{header|Ring}}== |
||
< |
<syntaxhighlight lang="ring"> |
||
a = 1 |
a = 1 |
||
b = 2 |
b = 2 |
||
Line 1,797: | Line 3,176: | ||
see "a = " + a + nl |
see "a = " + a + nl |
||
see "b = " + b + nl |
see "b = " + b + nl |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|RLaB}}== |
=={{header|RLaB}}== |
||
Line 1,804: | Line 3,183: | ||
Let we want to swap the content of two variables, which names are ''a'' and ''b'', |
Let we want to swap the content of two variables, which names are ''a'' and ''b'', |
||
then the following function would do the trick |
then the following function would do the trick |
||
<syntaxhighlight lang="rlab"> |
|||
<lang RLaB> |
|||
swap = function(x,y) |
swap = function(x,y) |
||
{ |
{ |
||
Line 1,827: | Line 3,206: | ||
>> b |
>> b |
||
1 |
1 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|RPL}}== |
|||
{{works with|Halcyon Calc|4.2.7}} |
|||
{| class="wikitable" |
|||
! Code |
|||
! Comments |
|||
|- |
|||
| |
|||
≪ OVER TYPE 6 == OVER TYPE 6 == 2 * + 1 + |
|||
{ ≪ SWAP ≫ |
|||
≪ OVER EVAL SWAP ROT STO ≫ |
|||
≪ DUP EVAL ROT ROT STO ≫ |
|||
≪ OVER EVAL OVER EVAL 4 ROLL STO SWAP STO ≫ } |
|||
SWAP GET EVAL |
|||
≫ 'GSWAP' STO |
|||
1 2 GSWAP |
|||
'A' 'B' GSWAP |
|||
3 'A' GSWAP |
|||
| |
|||
":#" means "stack level #" |
|||
calculate case index upon types of data at :1 and :2 |
|||
case 1: swap :2 with :1 |
|||
case 2: swap content of variable named at :2 with :1 |
|||
case 3: swap content of variable named at :1 with :2 |
|||
case 4: swap content of variables named at :1 and :2 |
|||
select program from case index and execute it |
|||
|} |
|||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
Ruby has support for swapping built in: |
Ruby has support for swapping built in: |
||
< |
<syntaxhighlight lang="ruby">a, b = b, a</syntaxhighlight> |
||
But the task calls for a "generic swap method", so here it is: |
But the task calls for a "generic swap method", so here it is: |
||
< |
<syntaxhighlight lang="ruby">def swap(a, b) |
||
return b, a |
return b, a |
||
end</ |
end</syntaxhighlight> |
||
This method does not swap the original variables, because Ruby passes parameters by value. |
This method does not swap the original variables, because Ruby passes parameters by value. |
||
Instead, this method returns simply a new array with the order of the elements switched. The caller may assign the original variables with the return value: |
Instead, this method returns simply a new array with the order of the elements switched. The caller may assign the original variables with the return value: |
||
< |
<syntaxhighlight lang="ruby">x = 42 |
||
y = "string" |
y = "string" |
||
x, y = swap x, y |
x, y = swap x, y |
||
puts x # prints string |
puts x # prints string |
||
puts y # prints 42</ |
puts y # prints 42</syntaxhighlight> |
||
=={{header| |
=={{header|Rust}}== |
||
Rust does not allow for swapping the value of two variables with different types, but if the types are the same it can be done using generic types and lifetimes. |
|||
<syntaxhighlight lang="rust"> |
|||
fn generic_swap<'a, T>(var1: &'a mut T, var2: &'a mut T) { |
|||
std::mem::swap(var1, var2) |
|||
} |
|||
</syntaxhighlight> |
|||
This function can be used in e.g. the following ways: |
|||
<syntaxhighlight lang="rust"> |
|||
fn main() { |
|||
let mut a: String = "Alice".to_owned(); |
|||
let mut b: String = "Bob".to_owned(); |
|||
let mut c: i32 = 1; |
|||
let mut d: i32 = 2; |
|||
generic_swap(&mut a, &mut b); |
|||
Run BASIC does not have support for swapping built in: |
|||
generic_swap(&mut c, &mut d); |
|||
<lang runbasic>a = 1 |
|||
b = 2 |
|||
'----- swap ---- |
|||
tmp = a |
|||
a = b |
|||
b = tmp |
|||
end</lang> |
|||
println!("a={}, b={}", a, b); |
|||
=={{header|Rust}}== |
|||
println!("c={}, d={}", c, d); |
|||
<lang rust>fn main() { |
|||
} |
|||
let mut a="Anna".to_owned(); |
|||
</syntaxhighlight> |
|||
let mut b="Bob".to_owned(); |
|||
{{out}} |
|||
std::mem::swap(&mut a, &mut b); |
|||
<pre> |
|||
println!("a={},b={}",a,b); |
|||
a=Bob, b=Alice |
|||
}</lang> |
|||
c=2, d=1 |
|||
</pre> |
|||
=={{header|Sather}}== |
=={{header|Sather}}== |
||
A possible way that needs the type of the objects to be specified: |
A possible way that needs the type of the objects to be specified: |
||
< |
<syntaxhighlight lang="sather">class SWAP{T} is |
||
swap(inout a, inout b:T) is |
swap(inout a, inout b:T) is |
||
t ::= a; |
t ::= a; |
||
Line 1,877: | Line 3,299: | ||
b := t; |
b := t; |
||
end; |
end; |
||
end;</ |
end;</syntaxhighlight> |
||
< |
<syntaxhighlight lang="sather">class MAIN is |
||
main is |
main is |
||
x ::= 10; |
x ::= 10; |
||
Line 1,886: | Line 3,308: | ||
#OUT + x + ", " + y + "\n"; |
#OUT + x + ", " + y + "\n"; |
||
end; |
end; |
||
end;</ |
end;</syntaxhighlight> |
||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
Line 1,897: | Line 3,319: | ||
To make up for that, it receives two values, and returns a tuple with the values inverted. |
To make up for that, it receives two values, and returns a tuple with the values inverted. |
||
< |
<syntaxhighlight lang="scala">def swap[A,B](a: A, b: B): (B, A) = (b, a)</syntaxhighlight> |
||
=={{header|Scheme}}== |
=={{header|Scheme}}== |
||
< |
<syntaxhighlight lang="scheme">; swap elements of a vector |
||
; vector-swap! is not part of r5rs, so we define it |
; vector-swap! is not part of r5rs, so we define it |
||
(define (vector-swap! v i j) |
(define (vector-swap! v i j) |
||
Line 1,938: | Line 3,360: | ||
; try it |
; try it |
||
(let ((a 1) (b 2)) (swap! a b) (list a b)) |
(let ((a 1) (b 2)) (swap! a b) (list a b)) |
||
; (2 1)</ |
; (2 1)</syntaxhighlight> |
||
=={{header| |
=={{header|sed}}== |
||
There are no variables in ''sed''. Just a "pattern space" and a "hold space" — that's all. The <code>x</code> command exchanges the contents of both. |
|||
=={{header|Seed7}}== |
|||
A generic template to generate swap functions is defined with: |
A generic template to generate swap functions is defined with: |
||
< |
<syntaxhighlight lang="seed7">const proc: generate_swap (in type: aType) is func |
||
begin |
begin |
||
Line 1,955: | Line 3,379: | ||
end func; |
end func; |
||
end func;</ |
end func;</syntaxhighlight> |
||
An instance of a swap function can be generated with: |
An instance of a swap function can be generated with: |
||
< |
<syntaxhighlight lang="seed7">generate_swap(integer); |
||
generate_swap(string);</ |
generate_swap(string);</syntaxhighlight> |
||
A swap function can be called with: |
A swap function can be called with: |
||
<lang |
<syntaxhighlight lang="seed7">swap(a, b);</syntaxhighlight> |
||
=={{header|SenseTalk}}== |
|||
<syntaxhighlight lang="sensetalk"> |
|||
set [x,y] to [13,"Hello"] -- assign values to two variables |
|||
put x,y |
|||
put |
|||
set [x,y] to [y,x] -- swap the variable values |
|||
put x,y |
|||
</syntaxhighlight> |
|||
Output: |
|||
<syntaxhighlight lang="sensetalk"> |
|||
13 |
|||
Hello |
|||
Hello |
|||
13 |
|||
</syntaxhighlight> |
|||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
< |
<syntaxhighlight lang="ruby">func swap(Ref a, Ref b) { |
||
var tmp = *a; |
var tmp = *a; |
||
*a = *b; |
*a = *b; |
||
*b = tmp; |
*b = tmp; |
||
}</ |
}</syntaxhighlight> |
||
or: |
or: |
||
< |
<syntaxhighlight lang="ruby">func swap(Ref a, Ref b) { |
||
(*a, *b) = (*b, *a); |
(*a, *b) = (*b, *a); |
||
}</ |
}</syntaxhighlight> |
||
or: |
or: |
||
< |
<syntaxhighlight lang="ruby">func swap(Ref a, Ref b) { |
||
[*a, *b] » (b, a); |
[*a, *b] » (b, a); |
||
}</ |
}</syntaxhighlight> |
||
The swap functions must be called with variable references. |
The swap functions must be called with variable references. |
||
< |
<syntaxhighlight lang="ruby">var (x, y) = (1, 2); |
||
swap(\x, \y);</ |
swap(\x, \y);</syntaxhighlight> |
||
=={{header|Slate}}== |
=={{header|Slate}}== |
||
This must be done with a macro method in Slate, but is in the standard library: |
This must be done with a macro method in Slate, but is in the standard library: |
||
< |
<syntaxhighlight lang="slate">x@(Syntax LoadVariable traits) swapWith: y@(Syntax LoadVariable traits) &environment: env |
||
"A macro that expands into simple code swapping the values of two variables |
"A macro that expands into simple code swapping the values of two variables |
||
in the current scope." |
in the current scope." |
||
Line 1,995: | Line 3,436: | ||
x variable store: y variable load. |
x variable store: y variable load. |
||
y variable store: tmpVar load} parenthesize |
y variable store: tmpVar load} parenthesize |
||
].</ |
].</syntaxhighlight> |
||
Usage: |
Usage: |
||
<lang |
<syntaxhighlight lang="slate">a `swapWith: b</syntaxhighlight> |
||
=={{header|Smalltalk}}== |
=={{header|Smalltalk}}== |
||
Line 2,004: | Line 3,445: | ||
An OrderedCollection can collect any kind of objects; so this swap implementend extending the OrderedCollection class is really generic. |
An OrderedCollection can collect any kind of objects; so this swap implementend extending the OrderedCollection class is really generic. |
||
< |
<syntaxhighlight lang="smalltalk">OrderedCollection extend [ |
||
swap: a and: b [ |
swap: a and: b [ |
||
|t| |
|t| |
||
Line 2,011: | Line 3,452: | ||
self at: b put: t |
self at: b put: t |
||
] |
] |
||
]</ |
]</syntaxhighlight> |
||
=={{header|SNOBOL4}}== |
=={{header|SNOBOL4}}== |
||
Line 2,017: | Line 3,458: | ||
The "canonical" version from M. Emmers tutorial: |
The "canonical" version from M. Emmers tutorial: |
||
< |
<syntaxhighlight lang="snobol4">* SWAP(.V1, .V2) - Exchange the contents of two variables. |
||
* The variables must be prefixed with the name operator |
* The variables must be prefixed with the name operator |
||
* when the function is called. |
* when the function is called. |
||
Line 2,025: | Line 3,466: | ||
$X = $Y |
$X = $Y |
||
$Y = TEMP :(RETURN) |
$Y = TEMP :(RETURN) |
||
SWAP_END</ |
SWAP_END</syntaxhighlight> |
||
=={{header|Standard ML}}== |
=={{header|Standard ML}}== |
||
Tuples are immutable in Standard ML. This function doesn't mutate anything, but simply returns a new pair with the order of the elements switched. |
Tuples are immutable in Standard ML. This function doesn't mutate anything, but simply returns a new pair with the order of the elements switched. |
||
< |
<syntaxhighlight lang="sml">fun swap (x, y) = (y, x)</syntaxhighlight> |
||
If the arguments are constrained to be reference values, a swap function is simple: |
If the arguments are constrained to be reference values, a swap function is simple: |
||
< |
<syntaxhighlight lang="sml">fun swapref (x, y) = |
||
let temp = !x in x := !y; y := temp end</ |
let temp = !x in x := !y; y := temp end</syntaxhighlight> |
||
=={{header|Stata}}== |
|||
The Mata '''[http://www.stata.com/help.cgi?mf_swap swap]''' function is built-in. |
|||
<syntaxhighlight lang="stata">mata |
|||
a=1,2,3 |
|||
b="ars longa vita brevis" |
|||
swap(a, b) |
|||
end</syntaxhighlight> |
|||
Notice that swap only works with variables, not with indexed arrays. For instance, swap(a[i],a[j]) does not work. One would instead write a[(i,j)]=a[(j,i)]. |
|||
=={{header|Swift}}== |
=={{header|Swift}}== |
||
< |
<syntaxhighlight lang="swift">func swap<T>(inout a: T, inout b: T) { |
||
(a, b) = (b, a) |
(a, b) = (b, a) |
||
}</ |
}</syntaxhighlight> |
||
'''Note:''' The Swift standard library has already a swap function. |
'''Note:''' The Swift standard library has already a swap function. |
||
Line 2,045: | Line 3,497: | ||
{{works with|Tcl|>=8.5}} |
{{works with|Tcl|>=8.5}} |
||
< |
<syntaxhighlight lang="tcl">proc swap {aName bName} { |
||
upvar 1 $aName a $bName b |
upvar 1 $aName a $bName b |
||
lassign [list $a $b] b a |
lassign [list $a $b] b a |
||
}</ |
}</syntaxhighlight> |
||
{{works with|Tcl|>=8.4}} |
{{works with|Tcl|>=8.4}} |
||
< |
<syntaxhighlight lang="tcl">proc swap {aName bName} { |
||
upvar 1 $aName a $bName b |
upvar 1 $aName a $bName b |
||
foreach {b a} [list $a $b] break |
foreach {b a} [list $a $b] break |
||
}</ |
}</syntaxhighlight> |
||
alternatively: |
alternatively: |
||
< |
<syntaxhighlight lang="tcl">proc swap {aName bName} { |
||
upvar 1 $aName a $bName b |
upvar 1 $aName a $bName b |
||
set a $b[set b $a; list] |
set a $b[set b $a; list] |
||
}</ |
}</syntaxhighlight> |
||
< |
<syntaxhighlight lang="tcl">set a 1 |
||
set b 2 |
set b 2 |
||
puts "before\ta=$a\tb=$b" |
puts "before\ta=$a\tb=$b" |
||
swap a b |
swap a b |
||
puts "after\ta=$a\tb=$b"</ |
puts "after\ta=$a\tb=$b"</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,075: | Line 3,527: | ||
An idiomatic method: |
An idiomatic method: |
||
< |
<syntaxhighlight lang="tcl">set a 1 |
||
set b 2 |
set b 2 |
||
puts "before\ta=$a\tb=$b" |
puts "before\ta=$a\tb=$b" |
||
set a $b[set b $a;lindex {}] |
set a $b[set b $a;lindex {}] |
||
puts "after\ta=$a\tb=$b"</ |
puts "after\ta=$a\tb=$b"</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>before a=1 b=2 |
<pre>before a=1 b=2 |
||
after a=2 b=1</pre> |
after a=2 b=1</pre> |
||
=={{header|ThinBASIC}}== |
|||
Generic function, swap the content of two variables. |
|||
<lang ThinBASIC>Swap Var1, Var2</lang> |
|||
=={{header|TI-89 BASIC}}== |
|||
TI-89 BASIC is dynamically typed, so the genericity is implicit. It has no pass by reference, so we must pass the variable names as strings. It is dynamically scoped, so we must choose hopefully distinct names for the variables. |
|||
<lang ti89b>Define swap(swapvar1, swapvar2) = Prgm |
|||
Local swaptmp |
|||
#swapvar1 → swaptmp |
|||
#swapvar2 → #swapvar1 |
|||
swaptmp → #swapvar2 |
|||
EndPrgm |
|||
1 → x |
|||
2 → y |
|||
swap("x", "y") |
|||
x |
|||
2 |
|||
y |
|||
1</lang> |
|||
=={{header|Trith}}== |
=={{header|Trith}}== |
||
As with other stack-based languages (e.g. [[Factor]] and [[Joy]]), the solution to this task is a trivial matter of swapping the top two operands on the stack: |
As with other stack-based languages (e.g. [[Factor]] and [[Joy]]), the solution to this task is a trivial matter of swapping the top two operands on the stack: |
||
<lang |
<syntaxhighlight lang="trith">swap</syntaxhighlight> |
||
=={{header|TXR}}== |
=={{header|TXR}}== |
||
Line 2,122: | Line 3,551: | ||
This allows multiple evaluation of the argument expressions. |
This allows multiple evaluation of the argument expressions. |
||
< |
<syntaxhighlight lang="txrlisp">(defmacro swp (left right) |
||
(with-gensyms (tmp) |
(with-gensyms (tmp) |
||
^(let ((,tmp ,left)) |
^(let ((,tmp ,left)) |
||
(set ,left ,right |
(set ,left ,right |
||
,right ,tmp))))</ |
,right ,tmp))))</syntaxhighlight> |
||
====Using <code>placelet</code>==== |
====Using <code>placelet</code>==== |
||
Line 2,132: | Line 3,561: | ||
TXR Lisp's <code>placelet</code> macro allows the programmer to bind a lexically scoped alias for a syntactic place. The place can be accessed and stored through this alias. Yet, the place is evaluated only once. With <code>placelet</code> it is easy to write many kinds of place-manipulating macros very simply. We can write a robust swap which evaluates the left and right expressions just once: |
TXR Lisp's <code>placelet</code> macro allows the programmer to bind a lexically scoped alias for a syntactic place. The place can be accessed and stored through this alias. Yet, the place is evaluated only once. With <code>placelet</code> it is easy to write many kinds of place-manipulating macros very simply. We can write a robust swap which evaluates the left and right expressions just once: |
||
< |
<syntaxhighlight lang="txrlisp">(defmacro swp (left right) |
||
(with-gensyms (tmp lpl rpl) |
(with-gensyms (tmp lpl rpl) |
||
^(placelet ((,lpl ,left) |
^(placelet ((,lpl ,left) |
||
Line 2,138: | Line 3,567: | ||
(let ((,tmp ,lpl)) |
(let ((,tmp ,lpl)) |
||
(set ,lpl ,rpl |
(set ,lpl ,rpl |
||
,rpl ,tmp)))))</ |
,rpl ,tmp)))))</syntaxhighlight> |
||
====Using place expanders==== |
====Using place expanders==== |
||
Line 2,144: | Line 3,573: | ||
Finally, the following is closely based on how <code>swap</code> is actually implemented in TXR Lisp's library. This explicitly uses the general mechanism for handling places, on which <code>placelet</code> is based also: |
Finally, the following is closely based on how <code>swap</code> is actually implemented in TXR Lisp's library. This explicitly uses the general mechanism for handling places, on which <code>placelet</code> is based also: |
||
< |
<syntaxhighlight lang="txrlisp">(defmacro swp (left right :env env) |
||
(with-gensyms (tmp) |
(with-gensyms (tmp) |
||
(with-update-expander (l-getter l-setter) left env |
(with-update-expander (l-getter l-setter) left env |
||
Line 2,150: | Line 3,579: | ||
^(let ((,tmp (,l-getter))) |
^(let ((,tmp (,l-getter))) |
||
(,l-setter (,r-getter)) |
(,l-setter (,r-getter)) |
||
(,r-setter ,tmp))))))</ |
(,r-setter ,tmp))))))</syntaxhighlight> |
||
<code>with-update-expander</code> is a macro which writes code for accessing and updating a place, and makes that code available as local macros. The result is wrapped around the body of code passed to the macro; the body can access these functions, using a backquote to insert the symbols which refer to them. For instance the macro call <code>(,l-getter)</code> expands to code which accesses the prior value of the <code>left</code> place, and <code>(,r-setter ,tmp)</code> stores the value of the temporary variable into the <code>right</code> place. |
<code>with-update-expander</code> is a macro which writes code for accessing and updating a place, and makes that code available as local macros. The result is wrapped around the body of code passed to the macro; the body can access these functions, using a backquote to insert the symbols which refer to them. For instance the macro call <code>(,l-getter)</code> expands to code which accesses the prior value of the <code>left</code> place, and <code>(,r-setter ,tmp)</code> stores the value of the temporary variable into the <code>right</code> place. |
||
=={{header|uBasic/4tH}}== |
|||
Since uBasic/4tH has a stack (just like [[Forth]]) and it is an integer BASIC only, this is quite trivial. However, making a function or procedure with the same functionality is impossible, because there is no way to pass variables by reference. |
|||
<lang>a = 5 : b = 7 |
|||
Print a,b |
|||
Push a,b : a = Pop() : b = Pop() |
|||
Print a,b</lang> |
|||
=={{header|UNIX Shell}}== |
=={{header|UNIX Shell}}== |
||
{{works with|ksh93}} |
{{works with|ksh93}} |
||
< |
<syntaxhighlight lang="bash">$ swap() { typeset -n var1=$1 var2=$2; set -- "$var1" "$var2"; var1=$2; var2=$1; } |
||
$ a=1 b=2 |
$ a=1 b=2 |
||
$ echo $a $b |
$ echo $a $b |
||
Line 2,172: | Line 3,594: | ||
$ swap a b |
$ swap a b |
||
$ echo $a $b |
$ echo $a $b |
||
1 2</ |
1 2</syntaxhighlight> |
||
{{works with|bash|4.2}} |
{{works with|bash|4.2}} |
||
< |
<syntaxhighlight lang="bash">$ swap() { local var1=$1 var2=$2; set -- "${!var1}" "${!var2}"; declare -g "$var1"="$2" "$var2"="$1"; } |
||
$ a=1 b=2 |
$ a=1 b=2 |
||
$ echo $a $b |
$ echo $a $b |
||
Line 2,184: | Line 3,606: | ||
$ swap a b |
$ swap a b |
||
$ echo $a $b |
$ echo $a $b |
||
1 2</ |
1 2</syntaxhighlight> |
||
=={{header|Ursala}}== |
=={{header|Ursala}}== |
||
Line 2,190: | Line 3,612: | ||
Swapping a pair is a very inexpensive operation because no actual copying or overwriting |
Swapping a pair is a very inexpensive operation because no actual copying or overwriting |
||
is performed. |
is performed. |
||
< |
<syntaxhighlight lang="ursala">pmgs("x","y") = ("y","x") # the pattern matching way |
||
ugs = ~&rlX # the idiosyncratic Ursala way |
ugs = ~&rlX # the idiosyncratic Ursala way |
||
Line 2,196: | Line 3,618: | ||
#cast %sWL |
#cast %sWL |
||
test = <pmgs ('a','b'),ugs ('x','y')></ |
test = <pmgs ('a','b'),ugs ('x','y')></syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,204: | Line 3,626: | ||
Using the view to shuffle the stack. |
Using the view to shuffle the stack. |
||
< |
<syntaxhighlight lang="v">[swap [a b : b a] view]. |
||
1 2 swap |
1 2 swap |
||
= 2 1 |
= 2 1 |
||
'hello' 'hi' swap</ |
'hello' 'hi' swap</syntaxhighlight> |
||
='hi' 'hello' |
='hi' 'hello' |
||
=={{header|VBScript}}== |
|||
This works for everything: strings, dates, booleans ... The fact is, with everything being a Variant, it's always generic. |
|||
=={{header|Verbexx}}== |
|||
<lang vb>sub swap( byref x, byref y ) |
|||
dim temp |
|||
temp = x |
|||
x = y |
|||
y = temp |
|||
end sub</lang> |
|||
<syntaxhighlight lang="verbexx">// user-defined swap verb -- parms are passed by alias, not value, so they can be updated: |
|||
Usage: |
|||
<lang vb>dim a |
|||
a = "woof" |
|||
dim b |
|||
b = now() |
|||
swap a,b |
|||
wscript.echo a |
|||
wscript.echo b</lang> |
|||
'<==> [_a] @FN [_b] { _a _b = _b _a } by_alias: ; |
|||
{{out}} |
|||
<lang vb>5/02/2010 2:35:36 PM |
|||
woof</lang> |
|||
=={{header|Visual Basic}}== |
|||
// test out swap verb |
|||
Visual Basic can use the [[#VBScript|VBScript]] example above, with the caveat that it won't work if any <code>DEFtype</code> (except <code>DefVar</code>) has been used. (The default data type is <code>Variant</code>, which can be used as a stand-in for any variable type.) |
|||
@VAR a = 12345; |
|||
Also, the sub will fail if one arg is a string containing non-numeric data and the other arg is numeric. |
|||
@VAR b = "*****"; |
|||
@SAY "a=" a " b=" b; |
|||
\b <==> \a; // "\" verb prevents evaluation of a and b here, |
|||
// so they can be passed by alias to <==> |
|||
@SAY "a=" a " b=" b; |
|||
a b = b a; // swap them back, just using the usual = verb |
|||
@SAY "a=" a " b=" b;</syntaxhighlight> |
|||
− |
|||
− |
|||
=={{header|Visual FoxPro}}== |
=={{header|Visual FoxPro}}== |
||
Since Visual FoxPro is not strongly typed, this will work with any data types. |
Since Visual FoxPro is not strongly typed, this will work with any data types. |
||
< |
<syntaxhighlight lang="vfp"> |
||
*!* Swap two variables |
*!* Swap two variables |
||
LOCAL a, b |
LOCAL a, b |
||
Line 2,259: | Line 3,676: | ||
v2 = dum |
v2 = dum |
||
ENDPROC |
ENDPROC |
||
</ |
</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,268: | Line 3,685: | ||
=={{header|Wart}}== |
=={{header|Wart}}== |
||
There's a primitive for modifying bindings. |
There's a primitive for modifying bindings. |
||
<lang |
<syntaxhighlight lang="wart">(swap! x y)</syntaxhighlight> |
||
New bindings can be created in parallel. |
New bindings can be created in parallel. |
||
< |
<syntaxhighlight lang="wart">let (x y) (list y x) |
||
...</ |
...</syntaxhighlight> |
||
=={{header|Wren}}== |
|||
Wren is dynamically typed and, once a variable has been declared, a value of any type can be assigned to it. Generic programming is not therefore a problem here. |
|||
However, it is still not possible to write a generic swap function. This is because all variables are passed to functions or methods by value and prescribing that they should be passed by reference instead is not supported. Moreover, variables of simple types (numbers, bools and nulls) are never boxed and so a function cannot mutate the original variable. |
|||
Perhaps the nearest we can get to a generic swap function is to pass the variables in a list (the list's address is then passed by value under the hood), swap the list elements (lists do have a swap method) and then unpack the list to the original variables after the function returns. |
|||
Another approach would be to box simple variables (using a user defined class) so that they can be mutated. However, the problem with this is that they usually need to be 'unboxed' when the function returns. |
|||
Both approaches are illustrated below. |
|||
<syntaxhighlight lang="wren">var swap = Fn.new { |l| l.swap(0, 1) } |
|||
var a = 6 |
|||
var b = 3 |
|||
var c = [a, b] |
|||
swap.call(c) // pass a list instead of individual variables |
|||
a = c[0] // unpack |
|||
b = c[1] // ditto |
|||
System.print("a is now %(a)") |
|||
System.print("b is now %(b)") |
|||
System.print() |
|||
// all user defined classes are reference types |
|||
class Box { |
|||
construct new(v) { _v = v } |
|||
v { _v } |
|||
v=(value) { _v = value } |
|||
} |
|||
// by passing boxed arguments we can mutate them |
|||
var boxSwap = Fn.new { |a, b| |
|||
var t = a.v |
|||
a.v = b.v |
|||
b.v = t |
|||
} |
|||
var d = Box.new(4) |
|||
var e = Box.new(8) |
|||
boxSwap.call(d, e) |
|||
d = d.v // unbox |
|||
e = e.v // ditto |
|||
System.print("d is now %(d)") |
|||
System.print("e is now %(e)")</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
a is now 3 |
|||
b is now 6 |
|||
d is now 8 |
|||
e is now 4 |
|||
</pre> |
|||
=={{header|XBS}}== |
|||
There is a keyword for swapping variables. Here is an example of 2 ways to swap variables |
|||
===Swap Keyword=== |
|||
<syntaxhighlight lang="xbs">set x=1; |
|||
set y=2; |
|||
log("Before Swap"); |
|||
log(x); |
|||
log(y); |
|||
swap x y; |
|||
log("After Swap"); |
|||
log(x); |
|||
log(y);</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Before Swap |
|||
1 |
|||
2 |
|||
After Swap |
|||
2 |
|||
1 |
|||
</pre> |
|||
===Swap Function=== |
|||
<syntaxhighlight lang="xbs">set x = 1; |
|||
set y = 2; |
|||
func Swap(a,b){ |
|||
send[b,a]; |
|||
} |
|||
set z = Swap(x,y); |
|||
x=z[0]; |
|||
y=z[1]; |
|||
log(x) |
|||
log(y);</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
2 |
|||
1 |
|||
</pre> |
|||
=={{header|XPL0}}== |
=={{header|XPL0}}== |
||
Line 2,279: | Line 3,787: | ||
the same size. |
the same size. |
||
< |
<syntaxhighlight lang="xpl0">include c:\cxpl\codes; |
||
proc Exch(A, B, S); |
proc Exch(A, B, S); |
||
Line 2,292: | Line 3,800: | ||
Exch(addr X, addr Y, 8); |
Exch(addr X, addr Y, 8); |
||
RlOut(0, X); RlOut(0, Y); CrLf(0); |
RlOut(0, X); RlOut(0, Y); CrLf(0); |
||
]</ |
]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,320: | Line 3,828: | ||
> foo |
> foo |
||
[20,10,40,50,30]</pre> |
[20,10,40,50,30]</pre> |
||
=={{header|Z80 Assembly}}== |
|||
===Zilog Z80=== |
|||
The Z80 has a few commands for swapping register contents: |
|||
* <code>EX DE,HL</code> will swap the contents of <code>DE</code> with the contents of <code>HL</code>. This is helpful because many instructions are only compatible with <code>HL</code>. |
|||
* <code>EXX</code> will swap out <code>BC</code>, <code>DE</code>, and <code>HL</code> with their "shadow registers." To switch back to the standard registers use <code>EXX</code> again. The accumulator and flags have their own shadow registers, which can be swapped with <code>EX AF,AF'</code>. |
|||
* <code>EX (SP),HL</code> will exchange HL with the top two bytes of the stack. |
|||
* Any two registers that you can <code>PUSH/POP</code> can be exchanged by pushing both registers and popping them in the "wrong" order on purpose. For example, to swap the <code>IX</code> and <code>IY</code> registers: |
|||
<syntaxhighlight lang="z80">push ix |
|||
push iy |
|||
pop ix ;the value that was once in IY is now in IX |
|||
pop iy ;the value that was once in IX is now in IY</syntaxhighlight> |
|||
Swapping two memory locations takes a bit more work. The Z80 can do an 8-bit swap or a 16-bit swap on memory. There are several ways to do this, but the methods differ slightly depending on which addressing modes you use. Only the accumulator can load/store a single byte directly from/to memory, but the register pairs <code>BC</code>, <code>DE</code>, <code>HL</code>, <code>SP</code>, <code>IX</code>, and <code>IY</code> can all load a 16-bit word directly from memory, or vice versa. |
|||
<syntaxhighlight lang="z80">;8-bit swap using the stack. |
|||
ld a,(&C000) |
|||
push af |
|||
ld a,(&D000) |
|||
ld (&C000),a ;store the byte at &D000 into &C000 |
|||
pop af ;now a = the byte at &C000 |
|||
ld (&D000),a ;now the byte at &D000 equals the byte that was originally at &C000</syntaxhighlight> |
|||
<syntaxhighlight lang="z80">;16-bit swap: |
|||
ld hl,(&C000) ;load the byte at &C000 into L and the byte at &C001 into H. |
|||
ld de,(&D000) ;load the byte at &D000 into E and the byte at &D001 into D. |
|||
ld (&D000),hl ;store the contents of L into &D000 and H into &D001. |
|||
ld (&C000),de ;store the contents of E into &C000 and D into &C001.</syntaxhighlight> |
|||
===Game Boy=== |
|||
The Game Boy is missing all the exchange commands that the Z80 and 8080 both have. There are no shadow registers, <code>EX</code>, or <code>EXX</code>, and you cannot load/store 16-bit register pairs to/from immediate memory addresses. The only register that can store directly to memory is the stack pointer (<code>SP</code>), and it can only store, not load! But not all is lost. <code>EX DE,HL</code> can be mimicked with the following sequence; although it's much slower than the Zilog's <code>EX DE,HL</code>, it's as quick as it possibly can be. |
|||
<syntaxhighlight lang="z80">push hl |
|||
ld h,d |
|||
ld L,e ;store de into HL. This is much faster than "push de pop hl." |
|||
pop de ;put old HL into DE</syntaxhighlight> |
|||
Swapping from memory must be done one byte at a time on the Game Boy. The Game Boy exclusive <code>LDI/LDD</code> commands can help us in this task. |
|||
<syntaxhighlight lang="z80">ld hl,&C000 |
|||
push bc |
|||
ldi a,(hl) ;equivalent of "ld a,(hl) inc hl" but is faster than the two separately. Some assemblers call this "ld a,(hl+)" |
|||
ld c,a |
|||
ld a,(hl) ;we don't need to increment hl this time. There's no wasted time or bytecode if we did however. |
|||
ld b,a ;on Zilog Z80 we would have just done "LD BC,(&C000)" but Game Boy can't do that. |
|||
; now we do the swap. |
|||
ld hl,&D000 |
|||
ld a,(hl) ;get the byte at &D000 |
|||
ld (&C000),a ;store it into &C000 |
|||
ld (hl),c ;store the old byte at &C000 into &D000 |
|||
inc hl ;inc HL to &D001 |
|||
ld a,(hl) ;get the byte at &D001 |
|||
ld (&C001),a ;store it at &C001 |
|||
ld (hl),b ;store the old byte at &C001 into &D001 |
|||
pop bc</syntaxhighlight> |
|||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
As a general case, no. Here a fake around for two known classes |
As a general case, no. Here a fake around for two known classes |
||
(which are the same for ease of example): |
(which are the same for ease of example): |
||
< |
<syntaxhighlight lang="zkl">class C{var v; fcn init(n){v=n}} |
||
var c1=C(1), c2=C(2); |
var c1=C(1), c2=C(2); |
||
println(c1.v," : ",c2.v); |
println(c1.v," : ",c2.v); |
||
Line 2,332: | Line 3,898: | ||
} |
} |
||
swap(c1,c2,"v"); |
swap(c1,c2,"v"); |
||
println(c1.v," : ",c2.v);</ |
println(c1.v," : ",c2.v);</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
Latest revision as of 14:33, 23 June 2024
![Task](http://static.miraheze.org/rosettacodewiki/thumb/b/ba/Rcode-button-task-crushed.png/64px-Rcode-button-task-crushed.png)
You are encouraged to solve this task according to the task description, using any language you may know.
- Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation. That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange.
Generic swap is a task which brings together a few separate issues in programming language semantics.
Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places.
Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities.
Some static languages have difficulties with generic programming due to a lack of support for (Parametric Polymorphism).
Do your best!
11l
F swap(&a, &b)
(a, b) = (b, a)
360 Assembly
Three consecutive exclusive OR's swap variable contents
SWAP CSECT , control section start
BAKR 14,0 stack caller's registers
LR 12,15 entry point address to reg.12
USING SWAP,12 use as base
MVC A,=C'5678____' init field A
MVC B,=C'____1234' init field B
LA 2,L address of length field in reg.2
WTO TEXT=(2) Write To Operator, results in:
* +5678________1234
XC A,B XOR A,B
XC B,A XOR B,A
XC A,B XOR A,B. A holds B, B holds A
WTO TEXT=(2) Write To Operator, results in:
* +____12345678____
PR , return to caller
LTORG , literals displacement
L DC H'16' halfword containg decimal 16
A DS CL8 field A, 8 bytes
B DS CL8 field B, 8 bytes
END SWAP program end
6502 Assembly
There are no atomic swap operations in 6502 Assembly but there are a few slower ways of doing it, using the stack. The 65c02 and 65816 revisions added a few commands which make swapping easier. The need for atomic swapping isn't really an issue since most 6502-based computers didn't use parallel processing; the biggest concern for registers or memory getting clobbered was from interrupts, which can be easily avoided by restricting the registers and/or memory they use, and using the stack to back up and restore their values at the beginning and end.
NMOS 6502
The original 6502 can't push X or Y onto the stack directly, and must do so through the accumulator. The most common way of swapping values is by pushing them onto the stack and popping them in the "wrong" order on purpose.
;swap X with Y
pha ;push accumulator
txa
pha ;push x
tya
pha ;push y
pla
tax ;pop y into x
pla
tay ;pop x into y
pla ;pop accumulator
Swapping A with X or Y is easiest with using zero page memory as a temporary store, or with self-modifying code.
sta temp ;a label representing a zero page memory address
txa
pha ;push x
ldx temp
pla ;pop x into accumulator
Swapping memory locations is fairly straightforward on all versions of the 6502:
temp equ $00
temp2 equ $01 ;these values don't matter.
lda temp
pha ;push temp
lda temp2
pha ;push temp2
pla
sta temp ;pop temp2 into temp
pla
sta temp2 ;pop temp into temp2
CMOS 65c02
This revision of the 6502 can push X and Y onto the stack directly. The above code can be condensed quite a bit. This is a different example that better illustrates how swapping can be done:
lda #$33
ldx #$44
ldy #$55
pha
phx
phy
pla ;a=#$55
ply ;y=#$44
plx ;x=#$33
68000 Assembly
Two registers can be swapped with EXG
:
EXG D0,D1 ;swap the contents of D0 and D1
EXG A0,A1 ;swap the contents of A0 and A1
However, these commands cannot be used with memory. If you want to do that you'll need to use the stack or a data register.
MOVE.L ($00FF0000),D0
MOVE.L ($00FF1000),D1
MOVE.L D0,($00FF1000)
MOVE.L D1,($00FF0000)
The SWAP
switches the high and low words of a data register. It can't be used with memory either.
MOVE.L #$1234ABCD,D0
SWAP D0 ;now D0 = #$ABCD1234
8086 Assembly
The XCHG
command swaps two registers' values. It can also work with memory that is pointed to by an index register such as SI
, DI
,or BP
. Both registers must be the same size, which enforces type matching. You cannot XCHG AX,CL
for example since AX
is 16-bit and CL
is only 8-bit.
Here are some examples of the XCHG
command in action:
xchg ax,bx ;exchanges ax with bx
xchg ah,al ;swap the high and low bytes of ax
;XCHG a register with memory
mov dx,0FFFFh
mov word ptr [ds:userRam],dx
mov si,offset userRam
mov ax,1234h
xchg ax,[si] ;exchange ax with the value stored at userRam. Now, ax = 0FFFFh and the value stored at userRam = 1234h
;XCHG a register with a value on the stack.
mov ax,1234h
mov bx,4567h
push bx
push bp
mov bp,sp ;using [sp] as an operand for XCHG will not work. You need to use bp instead.
xchg ax,[2+bp] ;exchanges AX with the value that was pushed from BX onto the stack. Now, AX = 4567h,
;and the entry on the stack just underneath the top of the stack is 1234h.
8th
swap
Or to swap between the stack and a var:
dup @ -rot !
ACL2
(defun swap (pair)
(cons (cdr pair)
(car pair)))
(let ((p (cons 1 2)))
(cw "Before: ~x0~%After: ~x1~%" p (swap p)))
Action!
INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit
PROC Swap(BYTE POINTER ptr1,ptr2 INT size)
BYTE tmp
INT i
FOR i=0 TO size-1
DO
tmp=ptr1^ ptr1^=ptr2^ ptr2^=tmp
ptr1==+1 ptr2==+1
OD
RETURN
PROC Main()
BYTE b1=[13],b2=[56]
INT i1=[65234],i2=[534]
REAL r1,r2
CHAR ARRAY s1="abcde",s2="XYZ"
Put(125) PutE() ;clear the screen
ValR("32.5",r1) ValR("-0.63",r2)
Print("Swap bytes: ")
PrintB(b1) Put(32) PrintB(b2) Print(" -> ")
Swap(@b1,@b2,1)
PrintB(b1) Put(32) PrintBE(b2)
Print("Swap integers: ")
PrintI(i1) Put(32) PrintI(i2) Print(" -> ")
Swap(@i1,@i2,2)
PrintI(i1) Put(32) PrintIE(i2)
Print("Swap floats: ")
PrintR(r1) Put(32) PrintR(r2) Print(" -> ")
Swap(r1,r2,6)
PrintR(r1) Put(32) PrintRE(r2)
Print("Swap strings: ")
Print(s1) Put(32) Print(s2) Print(" -> ")
Swap(@s1,@s2,2)
Print(s1) Put(32) PrintE(s2)
RETURN
- Output:
Screenshot from Atari 8-bit computer
Swap bytes: 13 56 -> 56 13 Swap integers: -302 534 -> 534 -302 Swap floats: 32.5 -0.63 -> -0.63 32.5 Swap strings: abcde XYZ -> XYZ abcde
Ada
The generic parameters for an Ada generic procedure are defined in a procedure specification, while the algorithm is defined in a procedure body. The first code snippet is the procedure specification. The second code snippet is the procedure body.
generic
type Swap_Type is private; -- Generic parameter
procedure Generic_Swap (Left, Right : in out Swap_Type);
procedure Generic_Swap (Left, Right : in out Swap_Type) is
Temp : constant Swap_Type := Left;
begin
Left := Right;
Right := Temp;
end Generic_Swap;
usage
To use the generic swap procedure, you need to instantiate the procedure for each type that you intend to use.
with Generic_Swap;
...
type T is ...
procedure T_Swap is new Generic_Swap (Swap_Type => T);
A, B : T;
...
T_Swap (A, B);
Aime
Aime is statically typed. A generic swap utility may nonetheless be defined in terms of parameters of unspecified type and pass by reference.
void
__swap(&, &,,)
{
set(0, $3);
set(1, $2);
}
void
swap(&, &)
{
xcall(xcall, __swap);
}
ALGOL 68
A generic swap operator =:= was proposed in ALGOL Bulletin for standard ALGOL 68 so that the compiler could optimise the operation. However such an operator was not adopted and needs to be manually defined for each mode required.
MODE GENMODE = STRING;
GENMODE v1:="Francis Gary Powers", v2:="Vilyam Fisher";
PRIO =:= = 1;
OP =:= = (REF GENMODE v1, v2)VOID: (
GENMODE tmp:=v1; v1:=v2; v2:=tmp
);
v1 =:= v2;
print(("v1: ",v1, ", v2: ", v2, new line))
- Output:
v1: Vilyam Fisher, v2: Francis Gary Powers
Special option
The B6700 Algol compiler offered access to a special machine operation via a function called ReadLock(a,b) that could be invoked on a variety of operands. By using the ability to #define this = that; one could define Swap(a,b) to be a:=ReadLock(a,b) to attain the appearance of a Swap operation. This all relied on the working of magnetic core memory, specifically that to read a word, the word is made zero and in the process the memory hardware notes which bits were thereby flipped. Thus it passes on the value in the word and meanwhile, rewrites that content back to the word so as to preserve its value on reading. Similarly, to write a value to a word, the word is first zeroed.
ReadLock(a,b) functioned by reading a and writing its value to b, but also, recovering the value that was in b which it returns as the result of the function - which is written to a by the assignment, completing the swap. The ReadLock part is "atomic" or not interruptable, so it is used in semaphores and the like, but was available for other use. It swapped a single word, so could swap types such as integers or floating-point numbers (single precision) thus being somewhat generic.
Amazing Hopper
#include <flow.h>
DEF-MAIN(argv,argc)
DIM(10) AS-INT-RAND( 10, random array )
SET( single var, 0.5768 )
PRNL( "SINGLE VAR: ", single var, "\nRANDOM ARRAY: ", random array )
single var <-> random array
PRNL( "SINGLE VAR: ", single var, "\nRANDOM ARRAY: ", random array )
END
- Output:
$ hopper swap.flw SINGLE VAR: 0.5768 RANDOM ARRAY: 4,2,5,10,8,3,4,8,3,5 SINGLE VAR: 4,2,5,10,8,3,4,8,3,5 RANDOM ARRAY: 0.5768 $
AmigaE
The simpler way to write a swap is to use the Amiga E ability to return multiple values. All basic data type in Amiga E can be held by its LONG type, and complex data type (like lists) are indeed pointers (which fits into a LONG too); so, because of the fact that Amiga E is not strongly typed, this solution works for any type.
PROC swap(a,b) IS b,a
PROC main()
DEF v1, v2, x
v1 := 10
v2 := 20
v1, v2 := swap(v1,v2)
WriteF('\d \d\n', v1,v2) -> 20 10
v1 := [ 10, 20, 30, 40 ]
v2 := [ 50, 60, 70, 80 ]
v1, v2 := swap(v1,v2)
ForAll({x}, v1, `WriteF('\d ',x)) -> 50 60 70 80
WriteF('\n')
ForAll({x}, v2, `WriteF('\d ',x)) -> 10 20 30 40
WriteF('\n')
ENDPROC
AppleScript
AppleScript has built-in support for swapping. This is generic and works for all combinations of data types.
set {x,y} to {y,x}
Arc
(mac myswap (a b)
(w/uniq gx
`(let ,gx a
(= a b)
(= b ,gx))))
(with (a 1
b 2)
(myswap a b)
(prn "a:" a #\Newline "b:" b))
Arturo
Using multi-assignment
swap: function [a,b]-> @[b,a]
c: 1
d: 2
print [c d]
[c,d]: swap c d
print [c d]
- Output:
1 2 2 1
In-place modification
swap: function [a,b].exportable [
tmp: var b
let b var a
let a tmp
]
c: 1
d: 2
print [c d]
swap 'c 'd
print [c d]
- Output:
1 2 2 1
AutoHotkey
Swap(ByRef Left, ByRef Right)
{
temp := Left
Left := Right
Right := temp
}
AWK
# syntax: GAWK -f GENERIC_SWAP.AWK
BEGIN {
printf("%s version %s\n",ARGV[0],PROCINFO["version"])
foo = 1
bar = "a"
printf("\n%s %s\n",foo,bar)
rc = swap("foo","bar") # ok
printf("%s %s %s\n",foo,bar,rc?"ok":"ng")
printf("\n%s %s\n",foo,bar)
rc = swap("FOO","BAR") # ng
printf("%s %s %s\n",foo,bar,rc?"ok":"ng")
exit(0)
}
function swap(a1,a2, tmp) { # strings or numbers only; no arrays
if (a1 in SYMTAB && a2 in SYMTAB) {
if (isarray(SYMTAB[a1]) || isarray(SYMTAB[a2])) {
return(0)
}
tmp = SYMTAB[a1]
SYMTAB[a1] = SYMTAB[a2]
SYMTAB[a2] = tmp
return(1)
}
return(0)
}
- Output:
gawk version 4.1.0 1 a a 1 ok a 1 a 1 ng
Axe
The Exch() command can swap data of any size at any two addresses. This example swaps two 2-byte variables.
Exch(°A,°B,2)
BASIC
Applesoft BASIC
A=43:B=47:H=A:A=B:B=H:?" A="A" B="B;
A=47 B=43
BaCon
x = 1
y$ = "hello"
SWAP x, y$
PRINT y$
BASIC256
global a, b
a = "one"
b = "two"
print a, b
call swap(a, b)
print a, b
end
subroutine swap(a, b)
temp = a : a = b : b = temp
end subroutine
BBC BASIC
Built-in function
a = 1.23 : b = 4.56
SWAP a,b
PRINT a,b
a$ = "Hello " : b$ = "world!"
SWAP a$,b$
PRINT a$,b$
Custom function
a = 1.23 : b = 4.56
PROCswap(^a,^b, 5)
PRINT a,b
a$ = "Hello " : b$ = "world!"
PROCswap(^a$,^b$, 6)
PRINT a$,b$
END
DEF PROCswap(a%, b%, s%)
LOCAL i%
FOR i% = 0 TO s%-1
SWAP a%?i%,b%?i%
NEXT
ENDPROC
- Output:
4.56 1.23 world! Hello
Chipmunk Basic
The GW-BASIC solution works without any changes.
FreeBASIC
FreeBASIC already has a built-in generic Swap procedure but a macro can be used to build another one:
' FB 1.05.0
#Macro Declare_Swap(T)
Sub Swap_##T(ByRef t1 As T, ByRef t2 As T)
Dim temp As T = t2
t2 = t1
t1 = temp
End Sub
#EndMacro
Dim As Integer i, j
i = 1 : j = 2
Declare_Swap(Integer) ' expands the macro
Swap_Integer(i, j)
Print i, j
Dim As String s, t
s = "Hello" : t = "World"
Declare_Swap(String)
Swap_String(s, t)
Print s, t
Print
Print "Press any key to exit"
Sleep
- Output:
2 1 World Hello
FutureBasic
window 1, @"Generic Swap", (0,0,480,270)
text ,,,,, 60
long i, j
double x, y
CFStringRef a, b
i = 1059 : j = 62
print i, j
swap i, j
print i, j
print
x = 1.23 : y = 4.56
print x, y
swap x, y
print x, y
print
a = @"Hello" : b = @"World!"
print a, b
swap a, b
print a, b
HandleEvents
- Output:
1059 62 62 1059 1.23 4.56 4.56 1.23 Hello World! World! Hello
Gambas
Click this link to run this code
Public Sub Main()
Dim vA As Variant = " World"
Dim vB As Variant = 1
Swap vA, vB
Print vA; vB
End
Output:
1 World
GW-BASIC
10 CLS : REM 10 HOME for Applesoft BASIC
20 A = 1 : B = 2
30 PRINT " A=";A," B=";B
40 T = A : A = B : B = T
50 PRINT " A=";A," B=";B
60 END
- Output:
A=1 B=2 A=2 B=1
IS-BASIC
100 DEF SWAP(REF A,REF B)
110 LET T=A:LET A=B:LET B=T
120 END DEF
130 LET A=1:LET B=2
140 PRINT A,B
150 CALL SWAP(A,B)
160 PRINT A,B
Minimal BASIC
10 LET A = 1
20 LET B = 2
30 PRINT " A=";A;" B=";B
40 LET T = A
50 LET A = B
60 LET B = T
70 PRINT " A=";A;" B=";B
80 END
MSX Basic
The GW-BASIC solution works without any changes.
OxygenBasic
macro Swap(a,b, c)
typeof(a) c
c=a
a=b
b=c
end macro
'demo with compound types:
'=========================
type point { float x,y}
point p={1,2}
point q={3,4}
swap p,q
print "p: " p.x "," p.y 'p: 3,4
print "q: " q.x "," q.y 'q: 1,2
PureBasic
Built in function:
Swap a, b
QBasic
QBasic already has a generic swap procedure built in, but a new subroutine can be defined:
SUB nswap (a, b)
temp = a: a = b: b = temp
END SUB
a = 1
b = 2
PRINT a, b
CALL nswap(a, b)
PRINT a, b
Quite BASIC
The Minimal BASIC solution works without any changes.
Run BASIC
Run BASIC does not have support for swapping built in:
a = 1
b = 2
'----- swap ----
tmp = a
a = b
b = tmp
end
ThinBASIC
Generic function, swap the content of two variables.
Swap Var1, Var2
TI-89 BASIC
TI-89 BASIC is dynamically typed, so the genericity is implicit. It has no pass by reference, so we must pass the variable names as strings. It is dynamically scoped, so we must choose hopefully distinct names for the variables.
Define swap(swapvar1, swapvar2) = Prgm
Local swaptmp
#swapvar1 → swaptmp
#swapvar2 → #swapvar1
swaptmp → #swapvar2
EndPrgm
1 → x
2 → y
swap("x", "y")
x
2
y
1
Tiny BASIC
LET a = 11
LET b = 22
PRINT a, " ", b
GOSUB 100
PRINT a, " ", b
END
100 REM swap(a, b)
LET t = a
LET a = b
LET b = t
RETURN
True BASIC
SUB swap(a, b)
LET temp = a
LET a = b
LET b = temp
END SUB
LET a = 1
LET b = 2
PRINT a, b
CALL swap(a, b)
PRINT a, b
END
uBasic/4tH
Since uBasic/4tH has a stack (just like Forth) and it is an integer BASIC only, this is quite trivial. However, making a function or procedure with the same functionality is impossible, because there is no way to pass variables by reference.
a = 5 : b = 7
Print a,b
Push a,b : a = Pop() : b = Pop()
Print a,b
VBScript
This works for everything: strings, dates, booleans ... The fact is, with everything being a Variant, it's always generic.
sub swap( byref x, byref y )
dim temp
temp = x
x = y
y = temp
end sub
Usage:
dim a
a = "woof"
dim b
b = now()
swap a,b
wscript.echo a
wscript.echo b
- Output:
5/02/2010 2:35:36 PM
woof
Visual Basic
Visual Basic can use the VBScript example above, with the caveat that it won't work if any DEFtype
(except DefVar
) has been used. (The default data type is Variant
, which can be used as a stand-in for any variable type.)
Also, the sub will fail if one arg is a string containing non-numeric data and the other arg is numeric.
Visual Basic .NET
Semantically identical to C#
Sub Swap(Of T)(ByRef a As T, ByRef b As T)
Dim temp = a
a = b
b = temp
End Sub
Usage:
Dim a = 1, b = 2
Swap(a, b)
XBasic
XBasic already has a generic swap procedure built in, but a new subroutine can be defined:
PROGRAM "nswap"
VERSION "0.0000"
DECLARE FUNCTION Entry ()
FUNCTION Entry ()
a = 1
b = 2
PRINT a, b
GOSUB nswap
PRINT a, b
SUB nswap
temp = a: a = b: b = temp
END SUB
END FUNCTION
END PROGRAM
Yabasic
Yabasic already has a generic swap procedure built in.
a = 1
b = 2
print a, b
//----- swap ----
temp = a : a = b : b = temp
print a, b
Batch File
Swap using pass-by-name
@echo off
setlocal enabledelayedexpansion
set a=1
set b=woof
echo %a%
echo %b%
call :swap a b
echo %a%
echo %b%
goto :eof
:swap
set temp1=!%1!
set temp2=!%2!
set %1=%temp2%
set %2=%temp1%
goto :eof
Beads
beads 1 program 'Generic swap'
var
a = [1 2 "Beads" 3 4]
b = [1 2 "Language" 4 5]
calc main_init
swap a[4] <=> b[3]
- Output:
A = [1, 2, "Beads", 3, 4] B = [1, 2, "Language", 4, 5] ------------------------------------------------- A = [1, 2, "Beads", "Language", 4] B = [1, 2, 3, 4, 5]
Binary Lambda Calculus
From https://github.com/tromp/AIT/blob/master/rosetta/swap.lam we get the 25-bit swap function
0001100000000101101101110
BQN
Two variables can be exchanged with modified assignment:
a‿b ⌽↩
With no right-hand side, this expands to a one-argument call a‿b ↩ ⌽ a‿b
. BQN doesn't make variable names or references first-class, so it wouldn't make sense to make this generic over variable names.
Bracmat
(!a.!b):(?b.?a)
Burlesque
\/
Stack-based swap.
C
This has a restriction that a and b must be the same size.
void swap(void *va, void *vb, size_t s)
{
char t, *a = (char*)va, *b = (char*)vb;
while(s--)
t = a[s], a[s] = b[s], b[s] = t;
}
If you have gcc, you can write a preprocessor macro with __typeof__.
- Caution: __typeof__ is a gcc extension, not part of standard C. __typeof__ does not conflict with C89 because the standard allows compilers to add keywords with underscores like __typeof__.
#define Swap(X,Y) do{ __typeof__ (X) _T = X; X = Y; Y = _T; }while(0)
Usage examples are:
#include <stdio.h>
#define Swap(X,Y) do{ __typeof__ (X) _T = X; X = Y; Y = _T; }while(0)
struct test
{
int a, b, c;
};
int main()
{
struct test t = { 1, 2, 3 };
struct test h = { 4, 5, 6 };
double alfa = 0.45, omega = 9.98;
struct test *pt = &t;
struct test *th = &h;
printf("%d %d %d\n", t.a, t.b, t.c );
Swap(t, h);
printf("%d %d %d\n", t.a, t.b, t.c );
printf("%d %d %d\n", h.a, h.b, h.c );
printf("%lf\n", alfa);
Swap(alfa, omega);
printf("%lf\n", alfa);
printf("%d\n", pt->a);
Swap(pt, th);
printf("%d\n", pt->a);
}
This is tested with GCC with -std=c89 option.
C#
C#: Using a generic method
C# 2.0 introduced the concept of generics to the language. Generics are outwardly similar to C++ templates, but are implemented quite differently: generics are maintained generically at runtime rather than being substitued with definite types by the compiler. Generics are intended to promote reusable, efficient, type-safe code, and are used widely throughout the .NET framework and 3rd party libraries, especially in collections. C# generics are less flexible than C++ templates, but are more strongly typed and arguably easier to work with.
static void Swap<T>(ref T a, ref T b)
{
T temp = a;
a = b;
b = temp;
}
Usage:
int a = 1;
int b = 2;
Swap(ref a, ref b); // Type parameter is inferred.
C#: Using tuple syntax
C# 7.0 introduced language support for tuples, which are implemented using the ValueTuple
family of structs. The example below creates a tuple with the values of b
and a
and uses deconstructing assignment to assign the members of the tuple back to the variables.
int a = 1;
int b = 2;
(a, b) = (b, a);
C++
Generic programming in C++ is provided through templates. Templates in C++ are quite powerful: They form a Turing-complete compile-time sub-language. However, that power isn't needed for swap. Note that the C++ standard library already provides a swap function which contains optimized implementations for standard library types; thus it's advisable to use that instead of a self-written variant like the one below.
While the standard allows to separate declaration and definition of templates into different files using the export keyword, most compilers (including the most used ones) don't implement that. Therefore in practice, templates declared in header files also have to be defined there.
The implementation of the swap function template is straightforward:
template<typename T> void swap(T& left, T& right)
{
T tmp(left);
left = right;
right = tmp;
}
Note that this function requires that the type T has an accessible copy constructor and assignment operator.
The standard utility 'swap' can be used to swap two values:
std::swap(x,y);
It will work with any types.
C++11
C++11 adds move constructors which can be more efficient than copy constructors.
template<class T>
void swap(T &lhs, T &rhs){
T tmp = std::move(lhs);
lhs = std::move(rhs);
rhs = std::move(tmp);
}
Chapel
Chapel includes a swap operator:
a <=> b
and supports swapping directly via tuples and destructuring:
(a, b) = (b, a)
Both variables must be of the same type. The Fibonnacci implementation contains an example.
Clojure
(defn swap [pair] (reverse pair)) ; returns a list
(defn swap [[a b]] '(b a)) ; returns a list
(defn swap [[a b]] [b a]) ; returns a vector
The latter two implementations use destructured binding to define local names for the two elements.
CMake
CMake has only one data type: the string.
function(swap var1 var2)
set(_SWAP_TEMPORARY "${${var1}}")
set(${var1} "${${var2}}" PARENT_SCOPE)
set(${var2} "${_SWAP_TEMPORARY}" PARENT_SCOPE)
endfunction(swap)
set(x 42)
set(y "string")
swap(x y)
message(STATUS ${x}) # -- string
message(STATUS ${y}) # -- 42
Because of limitations in CMake, there are a few specific situations where swap() will fail to swap the variables.
- When _SWAP_TEMPORARY is the name of the second variable: Inside swap(), its local variable _SWAP_TEMPORARY shadows the original _SWAP_TEMPORARY from the parent scope, preventing access to the original value.
set(x 42) set(_SWAP_TEMPORARY "string") swap(x _SWAP_TEMPORARY) message(STATUS ${x}) # -- 42 message(STATUS ${_SWAP_TEMPORARY}) # -- 42
- When value of either variable is "CACHE" or "PARENT_SCOPE": swap() can never set a variable to "CACHE" or "PARENT_SCOPE", because these are keywords of set() command.
string(TOUPPER CACHE x) set(y "string") swap(x y) # CMake Error... set given invalid arguments for CACHE mode.
COBOL
PROGRAM-ID. SWAP-DEMO.
AUTHOR. Bill Gunshannon.
INSTALLATION. Home.
DATE-WRITTEN. 16 December 2021.
************************************************************
** Program Abstract:
** A simple program to demonstrate the SWAP subprogram.
**
************************************************************
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Val1 PIC X(72).
01 Val2 PIC X(72).
PROCEDURE DIVISION.
Main-Program.
DISPLAY 'Enter a Value: ' WITH NO ADVANCING.
ACCEPT Val1.
DISPLAY 'Enter another Value: ' WITH NO ADVANCING.
ACCEPT Val2.
DISPLAY ' ' .
DISPLAY 'First value: ' FUNCTION TRIM(Val1) .
DISPLAY 'Second value: ' FUNCTION TRIM(Val2) .
CALL "SWAP" USING BY REFERENCE Val1, BY REFERENCE Val2.
DISPLAY ' '.
DISPLAY 'After SWAP '.
DISPLAY ' '.
DISPLAY 'First value: ' FUNCTION TRIM(Val1).
DISPLAY 'Second value: ' FUNCTION TRIM(Val2).
STOP RUN.
END PROGRAM SWAP-DEMO.
IDENTIFICATION DIVISION.
PROGRAM-ID. SWAP.
AUTHOR. Bill Gunshannon.
INSTALLATION. Home.
DATE-WRITTEN. 16 December 2021.
************************************************************
** Program Abstract:
** SWAP any Alphanumeric value. Only limit is 72
** character size. But that can be adjusted for
** whatever use one needs.
************************************************************
DATA DIVISION.
WORKING-STORAGE SECTION.
01 TEMP PIC X(72).
LINKAGE SECTION.
01 Field1 PIC X(72).
01 Field2 PIC X(72).
PROCEDURE DIVISION
USING BY REFERENCE Field1, BY REFERENCE Field2.
MOVE Field1 to TEMP.
MOVE Field2 to Field1.
MOVE TEMP to Field2.
GOBACK.
END PROGRAM SWAP.
- Output:
Enter a Value: 33 Enter another Value: 77 First value: 33 Second value: 77 After SWAP First value: 77 Second value: 33 -------------------------------- Enter a Value: Hello World Enter another Value: Good Bye First value: Hello World Second value: Good Bye After SWAP First value: Good Bye Second value: Hello World
ColdFusion
This is another standard swap.
<cfset temp = a />
<cfset a = b />
<cfset b = temp />
Common Lisp
(rotatef a b)
(psetq a b b a)
Computer/zero Assembly
LDA 29
STA 31
LDA 30
STA 29
LDA 31
STA 30
STP
---
org 29
byte $0F
byte $E0
byte $00
- Output:
Emulator with program loaded Hexdump of address 29-31 after running:
E0 0F 0F
Crystal
Crystal directly supports swapping:
a, b = b, a
D
import std.algorithm: swap; // from Phobos standard library
// The D solution uses templates and it's similar to the C++ one:
void mySwap(T)(ref T left, ref T right) {
auto temp = left;
left = right;
right = temp;
}
void main() {
import std.stdio;
int[] a = [10, 20];
writeln(a);
// The std.algorithm standard library module
// contains a generic swap:
swap(a[0], a[1]);
writeln(a);
// Using mySwap:
mySwap(a[0], a[1]);
writeln(a);
}
- Output:
[10, 20] [20, 10] [10, 20]
dc
We use two registers to swap in POSIX dc.
1 2 SaSbLaLb f
=2 1
Reverse (r) is a built-in stack command available as a GNU extension for dc.
1 2 r f
=2 1
DCL
symbols do not have to be declared, they can be integers or strings, they can change type on the fly
$ a1 = 123
$ a2 = "hello"
$ show symbol a*
$ gosub swap
$ show symbol a*
$ exit
$
$ swap:
$ t = a1
$ a1 = a2
$ a2 = t
$ return
- Output:
$ @generic_swap A1 = 123 Hex = 0000007B Octal = 00000000173 A2 = "hello" A1 = "hello" A2 = 123 Hex = 0000007B Octal = 00000000173
Delphi
Delphi does not have generics as such. The following code must be copied for each type that a swap is required. T should be changed to the required type.
procedure Swap_T(var a, b: T);
var
temp: T;
begin
temp := a;
a := b;
b := temp;
end;
Generics were introduced with Delphi 2009
program GenericSwap;
type
TSwap = class
class procedure Swap<T>(var left, right: T);
end;
class procedure TSwap.Swap<T>(var left, right: T);
var
temp : T;
begin
temp := left;
left := right;
right := temp;
end;
var
a, b : integer;
begin
a := 5;
b := 3;
writeln('Before swap: a=', a, ' b=', b);
TSwap.Swap<integer>(a, b);
writeln('After swap: a=', a, ' b=', b);
end.
Déjà Vu
To swap the two top-most items on the stack:
swap
To swap two variables without needing a third name, using the stack for temporary storage:
set :a set :b @a @b
E
(slots)
def swap(&left, &right) {
def t := left
left := right
right := t
}
(functional)
def swap([left, right]) {
return [right, left]
}
EchoLisp
;; 1)
;; a macro will do it, as shown in Racket (same syntax)
(define-syntax-rule (swap a b)
(let ([tmp a])
(set! a b)
(set! b tmp)))
(define A 666)
(define B "simon")
(swap A B)
A → "simon"
B → 666
;; 2)
;; The list-swap! function allows to swap two items inside a list, regardless of their types
;; This physically alters the list
(define L ' ( 1 2 3 4 🎩 ))
(list-swap! L 1 ' 🎩 )
→ (🎩 2 3 4 1)
Elena
ELENA 4.1 :
import extensions;
swap(ref object v1, ref object v2)
{
var tmp := v1;
v1 := v2;
v2 := tmp
}
public program()
{
var n := 2;
var s := "abc";
console.printLine(n," ",s);
swap(ref n, ref s);
console.printLine(n," ",s)
}
2 abc abc 2
Elixir
Elixir provides a robust mechanism of pattern matching; the =
operator is actually the match operator. Using the match operator, values can be assigned and variables can be bound or unbound, but only on the left (=:
).
x = 4
y = 5
{y,x} = {x,y}
y # => 4
x # => 5
[x,y] = [y,x]
x # => 4
y # => 5
Data structures can be used both for matching and for generally destructuring complex data. We can use anonymous functions to create a generic swap in iex. Note: using multiple value requires a data construct on which to match (as opposed to, say, Ruby's a,b = 1,2
), but we can use a list:
swap = fn x,y -> [y|x] end
[x|y] = swap.(1,2)
x # => 2
y # => 1
Variables can be bound and rebound regardless of type
swap_tuple = fn {x,y} -> {y,x} end
{a,b} = swap_tuple.({1,:ok})
a # => :ok
b # => 1
swap_list = fn [x,y] -> [y,x] end
[a,b] = swap_list.([1,"2"])
a # => "2"
b # => 1
Emacs Lisp
(defun swap (a-sym b-sym)
"Swap values of the variables given by A-SYM and B-SYM."
(let ((a-val (symbol-value a-sym)))
(set a-sym (symbol-value b-sym))
(set b-sym a-val)))
(swap 'a 'b)
A macro can take variable names unquoted. Here prog1
eliminates the temporary variable above so as to avoid any chance of a name clash between the two variables and the temporary.
(defmacro swap (a b)
`(setq ,b (prog1 ,a (setq ,a ,b))))
A macro could use the cl-lib
psetf
which can store to various kinds of expressions as locations, for example list elements. psetf
evaluates all its values before storing (like the Common Lisp example).
(require 'cl-lib)
(defmacro swap (a b)
`(cl-psetf ,a ,b
,b ,a))
(setq lst (list 123 456))
(swap (car lst) (cadr lst))
;; now lst is '(456 123)
EMal
fun swap = Pair by var a, var b do return var%var(b => a) end
int a = 1
int b = 2
writeLine("before swap: a=" + a + ", b=" + b)
Pair pair = swap(a, b)
a = pair[0]
b = pair[1]
writeLine(" after swap: a=" + a + ", b=" + b)
- Output:
before swap: a=1, b=2 after swap: a=2, b=1
Erlang
Erlang variables are single assignment and Erlang is dynamically typed, so this task doesn't really apply.
The closest thing would be to swap the items in a list (shown in the shell).
1> L = [a, 2].
[a,2]
2> lists:reverse(L).
[2,a]
Or swap the items in a tuple (also shown in the shell).
1> T = {2,a}.
{2,a}
2> list_to_tuple(lists:reverse(tuple_to_list(T))).
{a,2}
Euphoria
include std/console.e -- for display
object x = 3.14159
object y = "Rosettacode"
{y,x} = {x,y}
display("x is now []",{x})
display("y is now []",{y})
x is now Rosettacode y is now 3.14159
objects are generic, and can accept any type.
More strongly-typed variables can be swapped, if their types match or if the value is "acceptable" to the declared type.
In the above example, if we declared y as an integer, the swap would fail, pi is not an integer. If we declare y as an atom, it would succeed, as atoms can contain any valid number. If we declare y as a sequence or string, it would fail, because x is atomic.
F#
let swap (a,b) = (b,a)
Factor
Depending on how you look at it: this task doesn't apply, or it's trivial:
swap
Falcon
a = 1
b = 2
a,b = arr = b,a
Reading right to left: Assign b & a into an array variable called arr, then assign into a & b
Fish
Swap the top two values on the stack:
$
Forth
Since the Forth stack can contain pointers to any data type all we need is...
swap
Fortran
MODULE Genericswap
IMPLICIT NONE
INTERFACE Swap
MODULE PROCEDURE Swapint, Swapreal, Swapstring
END INTERFACE
CONTAINS
SUBROUTINE Swapint(a, b)
INTEGER, INTENT(IN OUT) :: a, b
INTEGER :: temp
temp = a ; a = b ; b = temp
END SUBROUTINE Swapint
SUBROUTINE Swapreal(a, b)
REAL, INTENT(IN OUT) :: a, b
REAL :: temp
temp = a ; a = b ; b = temp
END SUBROUTINE Swapreal
SUBROUTINE Swapstring(a, b)
CHARACTER(*), INTENT(IN OUT) :: a, b
CHARACTER(len(a)) :: temp
temp = a ; a = b ; b = temp
END SUBROUTINE Swapstring
END MODULE Genericswap
PROGRAM EXAMPLE
USE Genericswap
IMPLICIT NONE
INTEGER :: i1 = 1, i2 = 2
REAL :: r1 = 1.0, r2 = 2.0
CHARACTER(3) :: s1="abc", s2="xyz"
CALL Swap(i1, i2)
CALL Swap(r1, r2)
CALL Swap(s1, s2)
WRITE(*,*) i1, i2 ! Prints 2 and 1
WRITE(*,*) r1, r2 ! Prints 2.0 and 1.0
WRITE(*,*) s1, s2 ! Prints xyz and abc
END PROGRAM EXAMPLE
Free Pascal
{$ifdef fpc}{$mode delphi}{$H+}{$endif}
{ note this is compiled with delphi mode but will only compile in Free Pascal }
{ Delphi doesn't support this syntax }
procedure swap<T>(var left,right:T);
var
temp:T;
begin
temp:=left;
left:=right;
right:=temp;
end;
var
a:string = 'Test';
b:string = 'me';
begin
writeln(a:6,b:6);
swap<string>(a,b);
writeln(a:6,b:6);
end.
Output: Test me me Test
Frink
The following example will work on all Frink data types:
[b,a] = [a,b]
Fōrmulæ
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation —i.e. XML, JSON— they are intended for storage and transfer purposes more than visualization and edition.
Programs in Fōrmulæ are created/edited online in its website.
In this page you can see and run the program(s) related to this task and their results. You can also change either the programs or the parameters they are called with, for experimentation, but remember that these programs were created with the main purpose of showing a clear solution of the task, and they generally lack any kind of validation.
Solution
Fōrmulæ supports assignments of several symbols (provided as a list) from an expression that reduces to a list of the same cardinality (the expression is first reduced before the actual assignment).
This can be used to do a generic swap as follows:
Test case
Gecho
1 !0 2 !1
Now tape[0] and tape[1] are set to 1 and 2, respectively.
&0 &1 !0 pop !1
This pushes the value of tape[0] to the stack, tape[1] to the stack, sets tape[0] to the top element, and then pops it, then tape[1] to the top element.
Go
Built in
Not a valid solution, since the task requires writing a function or operator, but it is worth mentioning that Go's built in assignment operator does generic swap. The following swaps the values of a and b as long as they are of identical type.
a, b = b, a
Pass interfaces
A generic swap function can easily be written however, if you require the caller to use variables of the empty interface type. The empty interface can hold a value of any type.
package main
import "fmt"
func swap(a, b *interface{}) {
*a, *b = *b, *a
}
func main() {
var a, b interface{} = 3, "four"
fmt.Println(a, b)
swap(&a, &b)
fmt.Println(a, b)
}
- Output:
3 four four 3
Pass pointers
Somewhat less restrictive, this version allows pointers of any type to be passed, as long as they are the same type.
package main
import (
"fmt"
"reflect"
)
func swap(a, b interface{}) error {
ta := reflect.TypeOf(a)
tb := reflect.TypeOf(b)
if ta != tb {
return fmt.Errorf("swap args are different types: %v and %v", ta, tb)
}
if ta.Kind() != reflect.Ptr {
return fmt.Errorf("swap args must be pointers")
}
ea := reflect.ValueOf(a).Elem()
eb := reflect.ValueOf(b).Elem()
temp := reflect.New(ea.Type()).Elem()
temp.Set(ea)
ea.Set(eb)
eb.Set(temp)
return nil
}
func main() {
a, b := 3, "cats"
fmt.Println("a b:", a, b)
err := swap(a, b)
fmt.Println(err, "\n")
c, d := 3, 4
fmt.Println("c d:", c, d)
err = swap(c, d)
fmt.Println(err, "\n")
e, f := 3, 4
fmt.Println("e f:", e, f)
swap(&e, &f)
fmt.Println("e f:", e, f, "\n")
type mult struct {
int
string
}
g, h := mult{3, "cats"}, mult{4, "dogs"}
fmt.Println("g h:", g, h)
swap(&g, &h)
fmt.Println("g h:", g, h)
}
- Output:
a b: 3 cats swap args are different types: int and string c d: 3 4 swap args must be pointers e f: 3 4 e f: 4 3 g h: {3 cats} {4 dogs} g h: {4 dogs} {3 cats}
Gri
Putting &
in a call makes the parameter "call by reference", giving a command the opportunity to modify a variable in the caller. So to swap variables,
`Swap Vars &.a. &.b.'
{
new .temp.
.temp. = \.word2.
\.word2. = \.word3.
\.word3. = .temp.
delete .temp.
}
.foo. = 123
.bar. = 456
Swap Vars &.foo. &.bar.
show .foo. " " .bar.
# prints "456 123"
Or similar to swap synonyms (strings),
`Swap Syns &\a &\b'
{
new \temp
\temp = "\.word2."
\.word2. = "\.word3."
\.word3. = "\temp"
delete \temp
}
\quux = "one"
\xyzzy = "two"
Swap Syns &\quux &\xyzzy
show "\quux \xyzzy"
# prints "two one"
Groovy
Groovy has support for swapping built in:
(a, b) = [b, a]
But the task calls for a "generic swap method" to be written, so here it is:
def swap(a, b) {
[b, a]
}
This function doesn't mutate anything, but simply returns a new list with the order of the elements switched. It can be used like shown below:
def (x, y) = swap(1, 3)
assert x == 3
assert y == 1
Some examples here show an in-place swap of indexed elements in an array or collection, so for completeness here is an in-place swap of arbitrary indexed elements in a list:
def listSwap = { a, i, j ->
assert (0..<(a.size())).containsAll([i,j]);
a[[j,i]] = a[[i,j]]
}
def list = [2,4,6,8]
listSwap(list, 1, 3)
assert list == [2,8,6,4]
Harbour
Harbour has no build-in swap function, however, implemention of a UDF is a fairly easy task. And since it's a dynamic typed lang, there won't be problem while swapping different value types.
Implementation: (We exploit "pass by reference" method on the parameters used)
PROCEDURE Swap( /*@*/v1, /*@*/v2 )
LOCAL xTmp
xTmp := v1
v1 := v2
v2 := xTmp
RETURN
Sample code:
FUNCTION Main()
LOCAL v1 := "World!", v2 := "Hello"
? v1, v2 // --> World! Hello
Swap( @v1, @v2 )
? v1, v2 // --> Hello World!
RETURN 0
Haskell
Pure swap
Usually Haskellers prefer to work with immutable data. The following function doesn't mutate anything, but simply returns a new pair with the order of the elements switched.
The type signature, the first line, is optional; it may be inferred.
swap :: (a, b) -> (b, a)
swap (x, y) = (y, x)
This swap
function is available in the Data.Tuple
standard library module in GHC 7.0+
Swap mutable variables
The following function swaps the contents of two mutable references. Again the type signature is optional.
import Control.Monad.Ref
swap :: MonadRef r m => r a -> r a -> m ()
swap xRef yRef = do
x<-readRef xRef
y<-readRef yRef
writeRef xRef y
writeRef yRef x
Icon and Unicon
Icon provides a :=: operator for this. Additionally, there is a reversible exchange operator <-> that reverses the exchange if resumed.
IDL
IDL is dynamically typed and array-centric, so swapping is quite easy for any data type. The TEMPORARY function sets its argument to "undefined", and allows us to swap without any large copying.
pro swap, a, b
c = temporary(a)
a = temporary(b)
b = temporary(c)
end
J
J is dynamically typed and J's cycle primitive (C.
) will swap elements of an arbitrary list. See also J's reference documentation on C.
Shown here are a list of prime numbers and the result of J's parser on some random text (inverting the parsing process on the swapped result):
(<2 4) C. 2 3 5 7 11 13 17 19
2 3 11 7 5 13 17 19
(<0 3)&C.&.;:'Roses are red. Violets are blue.'
Violets are red. Roses are blue.
Also, if the argument list can be guaranteed to be a pair, J's reverse primitive will swap the pair.
|.2 3
3 2
|.&.;:'one two'
two one
A generic destructive swap of named values would instead require reference to the locations being destroyed. Here's an implementation of that:
destructiveSwap=: {{ EMPTY[ (m;n)=: n ,&<&do m }}
Example use:
V1=: 'cat'
V2=: 7
'V1' destructiveSwap 'V2'
V1
7
V2
cat
Jakt
fn swap<T>(anon a: &mut T, anon b: &mut T) {
let temporary = *a
*a = *b
*b = temporary
}
fn main() {
mut a = "Hello"
mut b = "World"
println("{} {}", a, b)
swap(&mut a, &mut b)
println("{} {}", a, b)
mut c = 1
mut d = 2
println("{} {}", c, d)
swap(&mut c, &mut d)
println("{} {}", c, d)
}
Java
Java uses references, so it can't swap the values of two variables that don't belong to a class.
class Pair<T> {
T first;
T second;
}
public static <T> void swap(Pair<T> p) {
T temp = p.first;
p.first = p.second;
p.second = temp;
}
JavaScript
JavaScript uses references, but if a function reassigns a parametric reference, the new object only has a local reference. However, if we wrap the variables to be switched in some other structure, like an object or an array, we can easily swap the values.
There's no actual "generics", since all variables are just that, variables of some kind.
The below function expects an array of length 2 (or longer), and switches the first two values in place, in the same array. This is closely related to how the Java solution works.
function swap(arr) {
var tmp = arr[0];
arr[0] = arr[1];
arr[1] = tmp;
}
Also there is metaprogramming solution. It uses code generation and eval. To avoid naming conflicts(user can pass 'tmp', which causes var tmp = tmp) it uses buildin, per activation context (thats why it is enclosed into self executing lambda), var arguments for temp storage.
function swap(aName, bName) {
eval('(function(){ arguments[0] = aName; aName = bName; bName = arguments[0] })()'
.replace(/aName/g, aName)
.replace(/bName/g, bName)
)
}
var x = 1
var y = 2
swap('x', 'y')
Solution without eval(), assuming that the code is running in the browser (window is the global object)
function swap(a, b) {
var tmp = window[a];
window[a] = window[b];
window[b] = tmp;
}
var x = 1;
var y = 2;
swap('x', 'y');
Another solution for swapping array items using destructing assignment:
const arr = [1, 2, 3, 4, 5];
[arr[0], arr[1]] = [arr[1], arr[0]]
Joy
Provided that the stack contains at least two elements:
swap
changes the order of those elements.
jq
jq is a functional language, so one is more likely to want to swap the two elements of an array than to swap the values of two variables, but jq does have variables and their values can be swapped, for example, using an intermediate variable, say $tmp, as illustrated here:
jq -n '1 as $a | 2 as $b | $a as $tmp | $b as $a | $tmp as $b | [$a,$b]'
Here is a filter that will swap the elements of a two-element array:
reverse
And here is a filter that, if presented with an array, will in effect copy it and then swap the i-th and j-th items, it being understood that if a is an array and k < 0 or k >= (a|length), then a[k] will evaluate to null:
def swap(i;j): .[i] as $t | .[i] = .[j] | .[j] = $t;
Julia
Similar to Python, Julia has built-in support for swapping:
a, b = b, a
Kotlin
As Kotlin does not support passing parameters by reference and tuples cannot be destructured automatically to pre-existing variables, it's just as easy to swap variable values 'inline' rather than using a function. However, here's one of way of doing it generically using the latter:
fun <T> swap(t1: T, t2: T) = Pair(t2, t1)
fun main() {
var a = 3
var b = 4
val c = swap(a, b) // infers that swap<Int> be used
a = c.first
b = c.second
println("a = $a")
println("b = $b")
var d = false
var e = true
val f = swap(d, e) // infers that swap<Boolean> be used
d = f.first
e = f.second
println("d = $d")
println("e = $e")
}
- Output:
a = 4 b = 3 d = true e = false
You can also explicitly create a container class and swap the value that it contains (but this is a bad idea in practice):
data class Ref<T>(var value: T) {
fun swap(other: Ref<T>) {
val tmp = this.value
this.value = other.value
other.value = tmp
}
override fun toString() = "$value"
}
fun main() {
val a = Ref(1)
val b = Ref(2)
a.swap(b)
println(a)
println(b)
}
Lambdatalk
1) using an Immediately Invoked Function Expression:
{{lambda {:x :y} :y :x} hello world}
-> world hello
2) or user defined function
{def swap {lambda {:x :y} :y :x}}
-> swap
3) applied on words (which can be numbers)
{swap hello world}
-> world hello
{swap hello brave new world}
-> brave new hello world
{swap {cons hello brave} {cons new world}}
-> (new world) (hello brave)
Lang
# Swap function with call-by-pointer
fp.swap = ($[aPtr], $[bPtr]) -> {
$tmp = $*aPtr
$*aPtr = $*bPtr
$*bPtr = $tmp
}
$a = 42
$b = A short text
fn.println($a, $b)
fp.swap($a, $b)
fn.println($a, $b)
- Output:
42, A short text A short text, 42
Lang5
swap # stack
reverse # array
langur
Values can be swapped using multi-variable assignment.
var abc = [1, 2, 3]
var def = [5, 6, 7]
abc[3], def[3] = def[3], abc[3]
writeln abc
writeln def
- Output:
[1, 2, 7] [5, 6, 3]
Lasso
define swap(a, b) => (: #b, #a)
local(a) = 'foo'
local(b) = 42
local(a,b) = swap(#a, #b)
stdoutnl(#a)
stdoutnl(#b)
- Output:
42 foo
Using Decompositional Assignment
local(a) = 'hair'
local(b) = 'moose'
local(a,b) = (: #b, #a)
stdoutnl(#a)
stdoutnl(#b)
- Output:
moose hair
Lhogho
Lhogho is very similar except that it does not have a localmake opcode.
to swap :s1 :s2
local "t
make "t thing :s1
make :s1 thing :s2
make :s2 :t
end
make "a 4
make "b "dog
swap "a "b ; pass the names of the variables to swap
show list :a :b ; [dog 4]
Lingo
A generic swap function is not possible in Lingo, since scalar values are passed by value. But the following solution shows how such generic swapping still can be achieved by executing a single line of code:
on swap (x, y)
return "tmp="&x&RETURN&x&"="&y&RETURN&y&"=tmp"
end
Usage:
x = 1
y = 2
do(swap("x","y"))
put x, y
-- 2 1
Lisaac
(a, b) := (b, a);
LiveCode
put "first" into a1
put "last" into b2
swap a1,b2
put a1 && b2
command swap @p1, @p2
put p2 into p3
put p1 into p2
put p3 into p1
end swap
Logo
to swap :s1 :s2
localmake "t thing :s1
make :s1 thing :s2
make :s2 :t
end
make "a 4
make "b "dog
swap "a "b ; pass the names of the variables to swap
show list :a :b ; [dog 4]
Logtalk
:- object(paws).
:- public(swap/4).
swap(First, Second, Second, First).
:- end_object.
Usage examples:
| ?- paws::swap(apples, oranges, X, Y).
X = oranges
Y = apples
yes
| ?- paws::swap(3.14, ext(lgt), X, Y).
X = ext(lgt)
Y = 3.14
yes
LOLCODE
LOLCODE's dynamic typing makes generic swapping trivial. In addition, the special IT variable‒which contains the most recently evaluated expression‒permits doing so without explicitly creating a temporary variable.
HAI 1.3
I HAS A foo ITZ "kittehz"
I HAS A bar ITZ 42
foo, foo R bar, bar R IT
VISIBLE foo BTW, 42
VISIBLE bar BTW, kittehz
KTHXBYE
Lua
Lua evaluates the values on the right-hand side before assigning them to the variables on the left-hand side. This behaviour allows the following notation to be used to swap two values:
x, y = y, x -- swap the values inside x and y
t[1], t[2] = t[2], t[1] -- swap the first and second values inside table t
Usage example:
x, y = 3, 4
print(x, y) --> 3 4
x, y = y, x -- swap
print(x, y) --> 4 3
M2000 Interpreter
Swap is a statement in M2000 which get two identifiers, variables or array items. Variables and Array items are all internal type of Variant. Normally a numeric variable hold the first type we assign to it. Numeric types are: Double, Single, Decimal, Currency, Decimal, Long, Integer. Boolean is also a type but true and false are not boolean, they are double -1 and 0). When we use Swap internal only variant swap happen, without check of type of variant.
Here we make a local Swap and pass by reference, numbers and strings. References created without testing what type of variant we use. So calling swap we make a swap moving bytes, and for strings this means moving pointers to BSTR type of strings.
\\ programming again Swap (for local use)
Module Swap (&a, &b) {
\\ this call internal command - by default is by reference without using character &
Swap a, b
}
X=20
Y=100
Swap &x, &y
Print X, Y, Type$(X)="Double",Type$(Y)="Double"
A$="A$"
B$="B$"
Swap &A$, &B$
Print A$="B$", B$="A$"
Using Swap (internal command), for variables, groups (only for variables inside groups), pointers to groups, pointers to containers, etc.
a=1000
b=50
Swap a,b
Print a, b
A$="Hello"
B$="There"
Swap A$, B$
Print A$, B$
Dim A(4)
A(0):=1,2,3,4
Swap A(3), A(2)
Print A(3), A(2)
\\ Groups are Values
Group alfa {
x=10, y=20
}
Group Beta {
x=40, y=50
}
\\ with List we show the public variables
\\ so among other variables there are:
\\ alfa[Group], alfa.x=10, alfa.y=20, beta[group], beta.x=40, beta.y=50
\\ So Alfa.x and Beta.x are simple variables, we can use swap
Swap Alfa.x, Beta.x
Print Alfa.x, Beta.x
Swap Alfa.x, Beta.x
List
\\ We have to use a third variable to hold value
For This {
\\ Local always make a new variable, and shadow any same local variable
Local M=alfa
alfa=beta
beta=m
}
\\ Now M erased (defined in For This block)
Print Alfa.x=40, Alfa.y=50
Print Beta.x=10, Beta.y=20
\\ Using -> we make pointers to Alfa, and Beta
\\ These pointers are valid until Alfa and Beta erased, or get Empty Group (->0)
pA->Alfa
pB->Beta
Print pA=>x=40, pA=>y=50
Print pB=>x=10, pB=>y=20
Swap pA,pB
Print pA=>x=10, pA=>y=20 ' pA point to beta
Print pB=>x=40, pB=>y=50 'pB point to alfa
Print type$(pA)="Group",Valid(pA=>X)=True
pA->0
pB->0
Print type$(pA)="Group",Valid(pA=>X)=False
\\ These pointers are valid until get Empty Group (->0), they point to a copy of Alfa and Beta
\\ both are in heap as "closed groups"
pA->(Alfa)
pB->(Beta)
Print pA=>x, pA=>y
\\ swap need variables or arrays
\\ pA=>x are closed to object so we have to open the object, and use the open one, where all public variables of group can be used
For pA, pB {
Swap .x, .y
}
Print pA=>x, pA=>y
For pA, pB {
Swap .x, .y
}
Print pA=>x, pA=>y
Print pB=>x, pB=>y
Swap pA,pB
Print pA=>x, pA=>y
Print pB=>x, pB=>y
L1=lambda x=1->{=x : x++}
L2=lambda x=100->{=x : x--}
Print L1()=1, L2()=100
Swap L1, L2
Print L1()=99, L2()=2
Swap L1, L2
Print L1()=3, L2()=98
\\ swap change pointers to containers (here pointers to arrays)
A=(1,2,3,4,5)
B=(6,7,8,9,10)
Swap A, B
Print A
Print B
\\ Arrays with () in names are values
Dim A(10)=1, B(10)=2
For This {
Dim C()
C()=A()
A()=B()
B()=C()
}
Print A()
Print B()
M4
define(`def2', `define(`$1',`$2')define(`$3',`$4')')dnl
define(`swap', `def2(`$1',defn(`$2'),`$2',defn(`$1'))')dnl
dnl
define(`a',`x')dnl
define(`b',`y')dnl
a b
swap(`a',`b')
a b
- Output:
x y y x
Maple
The assignment operator in Maple can swap values, since the right hand side is evaluated before the assignment occurs.
> a, b := 2, "foo":
> a;
2
> b;
"foo"
> a, b := b, a: # SWAP
> a;
"foo"
> b;
2
Mathematica / Wolfram Language
Mathematica functions are generic by default; however, it has to be told not to evaluate the arguments before executing the function.
swap[a_, b_] := {a, b} = {b, a}
SetAttributes[swap, HoldAll]
MATLAB / Octave
Numercial swaps are trivial operations. In fact, they are so natural to the language that multiple swaps can be performed simultaneously.
Example:
>> a = [30 40 50 60 70]
a =
30 40 50 60 70
>> a([1 3]) = a([3 1]) %Single swap
a =
50 40 30 60 70
>> a([1 2 4 3]) = a([2 3 1 4]) %Multiple swap, a.k.a permutation.
a =
40 30 60 50 70
A generic swap (compatible with any variable type) can be performed with the deal command:
>> a = 12
a = 12
>> b = 'foo'
b = foo
>> [b, a] = deal (a, b)
b = 12
a = foo
Maxima
a: 10$
b: foo$
/* A simple way to swap values */
[a, b]: [b, a]$
a; /* foo */
b; /* 10 */
/* A macro to hide this */
swap(x, y) ::= buildq([x, y], ([x, y]: [y, x], 'done))$
swap(a, b)$
a; /* 10 */
b; /* foo */
MAXScript
swap a b
Metafont
In Metafont, only numeric declarations can be omitted; any other type, must be explicitly given. So our swap, in order to declare and use a proper temporary variable(? in this code), must check the type of the variable passed (we check only for a; if b is of another kind, an error will occur)
vardef swap(suffix a, b) =
save ?; string s_;
if boolean a: boolean ?
elseif numeric a: numeric ? % this one could be omitted
elseif pair a: pair ?
elseif path a: path ?
elseif pen a: pen ?
elseif picture a: picture ?
elseif string a: string ?
elseif transform a: transform ? fi;
? := a; a := b; b := ?
enddef;
Examples:
j := 10;
i := 5;
show j, i;
swap(j,i);
show j, i;
boolean truth[];
truth1 := true;
truth2 := false;
show truth1, truth2;
swap(truth1,truth2);
show truth1, truth2;
min
Like many other stack languages, this is trivial.
swap
MiniScript
Like many other languages, MiniScript passes references by value, so a straightforward swap is impossible. However, there is a trick: given the map the variales are in (e.g. locals
) and the names of the variables, we can swap them.
swap = function(map, a, b)
temp = map[a]
map[a] = map[b]
map[b] = temp
end function
x = 1
y = 2
print "BEFORE: x=" + x + ", y=" + y
swap(locals, "x", "y")
print "AFTER: x=" + x + ", y=" + y
- Output:
BEFORE: x=1, y=2 AFTER: x=2, y=1
Modula-3
GENERIC INTERFACE GenericSwap(Elem);
PROCEDURE Swap(VAR left: Elem.T; VAR right: Elem.T);
END GenericSwap.
GENERIC MODULE GenericSwap(Elem);
PROCEDURE Swap(VAR left: Elem.T; VAR right: Elem.T) =
VAR temp: Elem.T := left;
BEGIN
left := right;
right := temp;
END Swap;
BEGIN
END GenericSwap.
Here is an example usage for integers:
INTERFACE IntSwap = GenericSwap(Integer) END IntSwap.
MODULE IntSwap = GenericSwap(Integer) END IntSwap.
MODULE Main;
IMPORT IntSwap, IO, Fmt;
VAR left := 10;
right := 20;
BEGIN
IO.Put("Left = " & Fmt.Int(left) & "\n");
IntSwap.Swap(left, right);
IO.Put("Left = " & Fmt.Int(left) & "\n");
END Main.
- Output:
Left = 10 Left = 20
Nemerle
For pairs, namespace Nemerle.Utility.Pair contains Swap():
def coords = (1, -1);
def invcoords = Swap(coords);
Or to swap two mutable variables of the same type:
a <-> b;
But, enough about built in functionality, let's demonstrate using generics:
Swap[T, U] (a : T, b : U) : U * T
{
(b, a)
}
NetRexx
Values stored in the default Rexx data type are treated as typeless data; context is based on the contents. Swapping the contents of variables stored in Rexx object can be achieved via the PARSE instruction.
/* NetRexx */
options replace format comments java crossref symbols nobinary
-- Simple values with no spaces can be swapped without the use of a parse template
lval = 27
rval = 5
say 'Before - <lval>'lval'</lval> <rval>'rval'</rval>'
parse (lval rval) rval lval
say 'After - <lval>'lval'</lval> <rval>'rval'</rval>'
say
-- More complex data needs to use some form of parsing template
lval = 'This value started on the left'
rval = 'This value started on the right'
dlm = 12x80facebead01 -- some delimiting value that is unlikely to occur in the LVAL to be swapped
say 'Before - <lval>'lval'</lval> <rval>'rval'</rval>'
parse (lval || dlm || rval) rval (dlm) lval
say 'After - <lval>'lval'</lval> <rval>'rval'</rval>'
say
return
- Output:
Before - <lval>27</lval> <rval>5</rval> After - <lval>5</lval> <rval>27</rval> Before - <lval>This value started on the left</lval> <rval>This value started on the right</rval> After - <lval>This value started on the right</lval> <rval>This value started on the left </rval>
NewLISP
(swap a b)
Nial
Like J
|reverse 1 2
=2 1
Nim
Builtin procedure swap
. Example usage:
swap(a, b)
OASYS Assembler
You can swap variable %A# with %B# by writing:
%A#%B#<%B#%A#<>>
A method which can be called to implement it can be written like:
[&SW,A^,B^],A^<,B^<<,B^<,A^<<>>
To call such method:
+%A#%B#&SW
OCaml
Tuples are immutable in OCaml. This function doesn't mutate anything, but simply returns a new pair with the order of the elements switched.
let swap (x, y) = (y, x)
If the arguments are constrained to be reference values, a swap function is simple:
let swapref x y =
let temp = !x in
x := !y;
y := temp
Oforth
swap
Oz
Oz variables are dataflow variables and cannot be changed once a value has been assigned. So a swap operation on dataflow variables does not make sense.
We can write a swap procedure for cells, though. Cells are mutable references.
proc {SwapCells A B}
Tmp = @A
in
A := @B
B := Tmp
end
Or shorter, if we exploit the fact that the assignment operator :=
returns the old value of the cells:
proc {SwapCells A B}
B := A := @B
end
A functional swap, operating on pairs:
fun {SwapPair A#B}
B#A
end
PARI/GP
Pari is near-typeless—everything is a GEN.
my(tmp=a);
a=b;
b=tmp;
[a,b]=[b,a]
Pascal
Standard Pascal does not have generics, but FreePascal has a start:
program generictest;
{$mode objfpc}
type
generic TSwap<T> = procedure (var a, b: T);
procedure Proc1(var a, b: integer);
var
temp: integer;
begin
temp := a;
a := b;
b := temp;
end;
var
S, T: integer;
SwapInt: specialize TSwap<integer>;
begin
S := 4;
T := 3;
SwapInt := @Proc1;
writeln(S, T:2);
SwapInt(S, T);
writeln(S, T:2);
end.
- Output:
4 3 3 4
since FreePascal version 3.2.0:
program generic_test;
{$mode objfpc}{H+}
uses
SysUtils;
generic procedure GSwap<T>(var L, R: T);
var
Tmp: T;
begin
Tmp := L;
L := R;
R := Tmp;
end;
var
I, J: Integer;
begin
I := 100;
J := 11;
WriteLn('I = ', I, ', J = ', J);
specialize GSwap<Integer>(I, J);
WriteLn('I = ', I, ', J = ', J);
end.
- Output:
I = 100, J = 11 I = 11, J = 100
PascalABC.NET
procedure Swap<T> (var a,b: T) := (a,b) := (b,a);
begin
var (i,j) := (1,2);
Swap(i,j);
Println(i,j);
var (s1,s2) := ('PascalABC.NET','Hello');
Swap(s1,s2);
Println(s1,s2);
end.
- Output:
2 1 Hello PascalABC.NET
Perl
Perl has support for swapping built-in
($y, $x) = ($x, $y);
Here's a generic swap routine:
sub swap {@_[0, 1] = @_[1, 0]}
Phix
The following applies to any types. Subscripting and nesting may also be used freely on either side.
{a,b} = {b,a}
Phixmonti
Applies to any types.
a b var a var b
PHP
function swap(&$a, &$b) {
list($a, $b) = array($b, $a);
}
Picat
Picat supports re-assignment (:=
), but it is not possible to swap two variables like this:
A = 1,
B = 2,
[A,B] := [B,A],
% ...
(This throws an error: "invalid left-hand side of assignment").
The following works, but it's probably not general enough for this task:
A = 1,
B = 2,
T = A, % Assuming that T is not used elsewhere in the clause
A := B,
B := T,
% ...
Instead swaps has to be done by some other means.
Inline swapping in a list
One way is to place the values in a list (or array) and use inline swapping of the list.
% Swapping positions in a list/array
swap2(L) =>
swap_list(L,1,2).
% Swap two elements in a list
swap_list(L,I,J) =>
T = L[I],
L[I] := L[J],
L[J] := T.
Usage:
L = [1,2],
swap2(L),
% ...
L is now [2,1]
Note: Placing the variables A, B in swap2
swap2([A,B])
will NOT change the values of A and B.
Using a second list
Another way is to place the swapped values in a second list:
swap_pair([A,B],[B,A]).
Usage:
A = 1,
B = 2,
swap_pair([A,B],X),
% ...
X is now [2,1]. A is still 1 and B is still 2.
PicoLisp
xchg works with any data type
(let (A 1 B 2)
(xchg 'A 'B)
(println A B) )
(let (Lst1 '(a b c) Lst2 '(d e f))
(xchg (cdr Lst1) (cdr Lst2))
(println Lst1 Lst2) )
- Output:
2 1 (a e c) (d b f)
Pike
mixed first = 5;
mixed second = "foo";
array pair = ({ 5, "foo" });
void swapvars(string a, string b)
{
[this[a], this[b]] = ({ this[b], this[a] });
}
void swaparray(array swapit)
{
[swapit[1], swapit[0]] = ({ swapit[0], swapit[1] });
}
void main()
{
write("swap variables:\n");
write("%O, %O\n", first, second);
// we could just use [first, second] = ({ second, first });
swapvars("first", "second");
write("%O, %O\n", first, second);
write("swap array:\n");
write("%{ %O %}\n", pair);
// we could just use [pair[1], pair[0]] = ({ pair[0], pair[1] });
// directly, but since arrays are called by reference,
// it also works through a function
swaparray(pair);
write("%{%O %}\n", pair);
}
- Output:
swap variables: 5, "foo" "foo", 5 swap array: 5 "foo" "foo" 5
PL/I
Using the preprocessor
%swap: procedure (a, b);
declare (a, b) character;
return ( 't=' || a || ';' || a || '=' || b || ';' || b '=t;' );
%end swap;
%activate swap;
The statement:-
swap (p, q);
is replaced, at compile time, by the three statements as in-line code:
t = p; p = q; q = t;
Using generic procedures
declare swap generic (
swapf when (float, float),
swapc when (char, char));
swapf: proc (a, b);
declare (a, b, t) float;
t = a; a = b; b = t;
end swapf;
swapc: proc (a, b);
declare (a, b) character(*);
declare t character (length(b));
t = a; a = b; b = t;
end swapc;
declare (r, s) character (5);
call swap (r, s);
Both of the above are not completely generic, but depend on either the presence of
- a temporary variable with the same attributes of the variables to be swapped, OR
- data-attribute specific procedures for the swap
The following code is completely generic, but, in line with the usual safety offered by PL/I, swaps only the contents up to the storage occupied by the smallest of the two variables: Prino 01:24, 11 February 2011 (UTC)
Completely generic code using the pre-processor
%swap: proc(x,y);
dcl (x, y) char;
x = trim(x); /* Just for neatness sake */
y = trim(y);
ans('begin; ') skip;
ans(' dcl c char (1); ') skip;
ans(' dcl sx char (1) based(px); ') skip;
ans(' dcl sy char (1) based(py); ') skip;
ans(' dcl i fixed bin (31); ') skip;
ans(' dcl px ptr init (addr(' || x || ')); ') skip;
ans(' dcl py ptr init (addr(' || y || ')); ') skip;
ans(' do i = 1 to min(stg(' || x || '), stg(' || y || '));') skip;
ans(' c = sx; ') skip;
ans(' sx = sy; ') skip;
ans(' sy = c; ') skip;
ans(' px = px + 1; ') skip;
ans(' py = py + 1; ') skip;
ans(' end; ') skip;
ans('end; ') skip;
%end swap;
%act swap;
dcl c1 char (10) init ('1234567890');
dcl c2 char (10) init ('ABCDEFGHIJ');
dcl f1 fixed bin (31) init (12345);
dcl f2 fixed bin (31) init (98765);
put data(c1, c2, f1, f2);
swap(c1, c2);
swap(f1, f2);
put data(c1, c2, f1, f2);
f1 = -656877352; /* '5a5a5a5a'x, aka 'QQQQ' */
swapper(c1, f1);
put data(c1,f1);
The code generated by 'swap(c1, c2);' looks like
begin;
dcl c char (1);
dcl sx char (1) based(px);
dcl sy char (1) based(py);
dcl i fixed bin (31);
dcl px ptr init (addr(C1));
dcl py ptr init (addr(C2));
do i = 1 to min(stg(C1), stg(C2));
c = sx;
sx = sy;
sy = c;
px = px + 1;
py = py + 1;
end;
end;
and, because declarations in PL/I begin blocks are local to that block, generating several blocks with the same variables will not cause any problems.
The result of compiling, linking and executing the above code:
C1='1234567890' C2='ABCDEFGHIJ' F1= 12345 F2= 98765; C1='ABCDEFGHIJ' C2='1234567890' F1= 98765 F2= 12345; C1='QQQQEFGHIJ' F1= -1044200508;
Or, using "Like"
The key problem is that a temporary storage area is needed (there alas being no compiler-recognised "swap" statement), and the waystation variable must have the correct type, nor can there be reliance on a suitable "t" variable being available for use. Devising a different Swap for each type of parameter would be tedious and tiresome to use, however one could employ the "generic" facility as above demonstrated, and use the pre-processor to generate a collection of Swap routines by it employing a template and stepping through a list of accommodated types.
Instead, the first example can be generalised via two steps. Firstly, it is possible to declare a variable to be of a type "like" some named variable (otherwise a third parameter naming the type could be supplied), and secondly, placing the in-line code between Begin ... End; means that any declaration is local to within that block only. Further, this bracketing allows a Swap to be invoked via an if-statement, as in If ... then Swap(x,y);
- otherwise there would be a mess. Thus:
%Swap:Procedure(a,b);
declare (a,b) character; /*These are proper strings of arbitrary length, pre-processor only.*/
return ('Begin; declare t like '|| a ||'; t='|| a ||';'|| a ||'='|| b ||';'|| b ||'=t; End;');
%End Swap;
Whereupon a Swap(this,that); would generate a rather longer text of in-line source code. This and other text expansions caused odd difficulties, because the 1980s compiler replaced the invocation by the expansion and then reformatted the result into lines of 71 characters (not 72) as necessary, and then, since any additional lines were given the same source sequence number as the original line, added 100000 as needed to generate strictly increasing sequence numbers. If many lines overflowed, eventually the sequence field (eight digits) overflowed, and all following source lines thereby acquired the same source sequence number. For this and other reasons, one approach was two-stage compilation: the output from the pre-processor stage could be saved and further compilation cancelled. That file could then be resequenced and fed to the pl/i compiler afresh.
Such a file would have the expansion of Swap(this,that) as follows (but with added layout here):
Begin;
declare t like this;
t = this;
this = that;
that = t;
End;
There would however be trouble if the type of this differed from the type of that, and a pl/i compiler may not generate a warning because it handles many type conversions in an assignment without complaint. There are no pre-processor enquiry functions to inspect the types at pre-processor time - if there were, a more accomplished Swap procedure could produce suitable error reports, which can be classed as "warning" or "severe", etc. The "storage" function produces its result at run time, but, each invocation of Swap being compiled would have its actual parameters known as the compiler dealt with the code produced by that invocation of Swap, and so for each invocation, the results of "storage" would be constants - except for items that were allocated at run time.
The bracketing could be via DO; ... END;
instead of BEGIN; ... END;
but in that case the declared temporary variable would be visible outside its fragment and there could be conflicts, either of differing type for the same name or of multiple declaration. This could be solved by adjusting Swap to generate a different name each time. One could try a prefix (or suffix) to the name of the first parameter (thus generating say SwapTemp_this
or similar), but there would still be difficulty if there were multiple swaps involving the same variable. Instead, Swap could count its invocations and generate a name involving that. Temporary variables would then litter the storage area, and they could consume a lot of space. On the other hand, the BEGIN; ... END;
arrangement, though typically involving temporary space on the data stack, could have its own constraints. In the 1980s, the IBM mainframe pl/i compiler had a limit of no more than 240 (or so) BEGIN; ... END;
blocks, plus procedure blocks, plus a few other items, in any one compilation otherwise there would be a failure "in phase PI". Separate compilation and the linking of pieces introduced its own oddities, as when pieces had been compiled with different compiler options.
Plain English
Plain English includes a routine for swapping two values in its noodle.
Swap [a value] with [another value].
Pop11
Swap is easily done via multiple assignment:
(a, b) -> (b, a);
Pop11 is dynamically typed, so the code above is "generic".
PostScript
Works with anything you can put on the operand stack:
exch
PowerShell
PowerShell allows swapping directly, through tuple assignment:
$b, $a = $a, $b
But one can also define a function which swaps the values of two references:
function swap ([ref] $a, [ref] $b) {
$a.Value, $b.Value = $b.Value, $a.Value
}
When using this function the arguments have to be explicitly given as references:
swap ([ref] $a) ([ref] $b)
Prolog
swap(A,B,B,A).
?- swap(1,2,X,Y).
X = 2,
Y = 1.
Python
Python has support for swapping built in:
a, b = b, a
But the task calls for a "generic swap method" to be written, so here it is:
def swap(a, b):
return b, a
Note that tuples are immutable in Python. This function doesn't mutate anything, but simply returns a new pair with the order of the elements switched.
Quackery
Quackery objects reside on the stack while in use. The word swap exchanges the top and second item on the stack. The closest thing Quackery has to variables are ancillary stacks. The word exchange defined here exchanges the top items on two ancillary stacks.
[ over take over take
2swap dip put put ] is exchange ( s s --> )
R
R function arguments are passed by value, not by reference. You can work around this, however, by using their names and environment:
swap <- function(name1, name2, envir = parent.env(environment()))
{
temp <- get(name1, pos = envir)
assign(name1, get(name2, pos = envir), pos = envir)
assign(name2, temp, pos = envir)
}
Usage:
> x <- 1 > y <- 2 > swap('x', 'y') > cat(x, y) 2 1
Racket
A swap operation can be easily written as a macro in Racket. The macro will even work as expected in Typed Racket.
#lang racket/load
(module swap racket
(provide swap)
;; a simple macro to swap two variables
(define-syntax-rule (swap a b)
(let ([tmp a])
(set! a b)
(set! b tmp))))
;; works fine in a statically typed setting
(module typed typed/racket
(require 'swap)
(: x Integer)
(define x 3)
(: y Integer)
(define y 4)
(swap x y)
(printf "x is ~a~n" x)
(printf "y is ~a~n" y))
Raku
(formerly Perl 6)
Similar to Perl 5. Raku supports type constraints for variables and subroutines, unlike Perl 5, but the default is still to permit all values.
Alternatively, you can write it like this:
($x, $y) .= reverse;
REBOL
REBOL [
Title: "Generic Swap"
URL: http://rosettacode.org/wiki/Generic_swap
Reference: [http://reboltutorial.com/blog/rebol-words/]
]
swap: func [
"Swap contents of variables."
a [word!] b [word!] /local x
][
x: get a
set a get b
set b x
]
answer: 42 ship: "Heart of Gold"
swap 'answer 'ship ; Note quoted variables.
print rejoin ["The answer is " answer ", the ship is " ship "."]
- Output:
The answer is Heart of Gold, the ship is 42.
Retro
swap
REXX
REXX has no primitive for swapping, but it can easily be performed using a temporary variable.
(This is the slowest of the three versions.)
using temp
a = 'I see you.'
b = -6
_temp_ = a /*swap ··· */
a = b /* A ··· */
b = _temp_ /* and B */
using VALUE
This version will work with any values.
a = "bull feathers"
b = 10
a= value('b', a) /*swap A and B */
using PARSE
If it's known that there are
- no blanks
- no null values
- (maybe) no whitespace (such as tabs)
in the values, the following method can be used:
(This is the fastest of the three versions.)
a = -199e-12
b = 12.
parse value a b with b a /*swap A and B */
Note that some REXX interpreters handle whitespace differently, some honor whitespace other than blanks,
others don't (particularly the older versions).
Ring
a = 1
b = 2
temp = a
a = b
b = temp
see "a = " + a + nl
see "b = " + b + nl
RLaB
RLaB does not have a built-in function for swapping the content of two variables. However, there is a workaround which comes from the fact that the global variable space $$ contains all the variables var1, var2 and so forth as $$.var1, ...
Let we want to swap the content of two variables, which names are a and b, then the following function would do the trick
swap = function(x,y)
{
if (!exist($$.[x]))
{ return 0; }
if (!exist($$.[y]))
{ return 0; }
local (t);
t = $$.[x];
$$.[x] = $$.[y];
$$.[y] = t;
return 1;
};
>> a=1
1
>> b = "fish"
fish
>> swap( "a" , "b" );
>> a
fish
>> b
1
RPL
Code | Comments |
---|---|
≪ OVER TYPE 6 == OVER TYPE 6 == 2 * + 1 + { ≪ SWAP ≫ ≪ OVER EVAL SWAP ROT STO ≫ ≪ DUP EVAL ROT ROT STO ≫ ≪ OVER EVAL OVER EVAL 4 ROLL STO SWAP STO ≫ } SWAP GET EVAL ≫ 'GSWAP' STO 1 2 GSWAP 'A' 'B' GSWAP 3 'A' GSWAP |
":#" means "stack level #" calculate case index upon types of data at :1 and :2 case 1: swap :2 with :1 case 2: swap content of variable named at :2 with :1 case 3: swap content of variable named at :1 with :2 case 4: swap content of variables named at :1 and :2 select program from case index and execute it |
Ruby
Ruby has support for swapping built in:
a, b = b, a
But the task calls for a "generic swap method", so here it is:
def swap(a, b)
return b, a
end
This method does not swap the original variables, because Ruby passes parameters by value. Instead, this method returns simply a new array with the order of the elements switched. The caller may assign the original variables with the return value:
x = 42
y = "string"
x, y = swap x, y
puts x # prints string
puts y # prints 42
Rust
Rust does not allow for swapping the value of two variables with different types, but if the types are the same it can be done using generic types and lifetimes.
fn generic_swap<'a, T>(var1: &'a mut T, var2: &'a mut T) {
std::mem::swap(var1, var2)
}
This function can be used in e.g. the following ways:
fn main() {
let mut a: String = "Alice".to_owned();
let mut b: String = "Bob".to_owned();
let mut c: i32 = 1;
let mut d: i32 = 2;
generic_swap(&mut a, &mut b);
generic_swap(&mut c, &mut d);
println!("a={}, b={}", a, b);
println!("c={}, d={}", c, d);
}
- Output:
a=Bob, b=Alice c=2, d=1
Sather
A possible way that needs the type of the objects to be specified:
class SWAP{T} is
swap(inout a, inout b:T) is
t ::= a;
a := b;
b := t;
end;
end;
class MAIN is
main is
x ::= 10;
y ::= 20;
SWAP{INT}::swap(inout x, inout y);
#OUT + x + ", " + y + "\n";
end;
end;
Scala
Scala has type parameters and abstract types (not to be confused with abstract data types). The swap example is about as simple as such things can be, with no variance or high-order type parameters.
The return type need not be declared in the example below, but it is shown for clarity. However, as Scala does not pass parameters by reference, it cannot swap values in-place. To make up for that, it receives two values, and returns a tuple with the values inverted.
def swap[A,B](a: A, b: B): (B, A) = (b, a)
Scheme
; swap elements of a vector
; vector-swap! is not part of r5rs, so we define it
(define (vector-swap! v i j)
(let ((a (vector-ref v i)) (b (vector-ref v j)))
(vector-set! v i b)
(vector-set! v j a)))
(let ((vec (vector 1 2 3 4 5)))
(vector-swap! vec 0 4)
vec)
; #(5 2 3 4 1)
; we can swap also in lists
(define (list-swap! v i j)
(let* ((x (list-tail v i))
(y (list-tail v j))
(a (car x))
(b (car y)))
(set-car! x b)
(set-car! y a)))
(let ((lis (list 1 2 3 4 5)))
(list-swap! lis 0 4)
lis)
; (5 2 3 4 1)
; using macros (will work on variables, not on vectors or lists)
(define-syntax swap!
(syntax-rules ()
((_ a b)
(let ((tmp a))
(set! a b)
(set! b tmp)))))
; try it
(let ((a 1) (b 2)) (swap! a b) (list a b))
; (2 1)
sed
There are no variables in sed. Just a "pattern space" and a "hold space" — that's all. The x
command exchanges the contents of both.
Seed7
A generic template to generate swap functions is defined with:
const proc: generate_swap (in type: aType) is func
begin
const proc: swap (inout aType: left, inout aType: right) is func
local
var aType: temp is aType.value;
begin
temp := left;
left := right;
right := temp;
end func;
end func;
An instance of a swap function can be generated with:
generate_swap(integer);
generate_swap(string);
A swap function can be called with:
swap(a, b);
SenseTalk
set [x,y] to [13,"Hello"] -- assign values to two variables
put x,y
put
set [x,y] to [y,x] -- swap the variable values
put x,y
Output:
13
Hello
Hello
13
Sidef
func swap(Ref a, Ref b) {
var tmp = *a;
*a = *b;
*b = tmp;
}
or:
func swap(Ref a, Ref b) {
(*a, *b) = (*b, *a);
}
or:
func swap(Ref a, Ref b) {
[*a, *b] » (b, a);
}
The swap functions must be called with variable references.
var (x, y) = (1, 2);
swap(\x, \y);
Slate
This must be done with a macro method in Slate, but is in the standard library:
x@(Syntax LoadVariable traits) swapWith: y@(Syntax LoadVariable traits) &environment: env
"A macro that expands into simple code swapping the values of two variables
in the current scope."
[
env ifNil: [error: 'Cannot swap variables outside of a method'].
tmpVar ::= env addVariable.
{tmpVar store: x variable load.
x variable store: y variable load.
y variable store: tmpVar load} parenthesize
].
Usage:
a `swapWith: b
Smalltalk
An OrderedCollection can collect any kind of objects; so this swap implementend extending the OrderedCollection class is really generic.
OrderedCollection extend [
swap: a and: b [
|t|
t := self at: a.
self at: a put: (self at: b).
self at: b put: t
]
]
SNOBOL4
The "canonical" version from M. Emmers tutorial:
* SWAP(.V1, .V2) - Exchange the contents of two variables.
* The variables must be prefixed with the name operator
* when the function is called.
DEFINE('SWAP(X,Y)TEMP') :(SWAP_END)
SWAP TEMP = $X
$X = $Y
$Y = TEMP :(RETURN)
SWAP_END
Standard ML
Tuples are immutable in Standard ML. This function doesn't mutate anything, but simply returns a new pair with the order of the elements switched.
fun swap (x, y) = (y, x)
If the arguments are constrained to be reference values, a swap function is simple:
fun swapref (x, y) =
let temp = !x in x := !y; y := temp end
Stata
The Mata swap function is built-in.
mata
a=1,2,3
b="ars longa vita brevis"
swap(a, b)
end
Notice that swap only works with variables, not with indexed arrays. For instance, swap(a[i],a[j]) does not work. One would instead write a[(i,j)]=a[(j,i)].
Swift
func swap<T>(inout a: T, inout b: T) {
(a, b) = (b, a)
}
Note: The Swift standard library has already a swap function.
Tcl
proc swap {aName bName} {
upvar 1 $aName a $bName b
lassign [list $a $b] b a
}
proc swap {aName bName} {
upvar 1 $aName a $bName b
foreach {b a} [list $a $b] break
}
alternatively:
proc swap {aName bName} {
upvar 1 $aName a $bName b
set a $b[set b $a; list]
}
set a 1
set b 2
puts "before\ta=$a\tb=$b"
swap a b
puts "after\ta=$a\tb=$b"
- Output:
before a=1 b=2 after a=2 b=1
An idiomatic method:
set a 1
set b 2
puts "before\ta=$a\tb=$b"
set a $b[set b $a;lindex {}]
puts "after\ta=$a\tb=$b"
- Output:
before a=1 b=2 after a=2 b=1
Trith
As with other stack-based languages (e.g. Factor and Joy), the solution to this task is a trivial matter of swapping the top two operands on the stack:
swap
TXR
TXR Lisp has a swap
macro operator. However, an operator just like it can be user-defined (let us call it swp
). Moreover, the user-defined version can be just as robust, ensuring once-only evaluation for both expressions.
Swapping can be achieved with pset
and rotate
also. We won't use these in the following examples.
Naive macro
This allows multiple evaluation of the argument expressions.
(defmacro swp (left right)
(with-gensyms (tmp)
^(let ((,tmp ,left))
(set ,left ,right
,right ,tmp))))
Using placelet
TXR Lisp's placelet
macro allows the programmer to bind a lexically scoped alias for a syntactic place. The place can be accessed and stored through this alias. Yet, the place is evaluated only once. With placelet
it is easy to write many kinds of place-manipulating macros very simply. We can write a robust swap which evaluates the left and right expressions just once:
(defmacro swp (left right)
(with-gensyms (tmp lpl rpl)
^(placelet ((,lpl ,left)
(,rpl ,right))
(let ((,tmp ,lpl))
(set ,lpl ,rpl
,rpl ,tmp)))))
Using place expanders
Finally, the following is closely based on how swap
is actually implemented in TXR Lisp's library. This explicitly uses the general mechanism for handling places, on which placelet
is based also:
(defmacro swp (left right :env env)
(with-gensyms (tmp)
(with-update-expander (l-getter l-setter) left env
(with-update-expander (r-getter r-setter) right env
^(let ((,tmp (,l-getter)))
(,l-setter (,r-getter))
(,r-setter ,tmp))))))
with-update-expander
is a macro which writes code for accessing and updating a place, and makes that code available as local macros. The result is wrapped around the body of code passed to the macro; the body can access these functions, using a backquote to insert the symbols which refer to them. For instance the macro call (,l-getter)
expands to code which accesses the prior value of the left
place, and (,r-setter ,tmp)
stores the value of the temporary variable into the right
place.
UNIX Shell
$ swap() { typeset -n var1=$1 var2=$2; set -- "$var1" "$var2"; var1=$2; var2=$1; }
$ a=1 b=2
$ echo $a $b
1 2
$ swap a b
$ echo $a $b
2 1
$ swap a b
$ echo $a $b
1 2
$ swap() { local var1=$1 var2=$2; set -- "${!var1}" "${!var2}"; declare -g "$var1"="$2" "$var2"="$1"; }
$ a=1 b=2
$ echo $a $b
1 2
$ swap a b
$ echo $a $b
2 1
$ swap a b
$ echo $a $b
1 2
Ursala
Most functions are polymorphic without any special provision to that effect. Swapping a pair is a very inexpensive operation because no actual copying or overwriting is performed.
pmgs("x","y") = ("y","x") # the pattern matching way
ugs = ~&rlX # the idiosyncratic Ursala way
#cast %sWL
test = <pmgs ('a','b'),ugs ('x','y')>
- Output:
<('b','a'),('y','x')>
V
Using the view to shuffle the stack.
[swap [a b : b a] view].
1 2 swap
= 2 1
'hello' 'hi' swap
='hi' 'hello'
Verbexx
// user-defined swap verb -- parms are passed by alias, not value, so they can be updated:
'<==> [_a] @FN [_b] { _a _b = _b _a } by_alias: ;
// test out swap verb
@VAR a = 12345;
@VAR b = "*****";
@SAY "a=" a " b=" b;
\b <==> \a; // "\" verb prevents evaluation of a and b here,
// so they can be passed by alias to <==>
@SAY "a=" a " b=" b;
a b = b a; // swap them back, just using the usual = verb
@SAY "a=" a " b=" b;
−
Visual FoxPro
Since Visual FoxPro is not strongly typed, this will work with any data types.
*!* Swap two variables
LOCAL a, b
a = 1
b = "Hallo"
? a, b
*!* Pass a and b by reference
Swap(@a, @b)
? a, b
PROCEDURE Swap(v1, v2)
LOCAL dum
dum = v1
v1 = v2
v2 = dum
ENDPROC
- Output:
1 Hallo Hallo 1
Wart
There's a primitive for modifying bindings.
(swap! x y)
New bindings can be created in parallel.
let (x y) (list y x)
...
Wren
Wren is dynamically typed and, once a variable has been declared, a value of any type can be assigned to it. Generic programming is not therefore a problem here.
However, it is still not possible to write a generic swap function. This is because all variables are passed to functions or methods by value and prescribing that they should be passed by reference instead is not supported. Moreover, variables of simple types (numbers, bools and nulls) are never boxed and so a function cannot mutate the original variable.
Perhaps the nearest we can get to a generic swap function is to pass the variables in a list (the list's address is then passed by value under the hood), swap the list elements (lists do have a swap method) and then unpack the list to the original variables after the function returns.
Another approach would be to box simple variables (using a user defined class) so that they can be mutated. However, the problem with this is that they usually need to be 'unboxed' when the function returns.
Both approaches are illustrated below.
var swap = Fn.new { |l| l.swap(0, 1) }
var a = 6
var b = 3
var c = [a, b]
swap.call(c) // pass a list instead of individual variables
a = c[0] // unpack
b = c[1] // ditto
System.print("a is now %(a)")
System.print("b is now %(b)")
System.print()
// all user defined classes are reference types
class Box {
construct new(v) { _v = v }
v { _v }
v=(value) { _v = value }
}
// by passing boxed arguments we can mutate them
var boxSwap = Fn.new { |a, b|
var t = a.v
a.v = b.v
b.v = t
}
var d = Box.new(4)
var e = Box.new(8)
boxSwap.call(d, e)
d = d.v // unbox
e = e.v // ditto
System.print("d is now %(d)")
System.print("e is now %(e)")
- Output:
a is now 3 b is now 6 d is now 8 e is now 4
XBS
There is a keyword for swapping variables. Here is an example of 2 ways to swap variables
Swap Keyword
set x=1;
set y=2;
log("Before Swap");
log(x);
log(y);
swap x y;
log("After Swap");
log(x);
log(y);
- Output:
Before Swap 1 2 After Swap 2 1
Swap Function
set x = 1;
set y = 2;
func Swap(a,b){
send[b,a];
}
set z = Swap(x,y);
x=z[0];
y=z[1];
log(x)
log(y);
- Output:
2 1
XPL0
The name Swap is normally used to call an intrinsic routine that swaps bytes in an integer. Thus Exch is used here instead. A and B must both be the same size.
include c:\cxpl\codes;
proc Exch(A, B, S);
char A, B, S;
int I, T;
for I:= 0 to S-1 do
[T:= A(I); A(I):= B(I); B(I):= T];
real X, Y;
[X:= 3.0; Y:= 4.0;
Exch(addr X, addr Y, 8);
RlOut(0, X); RlOut(0, Y); CrLf(0);
]
- Output:
4.00000 3.00000
Yorick
Yorick has a built-in function swap for exchanging the contents of two variables without requiring a temporary copy. Example of use:
> a = 1 > b = "foo" > swap, a, b > a "foo" > b 1
Swapping elements in an array can be accomplished using index lists. Arbitrary permutations of swaps are also straightforward. Example:
> foo = [10,20,30,40,50] > foo([1,2]) = foo([2,1]) > foo [20,10,30,40,50] > foo([3,4,5]) = foo([4,5,3]) > foo [20,10,40,50,30]
Z80 Assembly
Zilog Z80
The Z80 has a few commands for swapping register contents:
EX DE,HL
will swap the contents ofDE
with the contents ofHL
. This is helpful because many instructions are only compatible withHL
.EXX
will swap outBC
,DE
, andHL
with their "shadow registers." To switch back to the standard registers useEXX
again. The accumulator and flags have their own shadow registers, which can be swapped withEX AF,AF'
.EX (SP),HL
will exchange HL with the top two bytes of the stack.- Any two registers that you can
PUSH/POP
can be exchanged by pushing both registers and popping them in the "wrong" order on purpose. For example, to swap theIX
andIY
registers:
push ix
push iy
pop ix ;the value that was once in IY is now in IX
pop iy ;the value that was once in IX is now in IY
Swapping two memory locations takes a bit more work. The Z80 can do an 8-bit swap or a 16-bit swap on memory. There are several ways to do this, but the methods differ slightly depending on which addressing modes you use. Only the accumulator can load/store a single byte directly from/to memory, but the register pairs BC
, DE
, HL
, SP
, IX
, and IY
can all load a 16-bit word directly from memory, or vice versa.
;8-bit swap using the stack.
ld a,(&C000)
push af
ld a,(&D000)
ld (&C000),a ;store the byte at &D000 into &C000
pop af ;now a = the byte at &C000
ld (&D000),a ;now the byte at &D000 equals the byte that was originally at &C000
;16-bit swap:
ld hl,(&C000) ;load the byte at &C000 into L and the byte at &C001 into H.
ld de,(&D000) ;load the byte at &D000 into E and the byte at &D001 into D.
ld (&D000),hl ;store the contents of L into &D000 and H into &D001.
ld (&C000),de ;store the contents of E into &C000 and D into &C001.
Game Boy
The Game Boy is missing all the exchange commands that the Z80 and 8080 both have. There are no shadow registers, EX
, or EXX
, and you cannot load/store 16-bit register pairs to/from immediate memory addresses. The only register that can store directly to memory is the stack pointer (SP
), and it can only store, not load! But not all is lost. EX DE,HL
can be mimicked with the following sequence; although it's much slower than the Zilog's EX DE,HL
, it's as quick as it possibly can be.
push hl
ld h,d
ld L,e ;store de into HL. This is much faster than "push de pop hl."
pop de ;put old HL into DE
Swapping from memory must be done one byte at a time on the Game Boy. The Game Boy exclusive LDI/LDD
commands can help us in this task.
ld hl,&C000
push bc
ldi a,(hl) ;equivalent of "ld a,(hl) inc hl" but is faster than the two separately. Some assemblers call this "ld a,(hl+)"
ld c,a
ld a,(hl) ;we don't need to increment hl this time. There's no wasted time or bytecode if we did however.
ld b,a ;on Zilog Z80 we would have just done "LD BC,(&C000)" but Game Boy can't do that.
; now we do the swap.
ld hl,&D000
ld a,(hl) ;get the byte at &D000
ld (&C000),a ;store it into &C000
ld (hl),c ;store the old byte at &C000 into &D000
inc hl ;inc HL to &D001
ld a,(hl) ;get the byte at &D001
ld (&C001),a ;store it at &C001
ld (hl),b ;store the old byte at &C001 into &D001
pop bc
zkl
As a general case, no. Here a fake around for two known classes (which are the same for ease of example):
class C{var v; fcn init(n){v=n}}
var c1=C(1), c2=C(2);
println(c1.v," : ",c2.v);
fcn swap(ca,cb,name){
tmp:=ca.resove(name);
ca.setVar(name,cb.resolve(name)); cb.setVar(name,tmp)
}
swap(c1,c2,"v");
println(c1.v," : ",c2.v);
- Output:
1 : 2 2 : 1
- Programming Tasks
- Basic language learning
- 11l
- 360 Assembly
- 6502 Assembly
- 68000 Assembly
- 8086 Assembly
- 8th
- ACL2
- Action!
- Action! Tool Kit
- Ada
- Aime
- ALGOL 68
- Amazing Hopper
- AmigaE
- AppleScript
- Arc
- Arturo
- AutoHotkey
- AWK
- Axe
- BASIC
- Applesoft BASIC
- BaCon
- BASIC256
- BBC BASIC
- Chipmunk Basic
- FreeBASIC
- FutureBasic
- Gambas
- GW-BASIC
- IS-BASIC
- Minimal BASIC
- MSX Basic
- OxygenBasic
- PureBasic
- QBasic
- Quite BASIC
- Run BASIC
- ThinBASIC
- TI-89 BASIC
- Tiny BASIC
- True BASIC
- UBasic/4tH
- VBScript
- Visual Basic
- Visual Basic .NET
- XBasic
- Yabasic
- Batch File
- Beads
- Binary Lambda Calculus
- BQN
- Bracmat
- Burlesque
- C
- C sharp
- C++
- Chapel
- Clojure
- CMake
- COBOL
- ColdFusion
- Common Lisp
- Computer/zero Assembly
- Crystal
- D
- Dc
- DCL
- Delphi
- Déjà Vu
- E
- EchoLisp
- Elena
- Elixir
- Emacs Lisp
- EMal
- Erlang
- Euphoria/Omit
- Euphoria
- F Sharp
- Factor
- Falcon
- Fish
- Forth
- Fortran
- Free Pascal
- Frink
- Fōrmulæ
- Gecho
- Go
- Gri
- Groovy
- Harbour
- Haskell
- Icon
- Unicon
- IDL
- J
- Jakt
- Java
- JavaScript
- Joy
- Jq
- Julia
- Kotlin
- Lambdatalk
- Lang
- Lang5
- Langur
- Lasso
- Lhogho
- Lingo
- Lisaac
- LiveCode
- Logo
- Logtalk
- LOLCODE
- Lua
- M2000 Interpreter
- M4
- Maple
- Mathematica
- Wolfram Language
- MATLAB
- Octave
- Maxima
- MAXScript
- Metafont
- Min
- MiniScript
- Modula-3
- Nemerle
- NetRexx
- NewLISP
- Nial
- Nim
- OASYS Assembler
- OCaml
- Oforth
- Oz
- PARI/GP
- Pascal
- PascalABC.NET
- Perl
- Phix
- Phix/basics
- Phixmonti
- PHP
- Picat
- PicoLisp
- Pike
- PL/I
- Plain English
- Pop11
- PostScript
- PowerShell
- Prolog
- Python
- Quackery
- R
- Racket
- Raku
- REBOL
- Retro
- REXX
- Ring
- RLaB
- RPL
- Ruby
- Rust
- Sather
- Scala
- Scheme
- Sed
- Seed7
- SenseTalk
- Sidef
- Slate
- Smalltalk
- SNOBOL4
- Standard ML
- Stata
- Swift
- Tcl
- Trith
- TXR
- UNIX Shell
- Ursala
- V
- Verbexx
- Visual FoxPro
- Wart
- Wren
- XBS
- XPL0
- Yorick
- Z80 Assembly
- Zkl
- Bc/Omit
- XSLT/Omit
- Pages with too many expensive parser function calls