Generic swap: Difference between revisions

12,580 bytes added ,  2 months ago
 
(27 intermediate revisions by 20 users not shown)
Line 21:
 
=={{header|11l}}==
<langsyntaxhighlight lang="11l">F swap(&a, &b)
(a, b) = (b, a)</langsyntaxhighlight>
 
=={{header|360 Assembly}}==
Three consecutive exclusive OR's swap variable contents
<syntaxhighlight lang="360 assembly">
<lang 360 Assembly>
SWAP CSECT , control section start
BAKR 14,0 stack caller's registers
Line 47:
B DS CL8 field B, 8 bytes
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.
Line 53:
===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.
<langsyntaxhighlight lang="6502asm">;swap X with Y
pha ;push accumulator
txa
Line 63:
pla
tay ;pop x into y
pla ;pop accumulator</langsyntaxhighlight>
 
Swapping A with X or Y is easiest with using zero page memory as a temporary store, or with self-modifying code.
 
<langsyntaxhighlight lang="6502asm">
sta temp ;a label representing a zero page memory address
txa
pha ;push x
ldx temp
pla ;pop x into accumulator</langsyntaxhighlight>
 
Swapping memory locations is fairly straightforward on all versions of the 6502:
<langsyntaxhighlight lang="6502asm">
temp equ $00
temp2 equ $01 ;these values don't matter.
Line 87:
sta temp ;pop temp2 into temp
pla
sta temp2 ;pop temp into temp2</langsyntaxhighlight>
 
===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:
<langsyntaxhighlight lang="6502asm">lda #$33
ldx #$44
ldy #$55
Line 101:
pla ;a=#$55
ply ;y=#$44
plx ;x=#$33</langsyntaxhighlight>
 
=={{header|68000 Assembly}}==
 
Two registers can be swapped with <code>EXG</code>:
<langsyntaxhighlight lang="68000devpac">EXG D0,D1 ;swap the contents of D0 and D1
EXG A0,A1 ;swap the contents of A0 and A1</langsyntaxhighlight>
 
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.
<langsyntaxhighlight lang="68000devpac">MOVE.L ($00FF0000),D0
MOVE.L ($00FF1000),D1
MOVE.L D0,($00FF1000)
MOVE.L D1,($00FF0000)</langsyntaxhighlight>
 
The <code>SWAP</code> switches the high and low words of a data register. It can't be used with memory either.
<langsyntaxhighlight lang="68000devpac">MOVE.L #$1234ABCD,D0
SWAP D0 ;now D0 = #$ABCD1234</langsyntaxhighlight>
 
=={{header|8086 Assembly}}==
Line 123:
 
Here are some examples of the <code>XCHG</code> command in action:
<langsyntaxhighlight lang="asm">xchg ax,bx ;exchanges ax with bx
 
xchg ah,al ;swap the high and low bytes of ax
Line 144:
 
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.</langsyntaxhighlight>
 
=={{header|8th}}==
<langsyntaxhighlight lang="forth">
swap
</syntaxhighlight>
</lang>
Or to swap between the stack and a var:
<langsyntaxhighlight lang="forth">
dup @ -rot !
</syntaxhighlight>
</lang>
 
=={{header|ACL2}}==
<langsyntaxhighlight Lisplang="lisp">(defun swap (pair)
(cons (cdr pair)
(car pair)))
 
(let ((p (cons 1 2)))
(cw "Before: ~x0~%After: ~x1~%" p (swap p)))</langsyntaxhighlight>
 
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
<langsyntaxhighlight Actionlang="action!">INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit
 
PROC Swap(BYTE POINTER ptr1,ptr2 INT size)
Line 206:
Swap(@s1,@s2,2)
Print(s1) Put(32) PrintE(s2)
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Generic_swap.png Screenshot from Atari 8-bit computer]
Line 219:
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.
 
<langsyntaxhighlight lang="ada">generic
type Swap_Type is private; -- Generic parameter
procedure Generic_Swap (Left, Right : in out Swap_Type);
Line 228:
Left := Right;
Right := Temp;
end Generic_Swap;</langsyntaxhighlight>
 
===usage===
To use the generic swap procedure, you need to instantiate the procedure for each type that you intend to use.
<langsyntaxhighlight lang="ada">
with Generic_Swap;
...
Line 240:
...
T_Swap (A, B);
</syntaxhighlight>
</lang>
 
=={{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.
<langsyntaxhighlight lang="aime">void
__swap(&, &,,)
{
Line 255:
{
xcall(xcall, __swap);
}</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
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]}}
 
<langsyntaxhighlight lang="algol68">MODE GENMODE = STRING;
 
GENMODE v1:="Francis Gary Powers", v2:="Vilyam Fisher";
Line 278:
v1 =:= v2;
 
print(("v1: ",v1, ", v2: ", v2, new line))</langsyntaxhighlight>
{{out}}
<pre>
Line 289:
 
=={{header|Amazing Hopper}}==
<syntaxhighlight lang="amazing hopper">
<lang Amazing Hopper>
#include <flow.h>
 
Line 302:
PRNL( "SINGLE VAR: ", single var, "\nRANDOM ARRAY: ", random array )
END
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 315:
=={{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.
<langsyntaxhighlight lang="amigae">PROC swap(a,b) IS b,a
 
PROC main()
Line 330:
ForAll({x}, v2, `WriteF('\d ',x)) -> 10 20 30 40
WriteF('\n')
ENDPROC</langsyntaxhighlight>
 
=={{header|AppleScript}}==
AppleScript has built-in support for swapping. This is generic and works for all combinations of data types.
<langsyntaxhighlight AppleScriptlang="applescript">set {x,y} to {y,x}</langsyntaxhighlight>
 
=={{header|Arc}}==
<langsyntaxhighlight Arclang="arc">(mac myswap (a b)
(w/uniq gx
`(let ,gx a
Line 347:
(myswap a b)
(prn "a:" a #\Newline "b:" b))
</syntaxhighlight>
</lang>
 
=={{header|Arturo}}==
{{trans|Ruby}}
===Using multi-assignment===
<langsyntaxhighlight lang="rebol">swap: function [a,b]-> @[b,a]
 
c: 1
Line 359:
 
[c,d]: swap c d
print [c d]</langsyntaxhighlight>
 
{{out}}
Line 368:
===In-place modification===
 
<langsyntaxhighlight lang="rebol">swap: function [a,b].exportable [
tmp: var b
let b var a
Line 379:
 
swap 'c 'd
print [c d]</langsyntaxhighlight>
 
{{out}}
Line 387:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight lang="autohotkey">Swap(ByRef Left, ByRef Right)
{
temp := Left
Left := Right
Right := temp
}</langsyntaxhighlight>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f GENERIC_SWAP.AWK
BEGIN {
Line 421:
return(0)
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 432:
a 1 ng
</pre>
=={{header|Applesoft BASIC}}==
<lang Applesoft BASIC>A=43:B=47:H=A:A=B:B=H:?" A="A" B="B;</lang>
<pre> A=47 B=43</pre>
 
=={{header|Axe}}==
The Exch() command can swap data of any size at any two addresses. This example swaps two 2-byte variables.
<syntaxhighlight lang ="axe">Exch(°A,°B,2)</langsyntaxhighlight>
 
=={{header|Batch FileBASIC}}==
==={{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">
 
<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</lang>
 
 
 
=={{header|BaCon}}==
 
<lang freebasic>
x = 1
y$ = "hello"
Line 472 ⟶ 449:
SWAP x, y$
PRINT y$
</syntaxhighlight>
</lang>
 
==={{header|BASIC256}}===
<langsyntaxhighlight BASIC256lang="basic256">global a, b
a = "one"
b = "two"
Line 486 ⟶ 463:
subroutine swap(a, b)
temp = a : a = b : b = temp
end subroutine</langsyntaxhighlight>
 
==={{header|BBC BASIC}}===
====Built-in function====
<langsyntaxhighlight lang="bbcbasic"> a = 1.23 : b = 4.56
SWAP a,b
PRINT a,b
Line 496 ⟶ 473:
a$ = "Hello " : b$ = "world!"
SWAP a$,b$
PRINT a$,b$</langsyntaxhighlight>
====Custom function====
<langsyntaxhighlight lang="bbcbasic"> a = 1.23 : b = 4.56
PROCswap(^a,^b, 5)
PRINT a,b
Line 512 ⟶ 489:
SWAP a%?i%,b%?i%
NEXT
ENDPROC</langsyntaxhighlight>
{{out}}
<pre>
Line 518 ⟶ 495:
world! Hello
</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}}==
<langsyntaxhighlight lang="beads">beads 1 program 'Generic swap'
 
var
Line 527 ⟶ 853:
 
calc main_init
swap a[4] <=> b[3]</langsyntaxhighlight>
 
{{out}}
Line 537 ⟶ 863:
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 ⌽↩</langsyntaxhighlight>
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}}==
<langsyntaxhighlight lang="bracmat">(!a.!b):(?b.?a)</langsyntaxhighlight>
 
=={{header|Burlesque}}==
 
<langsyntaxhighlight lang="burlesque">
\/
</syntaxhighlight>
</lang>
 
Stack-based swap.
Line 558 ⟶ 888:
This has a restriction that a and b must be the same size.
 
<langsyntaxhighlight lang="c">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;
}</langsyntaxhighlight>
 
{{works with|gcc}}
Line 570 ⟶ 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>.
 
<langsyntaxhighlight lang="c">#define Swap(X,Y) do{ __typeof__ (X) _T = X; X = Y; Y = _T; }while(0)</langsyntaxhighlight>
 
Usage examples are:
 
<langsyntaxhighlight lang="c">#include <stdio.h>
 
#define Swap(X,Y) do{ __typeof__ (X) _T = X; X = Y; Y = _T; }while(0)
Line 605 ⟶ 935:
Swap(pt, th);
printf("%d\n", pt->a);
}</langsyntaxhighlight>
 
This is tested with GCC with <tt>-std=c89</tt> option.
Line 621 ⟶ 951:
are more strongly typed and arguably easier to work with.
 
<langsyntaxhighlight lang="csharp">static void Swap<T>(ref T a, ref T b)
{
T temp = a;
a = b;
b = temp;
}</langsyntaxhighlight>
 
Usage:
 
<langsyntaxhighlight lang="csharp">int a = 1;
int b = 2;
Swap(ref a, ref b); // Type parameter is inferred.</langsyntaxhighlight>
 
===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.
<langsyntaxhighlight lang="csharp">int a = 1;
int b = 2;
(a, b) = (b, a);</langsyntaxhighlight>
 
=={{header|C++}}==
Line 648 ⟶ 978:
The implementation of the swap function template is straightforward:
 
<langsyntaxhighlight lang="cpp">template<typename T> void swap(T& left, T& right)
{
T tmp(left);
left = right;
right = tmp;
}</langsyntaxhighlight>
Note that this function requires that the type T has an accessible copy constructor and assignment operator.
 
Line 659 ⟶ 989:
The standard utility 'swap' can be used to swap two values:
 
<syntaxhighlight lang ="cpp">std::swap(x,y);</langsyntaxhighlight>
 
It will work with any types.
Line 665 ⟶ 995:
===C++11===
C++11 adds move constructors which can be more efficient than copy constructors.
<langsyntaxhighlight lang="cpp">template<class T>
void swap(T &lhs, T &rhs){
T tmp = std::move(lhs);
lhs = std::move(rhs);
rhs = std::move(tmp);
}</langsyntaxhighlight>
 
=={{header|Chapel}}==
Chapel includes a swap operator:
<langsyntaxhighlight lang="chapel">a <=> b</langsyntaxhighlight>
and supports swapping directly via tuples and destructuring:
<langsyntaxhighlight lang="chapel">(a, b) = (b, a)</langsyntaxhighlight>
Both variables must be of the same type.
The [[Fibonacci sequence#Chapel|Fibonnacci implementation]] contains an example.
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="lisp">
(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
</syntaxhighlight>
</lang>
 
The latter two implementations use destructured binding to define local names for the two elements.
Line 692 ⟶ 1,022:
CMake has only one data type: the string.
 
<langsyntaxhighlight lang="cmake">function(swap var1 var2)
set(_SWAP_TEMPORARY "${${var1}}")
set(${var1} "${${var2}}" PARENT_SCOPE)
set(${var2} "${_SWAP_TEMPORARY}" PARENT_SCOPE)
endfunction(swap)</langsyntaxhighlight>
 
<langsyntaxhighlight lang="cmake">set(x 42)
set(y "string")
swap(x y)
message(STATUS ${x}) # -- string
message(STATUS ${y}) # -- 42</langsyntaxhighlight>
 
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: <langsyntaxhighlight lang="cmake">set(x 42)
set(_SWAP_TEMPORARY "string")
swap(x _SWAP_TEMPORARY)
message(STATUS ${x}) # -- 42
message(STATUS ${_SWAP_TEMPORARY}) # -- 42</langsyntaxhighlight> 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": <langsyntaxhighlight lang="cmake">string(TOUPPER CACHE x)
set(y "string")
swap(x y) # CMake Error... set given invalid arguments for CACHE mode.</langsyntaxhighlight> swap() can never set a variable to "CACHE" or "PARENT_SCOPE", because these are keywords of set() command.
 
=={{header|COBOL}}==
<syntaxhighlight lang="cobol">
<lang COBOL>
PROGRAM-ID. SWAP-DEMO.
AUTHOR. Bill Gunshannon.
Line 791 ⟶ 1,121:
 
END PROGRAM SWAP.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 822 ⟶ 1,152:
This is another standard swap.
 
<langsyntaxhighlight lang="cfm"><cfset temp = a />
<cfset a = b />
<cfset b = temp /></langsyntaxhighlight>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(rotatef a b)
 
(psetq a b b a)</langsyntaxhighlight>
 
=={{header|Computer/zero Assembly}}==
<langsyntaxhighlight lang="6502asm">LDA 29
STA 31
LDA 30
Line 843 ⟶ 1,173:
byte $0F
byte $E0
byte $00</langsyntaxhighlight>
 
 
Line 855 ⟶ 1,185:
Crystal directly supports swapping:
 
<langsyntaxhighlight lang="ruby">a, b = b, a</langsyntaxhighlight>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.algorithm: swap; // from Phobos standard library
 
// The D solution uses templates and it's similar to the C++ one:
Line 881 ⟶ 1,211:
mySwap(a[0], a[1]);
writeln(a);
}</langsyntaxhighlight>
{{out}}
<pre>[10, 20]
Line 889 ⟶ 1,219:
=={{header|dc}}==
We use two registers to swap in POSIX dc.
<langsyntaxhighlight lang="dc">1 2 SaSbLaLb f
=2 1</langsyntaxhighlight>
Reverse (r) is a built-in stack command available as a GNU extension for dc.
<langsyntaxhighlight lang="dc">1 2 r f
=2 1</langsyntaxhighlight>
 
=={{header|DCL}}==
symbols do not have to be declared, they can be integers or strings, they can change type on the fly
<langsyntaxhighlight DCLlang="dcl">$ a1 = 123
$ a2 = "hello"
$ show symbol a*
Line 908 ⟶ 1,238:
$ a1 = a2
$ a2 = t
$ return</langsyntaxhighlight>
{{out}}
<pre>$ @generic_swap
Line 918 ⟶ 1,248:
=={{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.
<syntaxhighlight lang="delphi">
<lang Delphi>
procedure Swap_T(var a, b: T);
var
Line 927 ⟶ 1,257:
b := temp;
end;
</syntaxhighlight>
</lang>
 
Generics were introduced with Delphi 2009
<syntaxhighlight lang="delphi">
<lang Delphi>
program GenericSwap;
 
Line 957 ⟶ 1,287:
writeln('After swap: a=', a, ' b=', b);
end.
</syntaxhighlight>
</lang>
 
=={{header|Déjà Vu}}==
To swap the two top-most items on the stack:
<syntaxhighlight lang ="dejavu">swap</langsyntaxhighlight>
To swap two variables without needing a third name, using the stack for temporary storage:
<langsyntaxhighlight lang="dejavu">set :a set :b @a @b</langsyntaxhighlight>
 
=={{header|E}}==
(slots)
 
<langsyntaxhighlight lang="e">def swap(&left, &right) {
def t := left
left := right
right := t
}</langsyntaxhighlight>
 
(functional)
 
<langsyntaxhighlight lang="e">def swap([left, right]) {
return [right, left]
}</langsyntaxhighlight>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="lisp">
;; 1)
;; a macro will do it, as shown in Racket (same syntax)
Line 1,002 ⟶ 1,332:
(list-swap! L 1 ' 🎩 )
→ (🎩 2 3 4 1)
</syntaxhighlight>
</lang>
 
=={{header|Elena}}==
ELENA 4.1 :
<langsyntaxhighlight lang="elena">import extensions;
swap(ref object v1, ref object v2)
Line 1,026 ⟶ 1,356:
console.printLine(n," ",s)
}</langsyntaxhighlight>
<pre>
2 abc
Line 1,034 ⟶ 1,364:
=={{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>).
<syntaxhighlight lang="elixir">
<lang Elixir>
x = 4
y = 5
Line 1,045 ⟶ 1,375:
x # => 4
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:
 
<syntaxhighlight lang="elixir">
<lang Elixir>
swap = fn x,y -> [y|x] end
[x|y] = swap.(1,2)
x # => 2
y # => 1
</syntaxhighlight>
</lang>
 
Variables can be bound and rebound regardless of type
<syntaxhighlight lang="elixir">
<lang Elixir>
swap_tuple = fn {x,y} -> {y,x} end
{a,b} = swap_tuple.({1,:ok})
Line 1,066 ⟶ 1,396:
a # => "2"
b # => 1
</syntaxhighlight>
</lang>
 
=={{header|Emacs Lisp}}==
<langsyntaxhighlight Lisplang="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)</langsyntaxhighlight>
 
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.
 
<langsyntaxhighlight Lisplang="lisp">(defmacro swap (a b)
`(setq ,b (prog1 ,a (setq ,a ,b))))</langsyntaxhighlight>
 
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]]).
 
<langsyntaxhighlight Lisplang="lisp">(require 'cl-lib)
(defmacro swap (a b)
`(cl-psetf ,a ,b
Line 1,090 ⟶ 1,420:
(setq lst (list 123 456))
(swap (car lst) (cadr lst))
;; now lst is '(456 123)</langsyntaxhighlight>
 
=={{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}}==
Line 1,098 ⟶ 1,445:
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].
[a,2]
2> lists:reverse(L).
[2,a]
</syntaxhighlight>
</lang>
 
Or swap the items in a tuple (also shown in the shell).
 
<syntaxhighlight lang="erlang">
<lang Erlang>
1> T = {2,a}.
{2,a}
2> list_to_tuple(lists:reverse(tuple_to_list(T))).
{a,2}
</syntaxhighlight>
</lang>
 
{{omit from|Euphoria}}
 
=={{header|Euphoria}}==
<syntaxhighlight lang="euphoria">
<lang Euphoria>
include std/console.e -- for display
 
Line 1,127 ⟶ 1,474:
display("x is now []",{x})
display("y is now []",{y})
</syntaxhighlight>
</lang>
 
<pre>
Line 1,143 ⟶ 1,490:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">let swap (a,b) = (b,a)</langsyntaxhighlight>
 
=={{header|Factor}}==
Depending on how you look at it: this task doesn't apply, or it's trivial:
<syntaxhighlight lang ="factor">swap</langsyntaxhighlight>
 
=={{header|Falcon}}==
<langsyntaxhighlight lang="falcon">
a = 1
b = 2
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
 
=={{header|Fish}}==
Swap the top two values on the stack:
<syntaxhighlight lang ="fish">$</langsyntaxhighlight>
 
=={{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</langsyntaxhighlight>
 
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<langsyntaxhighlight lang="fortran">MODULE Genericswap
IMPLICIT NONE
 
Line 1,210 ⟶ 1,557:
WRITE(*,*) r1, r2 ! Prints 2.0 and 1.0
WRITE(*,*) s1, s2 ! Prints xyz and abc
END PROGRAM EXAMPLE</langsyntaxhighlight>
 
=={{header|Free Pascal}}==
<langsyntaxhighlight lang="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 }
Line 1,231 ⟶ 1,578:
swap<string>(a,b);
writeln(a:6,b:6);
end.</langsyntaxhighlight>
<pre>
Output:
Test me
me Test</pre>
 
=={{header|FreeBASIC}}==
FreeBASIC already has a built-in generic Swap procedure but a macro can be used to build another one:
<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</lang>
 
{{out}}
<pre>
2 1
World Hello
</pre>
 
=={{header|Frink}}==
The following example will work on all Frink data types:
 
<langsyntaxhighlight lang="frink">
[b,a] = [a,b]
</syntaxhighlight>
</lang>
 
=={{header|FutureBasicFōrmulæ}}==
<lang futurebasic>window 1, @"Generic Swap", (0,0,480,270)
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Generic_swap}}
text ,,,,, 60
 
'''Solution'''
dim as long i, j
dim as double x, y
dim as CFStringRef a, b
 
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).
i = 1059 : j = 62
print i, j
swap i, j
print i, j
 
This can be used to do a generic swap as follows:
print
 
[[File:Fōrmulæ - Generic swap 01.png]]
x = 1.23 : y = 4.56
print x, y
swap x, y
print x, y
 
'''Test case'''
print
 
[[File:Fōrmulæ - Generic swap 02.png]]
a = @"Hello" : b = @"World!"
print a, b
swap a, b
print a, b
 
[[File:Fōrmulæ - Generic swap 03.png]]
HandleEvents</lang>
 
Output:
<pre>
1059 62
62 1059
 
1.23 4.56
4.56 1.23
 
Hello World!
World! Hello
</pre>
 
=={{header|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 &mdash;i.e. XML, JSON&mdash; they are intended for storage and transfer purposes more than visualization and edition.
 
Programs in Fōrmulæ are created/edited online in its [https://formulae.org website], However they run on execution servers. By default remote servers are used, but they are limited in memory and processing power, since they are intended for demonstration and casual use. A local server can be downloaded and installed, it has no limitations (it runs in your own computer). Because of that, example programs can be fully visualized and edited, but some of them will not run if they require a moderate or heavy computation/memory resources, and no local server is being used.
 
In '''[https://formulae.org/?example=Generic_swap this]''' page you can see the program(s) related to this task and their results.
 
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=b746e857f6f280fb92c204795f6053be Click this link to run this code]'''
<lang gambas>Public Sub Main()
Dim vA As Variant = " World"
Dim vB As Variant = 1
 
Swap vA, vB
 
Print vA; vB
 
End</lang>
Output:
<pre>
1 World
</pre>
 
=={{header|Gecho}}==
<langsyntaxhighlight lang="gecho">
1 !0 2 !1
</syntaxhighlight>
</lang>
Now tape[0] and tape[1] are set to 1 and 2, respectively.
<langsyntaxhighlight lang="gecho">
&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.
 
Line 1,358 ⟶ 1,622:
===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.
<langsyntaxhighlight lang="go">a, b = b, a</langsyntaxhighlight>
===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.
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,374 ⟶ 1,638:
swap(&a, &b)
fmt.Println(a, b)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,383 ⟶ 1,647:
===Pass pointers===
Somewhat less restrictive, this version allows pointers of any type to be passed, as long as they are the same type.
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,433 ⟶ 1,697:
swap(&g, &h)
fmt.Println("g h:", g, h)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,452 ⟶ 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,
 
<langsyntaxhighlight Grilang="gri">`Swap Vars &.a. &.b.'
{
new .temp.
Line 1,466 ⟶ 1,730:
 
show .foo. " " .bar.
# prints "456 123"</langsyntaxhighlight>
 
Or similar to swap synonyms (strings),
 
<langsyntaxhighlight Grilang="gri">`Swap Syns &\a &\b'
{
new \temp
Line 1,484 ⟶ 1,748:
 
show "\quux \xyzzy"
# prints "two one"</langsyntaxhighlight>
 
=={{header|Groovy}}==
Line 1,490 ⟶ 1,754:
Groovy has support for swapping built in:
 
<langsyntaxhighlight lang="groovy">(a, b) = [b, a]</langsyntaxhighlight>
 
But the task calls for a "generic swap method" to be written, so here it is:
 
<langsyntaxhighlight lang="groovy">def swap(a, b) {
[b, a]
}</langsyntaxhighlight>
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:
<langsyntaxhighlight lang="groovy">def (x, y) = swap(1, 3)
assert x == 3
assert y == 1</langsyntaxhighlight>
 
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:
<langsyntaxhighlight lang="groovy">def listSwap = { a, i, j ->
assert (0..<(a.size())).containsAll([i,j]);
a[[j,i]] = a[[i,j]]
Line 1,510 ⟶ 1,774:
def list = [2,4,6,8]
listSwap(list, 1, 3)
assert list == [2,8,6,4]</langsyntaxhighlight>
 
=={{header|Harbour}}==
Line 1,516 ⟶ 1,780:
 
Implementation: (We exploit "pass by reference" method on the parameters used)
<langsyntaxhighlight lang="visualfoxpro">PROCEDURE Swap( /*@*/v1, /*@*/v2 )
LOCAL xTmp
xTmp := v1
Line 1,522 ⟶ 1,786:
v2 := xTmp
RETURN
</syntaxhighlight>
</lang>
Sample code:
<langsyntaxhighlight lang="visualfoxpro"> FUNCTION Main()
LOCAL v1 := "World!", v2 := "Hello"
? v1, v2 // --> World! Hello
Line 1,530 ⟶ 1,794:
? v1, v2 // --> Hello World!
RETURN 0
</syntaxhighlight>
</lang>
 
=={{header|Haskell}}==
Line 1,538 ⟶ 1,802:
The type signature, the first line, is optional; it may be inferred.
 
<langsyntaxhighlight lang="haskell">swap :: (a, b) -> (b, a)
swap (x, y) = (y, x)</langsyntaxhighlight>
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.
<langsyntaxhighlight lang="haskell">import Control.Monad.Ref
swap :: MonadRef r m => r a -> r a -> m ()
swap xRef yRef = do
Line 1,550 ⟶ 1,814:
y<-readRef yRef
writeRef xRef y
writeRef yRef x</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
Icon provides a :=: operator for this. Additionally, there is a reversible exchange operator <-> that reverses the exchange if resumed.
<langsyntaxhighlight lang="icon">procedure main()
x := 1
y := 2
Line 1,562 ⟶ 1,826:
if x <-> y & x < y then write(x, " ", y)
end
</syntaxhighlight>
</lang>
 
=={{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.
 
<langsyntaxhighlight IDLlang="idl">pro swap, a, b
c = temporary(a)
a = temporary(b)
b = temporary(c)
end</langsyntaxhighlight>
 
=={{header|IS-BASIC}}==
<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</lang>
 
=={{header|J}}==
Line 1,587 ⟶ 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):
 
<langsyntaxhighlight Jlang="j"> (<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.</langsyntaxhighlight>
 
Also, if the argument list can be guaranteed to be a pair, J's reverse primitive will swap the pair.
 
<langsyntaxhighlight Jlang="j"> |.2 3
3 2
|.&.;:'one two'
two one</langsyntaxhighlight>
 
A generic destructive swap of named values would instead require reference to the locations being destroyed. Here's an implementation of that:
 
<langsyntaxhighlight Jlang="j">destructiveSwap=: {{ EMPTY[ (m;n)=: n ,&<&do m }}</langsyntaxhighlight>
 
Example use:
 
<langsyntaxhighlight Jlang="j"> V1=: 'cat'
V2=: 7
'V1' destructiveSwap 'V2'
Line 1,611 ⟶ 1,866:
7
V2
cat</langsyntaxhighlight>
 
=={{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}}==
Line 1,618 ⟶ 1,898:
Java uses references, so it can't swap the values of two variables that don't belong to a class.
 
<langsyntaxhighlight lang="java">class Pair<T> {
T first;
T second;
Line 1,626 ⟶ 1,906:
p.first = p.second;
p.second = temp;
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
Line 1,635 ⟶ 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.
 
<langsyntaxhighlight lang="javascript">function swap(arr) {
var tmp = arr[0];
arr[0] = arr[1];
arr[1] = tmp;
}</langsyntaxhighlight>
 
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.
<langsyntaxhighlight lang="javascript">function swap(aName, bName) {
eval('(function(){ arguments[0] = aName; aName = bName; bName = arguments[0] })()'
.replace(/aName/g, aName)
Line 1,651 ⟶ 1,931:
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)
<langsyntaxhighlight lang="javascript">function swap(a, b) {
var tmp = window[a];
window[a] = window[b];
Line 1,662 ⟶ 1,942:
var y = 2;
swap('x', 'y');
</syntaxhighlight>
</lang>
 
Another solution for swapping array items using destructing assignment:
<langsyntaxhighlight lang="javascript">const arr = [1, 2, 3, 4, 5];
[arr[0], arr[1]] = [arr[1], arr[0]]
</syntaxhighlight>
</lang>
 
=={{header|Joy}}==
Provided that the stack contains at least two elements and/or aggregates:
<syntaxhighlight lang ="joy">swap</langsyntaxhighlight>
changes the order of those elements and/or aggregates.
 
=={{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:<langsyntaxhighlight lang="jq">jq -n '1 as $a | 2 as $b | $a as $tmp | $b as $a | $tmp as $b | [$a,$b]'</langsyntaxhighlight>
 
Here is a filter that will swap the elements of a two-element array:
<syntaxhighlight lang ="jq">reverse</langsyntaxhighlight>
 
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:
<langsyntaxhighlight lang="jq">def swap(i;j): .[i] as $t | .[i] = .[j] | .[j] = $t;</langsyntaxhighlight>
 
=={{header|Julia}}==
Similar to Python, Julia has built-in support for swapping:
 
<langsyntaxhighlight lang="julia">a, b = b, a</langsyntaxhighlight>
 
=={{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">
<lang scala>// version 1.1
 
fun <T> swap(t1: T, t2: T) = Pair(t2, t1)
 
fun main(args: Array<String>) {
var a = 3
var b = 4
Line 1,709 ⟶ 1,988:
println("d = $d")
println("e = $e")
}</langsyntaxhighlight>
 
{{out}}
Line 1,718 ⟶ 1,997:
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}}==
<langsyntaxhighlight lang="scheme">
 
1) using an Immediately Invoked Function Expression:
Line 1,739 ⟶ 2,038:
{swap {cons hello brave} {cons new world}}
-> (new world) (hello brave)
</syntaxhighlight>
</lang>
 
=={{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}}==
<langsyntaxhighlight Lang5lang="lang5">swap # stack
reverse # array</langsyntaxhighlight>
 
=={{header|langur}}==
Langur does not have an option for using references (so far). The following is not directly applicable to the task, but valuesValues can be swapped using multi-variable assignment, including indexed values (for mutable variables).
 
<syntaxhighlight lang="langur">var .abc = [1, 2, 3]
{{works with|langur|0.10}}
<lang langur>var .abc = [1, 2, 3]
var .def = [5, 6, 7]
 
Line 1,755 ⟶ 2,078:
 
writeln .abc
writeln .def</langsyntaxhighlight>
 
Prior to 0.10, you would use parentheses as follows.
 
<lang langur>(.abc[3], .def[3]) = (.def[3], .abc[3])</lang>
 
{{out}}
Line 1,766 ⟶ 2,085:
 
=={{header|Lasso}}==
<langsyntaxhighlight lang="lasso">define swap(a, b) => (: #b, #a)
 
local(a) = 'foo'
Line 1,773 ⟶ 2,092:
local(a,b) = swap(#a, #b)
stdoutnl(#a)
stdoutnl(#b)</langsyntaxhighlight>
 
{{out}}
Line 1,781 ⟶ 2,100:
===Using Decompositional Assignment===
 
<langsyntaxhighlight lang="lasso">local(a) = 'hair'
local(b) = 'moose'
local(a,b) = (: #b, #a)
stdoutnl(#a)
stdoutnl(#b)</langsyntaxhighlight>
 
{{out}}
Line 1,794 ⟶ 2,113:
Lhogho is very similar except that it does not have a localmake opcode.
 
<langsyntaxhighlight lang="logo">
to swap :s1 :s2
local "t
Line 1,806 ⟶ 2,125:
swap "a "b ; pass the names of the variables to swap
show list :a :b ; [dog 4]
</syntaxhighlight>
</lang>
 
=={{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:
<langsyntaxhighlight lang="lingo">on swap (x, y)
return "tmp="&x&RETURN&x&"="&y&RETURN&y&"=tmp"
end</langsyntaxhighlight>
Usage:
<langsyntaxhighlight lang="lingo">x = 1
y = 2
do(swap("x","y"))
put x, y
-- 2 1</langsyntaxhighlight>
 
=={{header|Lisaac}}==
<langsyntaxhighlight Lisaaclang="lisaac">(a, b) := (b, a);</langsyntaxhighlight>
 
=={{header|LiveCode}}==
<langsyntaxhighlight LiveCodelang="livecode">put "first" into a1
put "last" into b2
swap a1,b2
Line 1,833 ⟶ 2,152:
put p1 into p2
put p3 into p1
end swap</langsyntaxhighlight>
 
=={{header|Logo}}==
<langsyntaxhighlight lang="logo">
to swap :s1 :s2
localmake "t thing :s1
Line 1,847 ⟶ 2,166:
swap "a "b ; pass the names of the variables to swap
show list :a :b ; [dog 4]
</syntaxhighlight>
</lang>
 
=={{header|Logtalk}}==
<langsyntaxhighlight lang="logtalk">:- object(paws).
 
:- public(swap/4).
swap(First, Second, Second, First).
 
:- end_object.</langsyntaxhighlight>
Usage examples:
<langsyntaxhighlight lang="logtalk">| ?- paws::swap(apples, oranges, X, Y).
X = oranges
Y = apples
Line 1,864 ⟶ 2,183:
| ?- paws::swap(3.14, ext(lgt), X, Y).
X = ext(lgt)
Y = 3.14</langsyntaxhighlight>
yes
 
Line 1,870 ⟶ 2,189:
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.
 
<langsyntaxhighlight LOLCODElang="lolcode">HAI 1.3
 
I HAS A foo ITZ "kittehz"
Line 1,880 ⟶ 2,199:
VISIBLE bar BTW, kittehz
 
KTHXBYE</langsyntaxhighlight>
 
=={{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:
<langsyntaxhighlight lang="lua">
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
</syntaxhighlight>
</lang>
 
Usage example:
<langsyntaxhighlight lang="lua">
x, y = 3, 4
print(x, y) --> 3 4
x, y = y, x -- swap
print(x, y) --> 4 3
</syntaxhighlight>
</lang>
 
=={{header|M2000 Interpreter}}==
Line 1,902 ⟶ 2,221:
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">
<lang M2000 Interpreter>
\\ pgrammingprogramming again Swap (for local use)
Module Swap (&a, &b) {
\\ this call internal command - by default is by reference without using character &
Line 1,916 ⟶ 2,235:
Swap &A$, &B$
Print A$="B$", B$="A$"
</syntaxhighlight>
</lang>
 
Using Swap (internal command), for variables, groups (only for variables inside groups), pointers to groups, pointers to containers, etc.
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
a=1000
b=50
Line 2,015 ⟶ 2,334:
Print A()
Print B()
</syntaxhighlight>
</lang>
 
=={{header|M4}}==
<langsyntaxhighlight lang="m4">define(`def2', `define(`$1',`$2')define(`$3',`$4')')dnl
define(`swap', `def2(`$1',defn(`$2'),`$2',defn(`$1'))')dnl
dnl
Line 2,025 ⟶ 2,344:
a b
swap(`a',`b')
a b</langsyntaxhighlight>
 
{{out}}
Line 2,036 ⟶ 2,355:
=={{header|Maple}}==
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;
Line 2,050 ⟶ 2,369:
> b;
2
</syntaxhighlight>
</lang>
 
=={{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.
<langsyntaxhighlight lang="mathematica">swap[a_, b_] := {a, b} = {b, a}
SetAttributes[swap, HoldAll]</langsyntaxhighlight>
 
=={{header|MATLAB}} / {{header|Octave}}==
Line 2,062 ⟶ 2,381:
 
Example:
<langsyntaxhighlight MATLABlang="matlab">>> a = [30 40 50 60 70]
 
a =
Line 2,078 ⟶ 2,397:
a =
 
40 30 60 50 70</langsyntaxhighlight>
 
 
A generic swap (compatible with any variable type) can be performed with the ''deal'' command:
 
<syntaxhighlight lang="matlab">
<lang MATLAB>
>> a = 12
a = 12
Line 2,093 ⟶ 2,412:
b = 12
a = foo
</syntaxhighlight>
</lang>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">a: 10$
b: foo$
 
Line 2,111 ⟶ 2,430:
 
a; /* 10 */
b; /* foo */</langsyntaxhighlight>
 
=={{header|MAXScript}}==
<syntaxhighlight lang ="maxscript">swap a b</langsyntaxhighlight>
 
=={{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)
 
<langsyntaxhighlight lang="metafont">vardef swap(suffix a, b) =
save ?; string s_;
if boolean a: boolean ?
Line 2,130 ⟶ 2,449:
elseif transform a: transform ? fi;
? := a; a := b; b := ?
enddef;</langsyntaxhighlight>
 
''Examples'':
 
<langsyntaxhighlight lang="metafont">j := 10;
i := 5;
show j, i;
Line 2,145 ⟶ 2,464:
show truth1, truth2;
swap(truth1,truth2);
show truth1, truth2;</langsyntaxhighlight>
 
=={{header|min}}==
{{works with|min|0.19.3}}
Like many other stack languages, this is trivial.
<syntaxhighlight lang ="min">swap</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight MiniScriptlang="miniscript">swap = function(map, a, b)
temp = map[a]
map[a] = map[b]
Line 2,164 ⟶ 2,483:
print "BEFORE: x=" + x + ", y=" + y
swap(locals, "x", "y")
print "AFTER: x=" + x + ", y=" + y</langsyntaxhighlight>
{{out}}
<pre>BEFORE: x=1, y=2
AFTER: x=2, y=1</pre>
 
=={{header|Modula-3}}==
<langsyntaxhighlight lang="modula3">GENERIC INTERFACE GenericSwap(Elem);
 
PROCEDURE Swap(VAR left: Elem.T; VAR right: Elem.T);
 
END GenericSwap.</langsyntaxhighlight>
<langsyntaxhighlight lang="modula3">GENERIC MODULE GenericSwap(Elem);
 
PROCEDURE Swap(VAR left: Elem.T; VAR right: Elem.T) =
Line 2,185 ⟶ 2,504:
 
BEGIN
END GenericSwap.</langsyntaxhighlight>
 
Here is an example usage for integers:
<langsyntaxhighlight lang="modula3">INTERFACE IntSwap = GenericSwap(Integer) END IntSwap.</langsyntaxhighlight>
<langsyntaxhighlight lang="modula3">MODULE IntSwap = GenericSwap(Integer) END IntSwap.</langsyntaxhighlight>
<langsyntaxhighlight lang="modula3">MODULE Main;
 
IMPORT IntSwap, IO, Fmt;
Line 2,201 ⟶ 2,520:
IntSwap.Swap(left, right);
IO.Put("Left = " & Fmt.Int(left) & "\n");
END Main.</langsyntaxhighlight>
 
{{out}}
Line 2,211 ⟶ 2,530:
=={{header|Nemerle}}==
For pairs, namespace Nemerle.Utility.Pair contains Swap():
<langsyntaxhighlight Nemerlelang="nemerle">def coords = (1, -1);
def invcoords = Swap(coords);</langsyntaxhighlight>
Or to swap two mutable variables of the same type:<syntaxhighlight lang Nemerle="nemerle">a <-> b;</langsyntaxhighlight>
But, enough about built in functionality, let's demonstrate using generics:
<langsyntaxhighlight Nemerlelang="nemerle">Swap[T, U] (a : T, b : U) : U * T
{
(b, a)
}</langsyntaxhighlight>
 
=={{header|NetRexx}}==
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.
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 2,244 ⟶ 2,563:
 
return
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,255 ⟶ 2,574:
 
=={{header|NewLISP}}==
<syntaxhighlight lang NewLISP="newlisp">(swap a b)</langsyntaxhighlight>
 
=={{header|Nial}}==
Like J
<langsyntaxhighlight lang="nial">|reverse 1 2
=2 1</langsyntaxhighlight>
 
=={{header|Nim}}==
Builtin procedure <code>swap</code>. Example usage:
<syntaxhighlight lang ="nim">swap(a, b)</langsyntaxhighlight>
 
=={{header|OASYS Assembler}}==
You can swap variable <tt>%A#</tt> with <tt>%B#</tt> by writing:
<langsyntaxhighlight lang="oasys_oaa">%A#%B#<%B#%A#<>></langsyntaxhighlight>
A method which can be called to implement it can be written like:
<langsyntaxhighlight lang="oasys_oaa">[&SW,A^,B^],A^<,B^<<,B^<,A^<<>></langsyntaxhighlight>
To call such method:
<syntaxhighlight lang ="oasys_oaa">+%A#%B#&SW</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight lang="ocaml">let swap (x, y) = (y, x)</langsyntaxhighlight>
If the arguments are constrained to be reference values, a swap function is simple:
<langsyntaxhighlight lang="ocaml">let swapref x y =
let temp = !x in
x := !y;
y := temp</langsyntaxhighlight>
 
=={{header|Oforth}}==
 
<syntaxhighlight lang Oforth="oforth">swap</langsyntaxhighlight>
 
=={{header|OxygenBasic}}==
 
<lang>
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
</lang>
 
=={{header|Oz}}==
Line 2,312 ⟶ 2,610:
 
We can write a swap procedure for cells, though. Cells are mutable references.
<langsyntaxhighlight lang="oz"> proc {SwapCells A B}
Tmp = @A
in
A := @B
B := Tmp
end</langsyntaxhighlight>
 
Or shorter, if we exploit the fact that the assignment operator <code>:=</code> returns the old value of the cells:
<langsyntaxhighlight lang="oz"> proc {SwapCells A B}
B := A := @B
end</langsyntaxhighlight>
 
A functional swap, operating on pairs:
<langsyntaxhighlight lang="oz"> fun {SwapPair A#B}
B#A
end</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
Pari is near-typeless&mdash;everything is a GEN.
<langsyntaxhighlight lang="parigp">my(tmp=a);
a=b;
b=tmp;</langsyntaxhighlight>
 
{{works with|PARI/GP|2.6.0 and above}}
 
<langsyntaxhighlight lang="parigp">[a,b]=[b,a]</langsyntaxhighlight>
 
=={{header|Pascal}}==
{{works with|Free_Pascal|2.6.0}}
Standard Pascal does not have generics, but FreePascal has a start:
<langsyntaxhighlight lang="pascal">program generictest;
 
{$mode objfpc}
Line 2,369 ⟶ 2,667:
SwapInt(S, T);
writeln(S, T:2);
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 2,376 ⟶ 2,674:
</pre>
'''since FreePascal version 3.2.0:'''
<langsyntaxhighlight lang="pascal">program generic_test;
{$mode objfpc}{H+}
uses
Line 2,398 ⟶ 2,696:
specialize GSwap<Integer>(I, J);
WriteLn('I = ', I, ', J = ', J);
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 2,408 ⟶ 2,706:
Perl has support for swapping built-in
 
<langsyntaxhighlight lang="perl">($y, $x) = ($x, $y);</langsyntaxhighlight>
 
Here's a generic swap routine:
 
<langsyntaxhighlight lang="perl">sub swap {@_[0, 1] = @_[1, 0]}</langsyntaxhighlight>
 
=={{header|Phix}}==
{{libheader|Phix/basics}}
The following applies to any types. Subscripting and nesting may also be used freely on either side.
<!--<langsyntaxhighlight Phixlang="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>
<!--</langsyntaxhighlight>-->
 
=={{header|Phixmonti}}==
Applies to any types.
<syntaxhighlight lang Phixmonti="phixmonti">a b var a var b</langsyntaxhighlight>
 
=={{header|PHP}}==
 
<langsyntaxhighlight lang="php">function swap(&$a, &$b) {
list($a, $b) = array($b, $a);
}</langsyntaxhighlight>
 
=={{header|Picat}}==
Picat supports re-assignment (<code>:=</code>), but it is not possible to swap two variables like this:
<langsyntaxhighlight Picatlang="picat">A = 1,
B = 2,
[A,B] := [B,A],
% ...</langsyntaxhighlight>
 
(This throws an error: "invalid left-hand side of assignment").
 
The following works, but it's probably not general enough for this task:
<langsyntaxhighlight Picatlang="picat">A = 1,
B = 2,
T = A, % Assuming that T is not used elsewhere in the clause
A := B,
B := T,
% ...</langsyntaxhighlight>
 
Instead swaps has to be done by some other means.
Line 2,453 ⟶ 2,751:
One way is to place the values in a list (or array) and use inline swapping of the list.
 
<langsyntaxhighlight Picatlang="picat">% Swapping positions in a list/array
swap2(L) =>
swap_list(L,1,2).
Line 2,461 ⟶ 2,759:
T = L[I],
L[I] := L[J],
L[J] := T.</langsyntaxhighlight>
 
Usage:
<langsyntaxhighlight Picatlang="picat">L = [1,2],
swap2(L),
% ...</langsyntaxhighlight>
 
L is now [2,1]
 
Note: Placing the variables A, B in swap2
<syntaxhighlight lang Picat="picat">swap2([A,B])</langsyntaxhighlight>
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:
<langsyntaxhighlight Picatlang="picat">swap_pair([A,B],[B,A]).</langsyntaxhighlight>
 
Usage:
<langsyntaxhighlight Picatlang="picat">A = 1,
B = 2,
swap_pair([A,B],X),
% ...</langsyntaxhighlight>
 
X is now [2,1]. A is still 1 and B is still 2.
Line 2,489 ⟶ 2,787:
=={{header|PicoLisp}}==
[http://software-lab.de/doc/refX.html#xchg xchg] works with any data type
<langsyntaxhighlight PicoLisplang="picolisp">(let (A 1 B 2)
(xchg 'A 'B)
(println A B) )
Line 2,495 ⟶ 2,793:
(let (Lst1 '(a b c) Lst2 '(d e f))
(xchg (cdr Lst1) (cdr Lst2))
(println Lst1 Lst2) )</langsyntaxhighlight>
{{out}}
<pre>2 1
(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}}==
 
==== Using the preprocessor ====
<langsyntaxhighlight lang="pli">
%swap: procedure (a, b);
declare (a, b) character;
return ( 't=' || a || ';' || a || '=' || b || ';' || b '=t;' );
%end swap;
%activate swap;</langsyntaxhighlight>
 
The statement:-
Line 2,517 ⟶ 2,856:
 
==== Using generic procedures ====
<langsyntaxhighlight lang="pli">declare swap generic (
swapf when (float, float),
swapc when (char, char));
Line 2,532 ⟶ 2,871:
 
declare (r, s) character (5);
call swap (r, s);</langsyntaxhighlight>
 
Both of the above are not completely generic, but depend on either the presence of
Line 2,541 ⟶ 2,880:
 
==== Completely generic code using the pre-processor ====
<langsyntaxhighlight lang="pli">%swap: proc(x,y);
dcl (x, y) char;
 
Line 2,576 ⟶ 2,915:
f1 = -656877352; /* '5a5a5a5a'x, aka 'QQQQ' */
swapper(c1, f1);
put data(c1,f1);</langsyntaxhighlight>
 
The code generated by 'swap(c1, c2);' looks like
 
<langsyntaxhighlight lang="pli">
begin;
dcl c char (1);
Line 2,595 ⟶ 2,934:
py = py + 1;
end;
end;</langsyntaxhighlight>
 
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 2,615 ⟶ 2,954:
 
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:
<langsyntaxhighlight lang="pli">
%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;</langsyntaxhighlight>
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):
<langsyntaxhighlight lang="pli">
Begin;
declare t like this;
Line 2,629 ⟶ 2,968:
this = that;
that = t;
End;</langsyntaxhighlight>
 
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.
 
=={{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}}==
Line 2,639 ⟶ 2,982:
Swap is easily done via multiple assignment:
 
<langsyntaxhighlight lang="pop11">(a, b) -> (b, a);</langsyntaxhighlight>
 
Pop11 is dynamically typed, so the code above is "generic".
 
=={{header|PostScript}}==
Works with anything you can put on the operand stack:<syntaxhighlight lang PostScript="postscript">exch</langsyntaxhighlight>
 
=={{header|PowerShell}}==
PowerShell allows swapping directly, through tuple assignment:
<langsyntaxhighlight lang="powershell">$b, $a = $a, $b</langsyntaxhighlight>
But one can also define a function which swaps the values of two references:
<langsyntaxhighlight lang="powershell">function swap ([ref] $a, [ref] $b) {
$a.Value, $b.Value = $b.Value, $a.Value
}</langsyntaxhighlight>
When using this function the arguments have to be explicitly given as references:
<langsyntaxhighlight lang="powershell">swap ([ref] $a) ([ref] $b)</langsyntaxhighlight>
 
=={{header|Prolog}}==
 
<langsyntaxhighlight lang="prolog">
swap(A,B,B,A).
 
Line 2,664 ⟶ 3,007:
X = 2,
Y = 1.
</syntaxhighlight>
</lang>
 
=={{header|PureBasic}}==
Built in function:
<lang PureBasic>Swap a, b</lang>
 
=={{header|Python}}==
Line 2,674 ⟶ 3,013:
Python has support for swapping built in:
 
<langsyntaxhighlight lang="python">a, b = b, a</langsyntaxhighlight>
 
But the task calls for a "generic swap method" to be written, so here it is:
 
<langsyntaxhighlight lang="python">def swap(a, b):
return b, a</langsyntaxhighlight>
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|QBasic}}==
QBasic already has a generic swap procedure built in, but a new subroutine can be defined:
<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</lang>
 
=={{header|Quackery}}==
Line 2,699 ⟶ 3,025:
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.
 
<langsyntaxhighlight Quackerylang="quackery">[ over take over take
2swap dip put put ] is exchange ( s s --> )</langsyntaxhighlight>
 
 
Line 2,707 ⟶ 3,033:
R function arguments are passed by value, not by reference. You can work around this, however, by using their names and environment:
 
<langsyntaxhighlight Rlang="r">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)
}</langsyntaxhighlight>
 
Usage:
Line 2,725 ⟶ 3,051:
A swap operation can be easily written as a macro in Racket. The macro will even work as expected in Typed Racket.
 
<langsyntaxhighlight lang="racket">
#lang racket/load
 
Line 2,750 ⟶ 3,076:
(printf "x is ~a~n" x)
(printf "y is ~a~n" y))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Line 2,759 ⟶ 3,085:
Alternatively, you can write it like this:
 
<syntaxhighlight lang="raku" perl6line>($x, $y) .= reverse;</langsyntaxhighlight>
 
=={{header|REBOL}}==
<langsyntaxhighlight REBOLlang="rebol">REBOL [
Title: "Generic Swap"
URL: http://rosettacode.org/wiki/Generic_swap
Line 2,779 ⟶ 3,105:
answer: 42 ship: "Heart of Gold"
swap 'answer 'ship ; Note quoted variables.
print rejoin ["The answer is " answer ", the ship is " ship "."]</langsyntaxhighlight>
 
{{out}}
Line 2,786 ⟶ 3,112:
=={{header|Retro}}==
 
<syntaxhighlight lang Retro="retro">swap</langsyntaxhighlight>
 
=={{header|REXX}}==
Line 2,792 ⟶ 3,118:
(This is the slowest of the three versions.)
===using temp===
<langsyntaxhighlight lang="rexx">a = 'I see you.'
b = -6
 
_temp_ = a /*swap ··· */
a = b /* A ··· */
b = _temp_ /* and B */ </langsyntaxhighlight>
 
===using VALUE===
This version will work with any values.
<langsyntaxhighlight lang="rexx">a = "bull feathers"
b = 10
 
a= value('b', a) /*swap A and B */</langsyntaxhighlight>
 
===using PARSE===
Line 2,813 ⟶ 3,139:
in the values, the following method can be used:
<br>(This is the fastest of the three versions.)
<langsyntaxhighlight lang="rexx">a = -199e-12
b = 12.
 
parse value a b with b a /*swap A and B */</langsyntaxhighlight>
Note that some REXX interpreters handle whitespace differently, some honor whitespace other than blanks,
<br>others don't &nbsp; (particularly the older versions).
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
a = 1
b = 2
Line 2,829 ⟶ 3,155:
see "a = " + a + nl
see "b = " + b + nl
</syntaxhighlight>
</lang>
 
=={{header|RLaB}}==
Line 2,836 ⟶ 3,162:
Let we want to swap the content of two variables, which names are ''a'' and ''b'',
then the following function would do the trick
<syntaxhighlight lang="rlab">
<lang RLaB>
swap = function(x,y)
{
Line 2,859 ⟶ 3,185:
>> b
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}}==
Ruby has support for swapping built in:
 
<langsyntaxhighlight lang="ruby">a, b = b, a</langsyntaxhighlight>
 
But the task calls for a "generic swap method", so here it is:
 
<langsyntaxhighlight lang="ruby">def swap(a, b)
return b, a
end</langsyntaxhighlight>
 
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:
 
<langsyntaxhighlight lang="ruby">x = 42
y = "string"
x, y = swap x, y
puts x # prints string
puts y # prints 42</langsyntaxhighlight>
 
=={{header|Run BASIC}}==
 
Run BASIC does not have support for swapping built in:
<lang runbasic>a = 1
b = 2
'----- swap ----
tmp = a
a = b
b = tmp
end</lang>
 
=={{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.
<langsyntaxhighlight lang="rust">
fn generic_swap<'a, T>(var1: &'a mut T, var2: &'a mut T) {
std::mem::swap(var1, var2)
}
</syntaxhighlight>
</lang>
This function can be used in e.g. the following ways:
<langsyntaxhighlight lang="rust">
fn main() {
let mut a: String = "Alice".to_owned();
Line 2,913 ⟶ 3,262:
println!("c={}, d={}", c, d);
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,923 ⟶ 3,272:
A possible way that needs the type of the objects to be specified:
 
<langsyntaxhighlight lang="sather">class SWAP{T} is
swap(inout a, inout b:T) is
t ::= a;
Line 2,929 ⟶ 3,278:
b := t;
end;
end;</langsyntaxhighlight>
 
<langsyntaxhighlight lang="sather">class MAIN is
main is
x ::= 10;
Line 2,938 ⟶ 3,287:
#OUT + x + ", " + y + "\n";
end;
end;</langsyntaxhighlight>
 
=={{header|Scala}}==
Line 2,949 ⟶ 3,298:
To make up for that, it receives two values, and returns a tuple with the values inverted.
 
<langsyntaxhighlight lang="scala">def swap[A,B](a: A, b: B): (B, A) = (b, a)</langsyntaxhighlight>
 
=={{header|Scheme}}==
<langsyntaxhighlight lang="scheme">; swap elements of a vector
; vector-swap! is not part of r5rs, so we define it
(define (vector-swap! v i j)
Line 2,990 ⟶ 3,339:
; try it
(let ((a 1) (b 2)) (swap! a b) (list a b))
; (2 1)</langsyntaxhighlight>
 
=={{header|Seed7sed}}==
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:
<langsyntaxhighlight lang="seed7">const proc: generate_swap (in type: aType) is func
begin
 
Line 3,007 ⟶ 3,358:
end func;
 
end func;</langsyntaxhighlight>
An instance of a swap function can be generated with:
<langsyntaxhighlight lang="seed7">generate_swap(integer);
generate_swap(string);</langsyntaxhighlight>
A swap function can be called with:
<syntaxhighlight lang ="seed7">swap(a, b);</langsyntaxhighlight>
 
=={{header|SenseTalk}}==
<langsyntaxhighlight lang="sensetalk">
set [x,y] to [13,"Hello"] -- assign values to two variables
put x,y
Line 3,021 ⟶ 3,372:
set [x,y] to [y,x] -- swap the variable values
put x,y
</syntaxhighlight>
</lang>
Output:
<langsyntaxhighlight lang="sensetalk">
13
Hello
Line 3,029 ⟶ 3,380:
Hello
13
</syntaxhighlight>
</lang>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func swap(Ref a, Ref b) {
var tmp = *a;
*a = *b;
*b = tmp;
}</langsyntaxhighlight>
 
or:
<langsyntaxhighlight lang="ruby">func swap(Ref a, Ref b) {
(*a, *b) = (*b, *a);
}</langsyntaxhighlight>
 
or:
<langsyntaxhighlight lang="ruby">func swap(Ref a, Ref b) {
[*a, *b] » (b, a);
}</langsyntaxhighlight>
 
The swap functions must be called with variable references.
 
<langsyntaxhighlight lang="ruby">var (x, y) = (1, 2);
swap(\x, \y);</langsyntaxhighlight>
 
=={{header|Slate}}==
This must be done with a macro method in Slate, but is in the standard library:
<langsyntaxhighlight 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
in the current scope."
Line 3,064 ⟶ 3,415:
x variable store: y variable load.
y variable store: tmpVar load} parenthesize
].</langsyntaxhighlight>
 
Usage:
<syntaxhighlight lang ="slate">a `swapWith: b</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
Line 3,073 ⟶ 3,424:
 
An OrderedCollection can collect any kind of objects; so this swap implementend extending the OrderedCollection class is really generic.
<langsyntaxhighlight lang="smalltalk">OrderedCollection extend [
swap: a and: b [
|t|
Line 3,080 ⟶ 3,431:
self at: b put: t
]
]</langsyntaxhighlight>
 
=={{header|SNOBOL4}}==
Line 3,086 ⟶ 3,437:
The "canonical" version from M. Emmers tutorial:
 
<langsyntaxhighlight lang="snobol4">* SWAP(.V1, .V2) - Exchange the contents of two variables.
* The variables must be prefixed with the name operator
* when the function is called.
Line 3,094 ⟶ 3,445:
$X = $Y
$Y = TEMP :(RETURN)
SWAP_END</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight lang="sml">fun swap (x, y) = (y, x)</langsyntaxhighlight>
If the arguments are constrained to be reference values, a swap function is simple:
<langsyntaxhighlight lang="sml">fun swapref (x, y) =
let temp = !x in x := !y; y := temp end</langsyntaxhighlight>
 
=={{header|Stata}}==
The Mata '''[http://www.stata.com/help.cgi?mf_swap swap]''' function is built-in.
 
<langsyntaxhighlight lang="stata">mata
a=1,2,3
b="ars longa vita brevis"
swap(a, b)
end</langsyntaxhighlight>
 
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)].
Line 3,116 ⟶ 3,467:
=={{header|Swift}}==
 
<langsyntaxhighlight lang="swift">func swap<T>(inout a: T, inout b: T) {
(a, b) = (b, a)
}</langsyntaxhighlight>
 
'''Note:''' The Swift standard library has already a swap function.
Line 3,125 ⟶ 3,476:
 
{{works with|Tcl|>=8.5}}
<langsyntaxhighlight lang="tcl">proc swap {aName bName} {
upvar 1 $aName a $bName b
lassign [list $a $b] b a
}</langsyntaxhighlight>
 
{{works with|Tcl|>=8.4}}
<langsyntaxhighlight lang="tcl">proc swap {aName bName} {
upvar 1 $aName a $bName b
foreach {b a} [list $a $b] break
}</langsyntaxhighlight>
 
alternatively:
 
<langsyntaxhighlight lang="tcl">proc swap {aName bName} {
upvar 1 $aName a $bName b
set a $b[set b $a; list]
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="tcl">set a 1
set b 2
puts "before\ta=$a\tb=$b"
swap a b
puts "after\ta=$a\tb=$b"</langsyntaxhighlight>
 
{{out}}
Line 3,155 ⟶ 3,506:
An idiomatic method:
 
<langsyntaxhighlight lang="tcl">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"</langsyntaxhighlight>
 
{{out}}
<pre>before a=1 b=2
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|Tiny BASIC}}==
<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</lang>
 
=={{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:
<syntaxhighlight lang ="trith">swap</langsyntaxhighlight>
 
=={{header|True BASIC}}==
<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</lang>
 
=={{header|TXR}}==
Line 3,231 ⟶ 3,530:
This allows multiple evaluation of the argument expressions.
 
<langsyntaxhighlight lang="txrlisp">(defmacro swp (left right)
(with-gensyms (tmp)
^(let ((,tmp ,left))
(set ,left ,right
,right ,tmp))))</langsyntaxhighlight>
 
====Using <code>placelet</code>====
Line 3,241 ⟶ 3,540:
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:
 
<langsyntaxhighlight lang="txrlisp">(defmacro swp (left right)
(with-gensyms (tmp lpl rpl)
^(placelet ((,lpl ,left)
Line 3,247 ⟶ 3,546:
(let ((,tmp ,lpl))
(set ,lpl ,rpl
,rpl ,tmp)))))</langsyntaxhighlight>
 
====Using place expanders====
Line 3,253 ⟶ 3,552:
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:
 
<langsyntaxhighlight lang="txrlisp">(defmacro swp (left right :env env)
(with-gensyms (tmp)
(with-update-expander (l-getter l-setter) left env
Line 3,259 ⟶ 3,558:
^(let ((,tmp (,l-getter)))
(,l-setter (,r-getter))
(,r-setter ,tmp))))))</langsyntaxhighlight>
 
<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}}==
{{works with|ksh93}}
<langsyntaxhighlight lang="bash">$ swap() { typeset -n var1=$1 var2=$2; set -- "$var1" "$var2"; var1=$2; var2=$1; }
$ a=1 b=2
$ echo $a $b
Line 3,281 ⟶ 3,573:
$ swap a b
$ echo $a $b
1 2</langsyntaxhighlight>
 
{{works with|bash|4.2}}
<langsyntaxhighlight lang="bash">$ swap() { local var1=$1 var2=$2; set -- "${!var1}" "${!var2}"; declare -g "$var1"="$2" "$var2"="$1"; }
$ a=1 b=2
$ echo $a $b
Line 3,293 ⟶ 3,585:
$ swap a b
$ echo $a $b
1 2</langsyntaxhighlight>
 
=={{header|Ursala}}==
Line 3,299 ⟶ 3,591:
Swapping a pair is a very inexpensive operation because no actual copying or overwriting
is performed.
<langsyntaxhighlight Ursalalang="ursala">pmgs("x","y") = ("y","x") # the pattern matching way
 
ugs = ~&rlX # the idiosyncratic Ursala way
Line 3,305 ⟶ 3,597:
#cast %sWL
 
test = <pmgs ('a','b'),ugs ('x','y')></langsyntaxhighlight>
 
{{out}}
Line 3,313 ⟶ 3,605:
Using the view to shuffle the stack.
 
<langsyntaxhighlight lang="v">[swap [a b : b a] view].
 
1 2 swap
= 2 1
'hello' 'hi' swap</langsyntaxhighlight>
='hi' 'hello'
 
=={{header|VBScript}}==
This works for everything: strings, dates, booleans ... The fact is, with everything being a Variant, it's always generic.
 
<lang vb>sub swap( byref x, byref y )
dim temp
temp = x
x = y
y = temp
end sub</lang>
 
Usage:
<lang vb>dim a
a = "woof"
dim b
b = now()
swap a,b
wscript.echo a
wscript.echo b</lang>
 
{{out}}
<lang vb>5/02/2010 2:35:36 PM
woof</lang>
 
=={{header|Verbexx}}==
 
<langsyntaxhighlight lang="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: ;
Line 3,363 ⟶ 3,633:
a b = b a; // swap them back, just using the usual = verb
 
@SAY "a=" a " b=" b;</langsyntaxhighlight>
 
=={{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#]]
<lang vbnet>Sub Swap(Of T)(ByRef a As T, ByRef b As T)
Dim temp = a
a = b
b = temp
End Sub</lang>
 
Usage:
<lang vbnet>Dim a = 1, b = 2
Swap(a, b)</lang>
 
Line 3,387 ⟶ 3,639:
=={{header|Visual FoxPro}}==
Since Visual FoxPro is not strongly typed, this will work with any data types.
<langsyntaxhighlight lang="vfp">
*!* Swap two variables
LOCAL a, b
Line 3,403 ⟶ 3,655:
v2 = dum
ENDPROC
</langsyntaxhighlight>
{{out}}
<pre>
Line 3,412 ⟶ 3,664:
=={{header|Wart}}==
There's a primitive for modifying bindings.
<syntaxhighlight lang ="wart">(swap! x y)</langsyntaxhighlight>
 
New bindings can be created in parallel.
<langsyntaxhighlight lang="wart">let (x y) (list y x)
...</langsyntaxhighlight>
 
=={{header|Wren}}==
Line 3,423 ⟶ 3,675:
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.
<langsyntaxhighlight ecmascriptlang="wren">var swap = Fn.new { |l| l.swap(0, 1) }
var t = l[0]
l[0] = l[1]
l[1] = t
}
 
var a = 6
Line 3,464 ⟶ 3,712:
e = e.v // ditto
System.print("d is now %(d)")
System.print("e is now %(e)")</langsyntaxhighlight>
 
{{out}}
Line 3,478 ⟶ 3,726:
There is a keyword for swapping variables. Here is an example of 2 ways to swap variables
===Swap Keyword===
<langsyntaxhighlight XBSlang="xbs">set x=1;
set y=2;
log("Before Swap");
Line 3,486 ⟶ 3,734:
log("After Swap");
log(x);
log(y);</langsyntaxhighlight>
{{out}}
<pre>
Line 3,497 ⟶ 3,745:
</pre>
===Swap Function===
<langsyntaxhighlight XBSlang="xbs">set x = 1;
set y = 2;
func Swap(a,b){
Line 3,506 ⟶ 3,754:
y=z[1];
log(x)
log(y);</langsyntaxhighlight>
{{out}}
<pre>
Line 3,518 ⟶ 3,766:
the same size.
 
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes;
 
proc Exch(A, B, S);
Line 3,531 ⟶ 3,779:
Exch(addr X, addr Y, 8);
RlOut(0, X); RlOut(0, Y); CrLf(0);
]</langsyntaxhighlight>
 
{{out}}
Line 3,537 ⟶ 3,785:
4.00000 3.00000
</pre>
 
=={{header|Yabasic}}==
Yabasic already has a generic swap procedure built in.
<lang yabasic>a = 1
b = 2
 
print a, b
//----- swap ----
temp = a : a = b : b = temp
print a, b</lang>
 
=={{header|Yorick}}==
Line 3,576 ⟶ 3,814:
* <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:
<langsyntaxhighlight 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</langsyntaxhighlight>
 
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.
 
<langsyntaxhighlight lang="z80">;8-bit swap using the stack.
 
ld a,(&C000)
Line 3,590 ⟶ 3,828:
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</langsyntaxhighlight>
 
<langsyntaxhighlight 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.</langsyntaxhighlight>
 
===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.
 
<langsyntaxhighlight 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</langsyntaxhighlight>
 
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.
<langsyntaxhighlight 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+)"
Line 3,626 ⟶ 3,864:
ld (&C001),a ;store it at &C001
ld (hl),b ;store the old byte at &C001 into &D001
pop bc</langsyntaxhighlight>
 
=={{header|zkl}}==
As a general case, no. Here a fake around for two known classes
(which are the same for ease of example):
<langsyntaxhighlight lang="zkl">class C{var v; fcn init(n){v=n}}
var c1=C(1), c2=C(2);
println(c1.v," : ",c2.v);
Line 3,639 ⟶ 3,877:
}
swap(c1,c2,"v");
println(c1.v," : ",c2.v);</langsyntaxhighlight>
{{out}}
<pre>
885

edits