Generic swap: Difference between revisions
→{{header|langur}}
Langurmonkey (talk | contribs) |
|||
(28 intermediate revisions by 21 users not shown) | |||
Line 21:
=={{header|11l}}==
<
(a, b) = (b, a)</
=={{header|360 Assembly}}==
Three consecutive exclusive OR's swap variable contents
<syntaxhighlight 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>
=={{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.
<
pha ;push accumulator
txa
Line 63:
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.
Line 87:
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:
<
ldx #$44
ldy #$55
Line 101:
pla ;a=#$55
ply ;y=#$44
plx ;x=#$33</
=={{header|68000 Assembly}}==
Two registers can be swapped with <code>EXG</code>:
<
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 ($00FF1000),D1
MOVE.L D0,($00FF1000)
MOVE.L D1,($00FF0000)</
The <code>SWAP</code> switches the high and low words of a data register. It can't be used with memory either.
<
SWAP D0 ;now D0 = #$ABCD1234</
=={{header|8086 Assembly}}==
Line 123:
Here are some examples of the <code>XCHG</code> command in action:
<
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.</
=={{header|8th}}==
<
swap
</syntaxhighlight>
Or to swap between the stack and a var:
<
dup @ -rot !
</syntaxhighlight>
=={{header|ACL2}}==
<
(cons (cdr pair)
(car pair)))
(let ((p (cons 1 2)))
(cw "Before: ~x0~%After: ~x1~%" p (swap p)))</
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
<
PROC Swap(BYTE POINTER ptr1,ptr2 INT size)
Line 206:
Swap(@s1,@s2,2)
Print(s1) Put(32) PrintE(s2)
RETURN</
{{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.
<
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;</
===usage===
To use the generic swap procedure, you need to instantiate the procedure for each type that you intend to use.
<
with Generic_Swap;
...
Line 240:
...
T_Swap (A, B);
</syntaxhighlight>
=={{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.
<
__swap(&, &,,)
{
Line 255:
{
xcall(xcall, __swap);
}</
=={{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]}}
<
GENMODE v1:="Francis Gary Powers", v2:="Vilyam Fisher";
Line 278:
v1 =:= v2;
print(("v1: ",v1, ", v2: ", v2, new line))</
{{out}}
<pre>
Line 289:
=={{header|Amazing Hopper}}==
<syntaxhighlight lang="amazing hopper">
#include <flow.h>
Line 302:
PRNL( "SINGLE VAR: ", single var, "\nRANDOM ARRAY: ", random array )
END
</syntaxhighlight>
{{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.
<
PROC main()
Line 330:
ForAll({x}, v2, `WriteF('\d ',x)) -> 10 20 30 40
WriteF('\n')
ENDPROC</
=={{header|AppleScript}}==
AppleScript has built-in support for swapping. This is generic and works for all combinations of data types.
<
=={{header|Arc}}==
<
(w/uniq gx
`(let ,gx a
Line 347:
(myswap a b)
(prn "a:" a #\Newline "b:" b))
</syntaxhighlight>
=={{header|Arturo}}==
{{trans|Ruby}}
===Using multi-assignment===
<
c: 1
Line 359:
[c,d]: swap c d
print [c d]</
{{out}}
Line 368:
===In-place modification===
<
tmp: var b
let b var a
Line 379:
swap 'c 'd
print [c d]</
{{out}}
Line 387:
=={{header|AutoHotkey}}==
<
{
temp := Left
Left := Right
Right := temp
}</
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f GENERIC_SWAP.AWK
BEGIN {
Line 421:
return(0)
}
</syntaxhighlight>
{{out}}
<pre>
Line 432:
a 1 ng
</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
=={{header|
==={{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}}===
<syntaxhighlight lang="freebasic">
x = 1
y$ = "hello"
Line 472 ⟶ 449:
SWAP x, y$
PRINT y$
</syntaxhighlight>
==={{header|BASIC256}}===
<
a = "one"
b = "two"
Line 486 ⟶ 463:
subroutine swap(a, b)
temp = a : a = b : b = temp
end subroutine</
==={{header|BBC BASIC}}===
====Built-in function====
<
SWAP a,b
PRINT a,b
Line 496 ⟶ 473:
a$ = "Hello " : b$ = "world!"
SWAP a$,b$
PRINT a$,b$</
====Custom function====
<
PROCswap(^a,^b, 5)
PRINT a,b
Line 512 ⟶ 489:
SWAP a%?i%,b%?i%
NEXT
ENDPROC</
{{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}}==
<
var
Line 527 ⟶ 853:
calc main_init
swap a[4] <=> b[3]</
{{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
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|Burlesque}}==
<
\/
</syntaxhighlight>
Stack-based swap.
Line 558 ⟶ 888:
This has a restriction that a and b must be the same size.
<
{
char t, *a = (char*)va, *b = (char*)vb;
while(s--)
t = a[s], a[s] = b[s], b[s] = t;
}</
{{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>.
<
Usage examples are:
<
#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);
}</
This is tested with GCC with <tt>-std=c89</tt> option.
Line 621 ⟶ 951:
are more strongly typed and arguably easier to work with.
<
{
T temp = a;
a = b;
b = temp;
}</
Usage:
<
int b = 2;
Swap(ref a, ref b); // Type parameter is inferred.</
===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.
<
int b = 2;
(a, b) = (b, a);</
=={{header|C++}}==
Line 648 ⟶ 978:
The implementation of the swap function template is straightforward:
<
{
T tmp(left);
left = right;
right = tmp;
}</
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
It will work with any types.
Line 665 ⟶ 995:
===C++11===
C++11 adds move constructors which can be more efficient than copy constructors.
<
void swap(T &lhs, T &rhs){
T tmp = std::move(lhs);
lhs = std::move(rhs);
rhs = std::move(tmp);
}</
=={{header|Chapel}}==
Chapel includes a swap operator:
<
and supports swapping directly via tuples and destructuring:
<
Both variables must be of the same type.
The [[Fibonacci sequence#Chapel|Fibonnacci implementation]] contains an example.
=={{header|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
</syntaxhighlight>
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.
<
set(_SWAP_TEMPORARY "${${var1}}")
set(${var1} "${${var2}}" PARENT_SCOPE)
set(${var2} "${_SWAP_TEMPORARY}" PARENT_SCOPE)
endfunction(swap)</
<
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: <
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": <
set(y "string")
swap(x y) # CMake Error... set given invalid arguments for CACHE mode.</
=={{header|COBOL}}==
<syntaxhighlight lang="cobol">
PROGRAM-ID. SWAP-DEMO.
AUTHOR. Bill Gunshannon.
Line 791 ⟶ 1,121:
END PROGRAM SWAP.
</syntaxhighlight>
{{out}}
<pre>
Line 822 ⟶ 1,152:
This is another standard swap.
<
<cfset a = b />
<cfset b = temp /></
=={{header|Common Lisp}}==
<
(psetq a b b a)</
=={{header|Computer/zero Assembly}}==
<
STA 31
LDA 30
Line 843 ⟶ 1,173:
byte $0F
byte $E0
byte $00</
Line 855 ⟶ 1,185:
Crystal directly supports swapping:
<
=={{header|D}}==
<
// The D solution uses templates and it's similar to the C++ one:
Line 881 ⟶ 1,211:
mySwap(a[0], a[1]);
writeln(a);
}</
{{out}}
<pre>[10, 20]
Line 889 ⟶ 1,219:
=={{header|dc}}==
We use two registers to swap in POSIX dc.
<
=2 1</
Reverse (r) is a built-in stack command available as a GNU extension for dc.
<
=2 1</
=={{header|DCL}}==
symbols do not have to be declared, they can be integers or strings, they can change type on the fly
<
$ a2 = "hello"
$ show symbol a*
Line 908 ⟶ 1,238:
$ a1 = a2
$ a2 = t
$ return</
{{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">
procedure Swap_T(var a, b: T);
var
Line 927 ⟶ 1,257:
b := temp;
end;
</syntaxhighlight>
Generics were introduced with Delphi 2009
<syntaxhighlight lang="delphi">
program GenericSwap;
Line 957 ⟶ 1,287:
writeln('After swap: a=', a, ' b=', b);
end.
</syntaxhighlight>
=={{header|Déjà Vu}}==
To swap the two top-most items on the stack:
<syntaxhighlight lang
To swap two variables without needing a third name, using the stack for temporary storage:
<
=={{header|E}}==
(slots)
<
def t := left
left := right
right := t
}</
(functional)
<
return [right, left]
}</
=={{header|EchoLisp}}==
<
;; 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>
=={{header|Elena}}==
ELENA 4.1 :
<
swap(ref object v1, ref object v2)
Line 1,026 ⟶ 1,356:
console.printLine(n," ",s)
}</
<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">
x = 4
y = 5
Line 1,045 ⟶ 1,375:
x # => 4
y # => 5
</syntaxhighlight>
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">
swap = fn x,y -> [y|x] end
[x|y] = swap.(1,2)
x # => 2
y # => 1
</syntaxhighlight>
Variables can be bound and rebound regardless of type
<syntaxhighlight 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>
=={{header|Emacs Lisp}}==
<
"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 <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.
<
`(setq ,b (prog1 ,a (setq ,a ,b))))</
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]]).
<
(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)</
=={{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">
1> L = [a, 2].
[a,2]
2> lists:reverse(L).
[2,a]
</syntaxhighlight>
Or swap the items in a tuple (also shown in the shell).
<syntaxhighlight lang="erlang">
1> T = {2,a}.
{2,a}
2> list_to_tuple(lists:reverse(tuple_to_list(T))).
{a,2}
</syntaxhighlight>
{{omit from|Euphoria}}
=={{header|Euphoria}}==
<syntaxhighlight lang="euphoria">
include std/console.e -- for display
Line 1,127 ⟶ 1,474:
display("x is now []",{x})
display("y is now []",{y})
</syntaxhighlight>
<pre>
Line 1,143 ⟶ 1,490:
=={{header|F_Sharp|F#}}==
<
=={{header|Factor}}==
Depending on how you look at it: this task doesn't apply, or it's trivial:
<syntaxhighlight lang
=={{header|Falcon}}==
<
a = 1
b = 2
a,b = arr = b,a
</syntaxhighlight>
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
=={{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
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<
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</
=={{header|Free Pascal}}==
<
{ 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.</
<pre>
Output:
Test me
me Test</pre>
=={{header|Frink}}==
The following example will work on all Frink data types:
<
[b,a] = [a,b]
</syntaxhighlight>
=={{header|
{{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}}==
<
1 !0 2 !1
</syntaxhighlight>
Now tape[0] and tape[1] are set to 1 and 2, respectively.
<
&0 &1 !0 pop !1
</syntaxhighlight>
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.
<
===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.
<
import "fmt"
Line 1,374 ⟶ 1,638:
swap(&a, &b)
fmt.Println(a, b)
}</
{{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.
<
import (
Line 1,433 ⟶ 1,697:
swap(&g, &h)
fmt.Println("g h:", g, h)
}</
{{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,
<
{
new .temp.
Line 1,466 ⟶ 1,730:
show .foo. " " .bar.
# prints "456 123"</
Or similar to swap synonyms (strings),
<
{
new \temp
Line 1,484 ⟶ 1,748:
show "\quux \xyzzy"
# prints "two one"</
=={{header|Groovy}}==
Line 1,490 ⟶ 1,754:
Groovy has support for swapping built in:
<
But the task calls for a "generic swap method" to be written, so here it is:
<
[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:
<
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:
<
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]</
=={{header|Harbour}}==
Line 1,516 ⟶ 1,780:
Implementation: (We exploit "pass by reference" method on the parameters used)
<
LOCAL xTmp
xTmp := v1
Line 1,522 ⟶ 1,786:
v2 := xTmp
RETURN
</syntaxhighlight>
Sample code:
<
LOCAL v1 := "World!", v2 := "Hello"
? v1, v2 // --> World! Hello
Line 1,530 ⟶ 1,794:
? v1, v2 // --> Hello World!
RETURN 0
</syntaxhighlight>
=={{header|Haskell}}==
Line 1,538 ⟶ 1,802:
The type signature, the first line, is optional; it may be inferred.
<
swap (x, y) = (y, x)</
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.
<
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</
=={{header|Icon}} and {{header|Unicon}}==
Icon provides a :=: operator for this. Additionally, there is a reversible exchange operator <-> that reverses the exchange if resumed.
<
x := 1
y := 2
Line 1,562 ⟶ 1,826:
if x <-> y & x < y then write(x, " ", y)
end
</syntaxhighlight>
=={{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.
<
c = temporary(a)
a = temporary(b)
b = temporary(c)
end</
=={{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):
<
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.
<
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:
<
Example use:
<
V2=: 7
'V1' destructiveSwap 'V2'
Line 1,611 ⟶ 1,866:
7
V2
cat</
=={{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.
<
T first;
T second;
Line 1,626 ⟶ 1,906:
p.first = p.second;
p.second = temp;
}</
=={{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.
<
var tmp = arr[0];
arr[0] = arr[1];
arr[1] = tmp;
}</
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.
<
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>
Solution without <tt>eval()</tt>, assuming that the code is running in the browser (<tt>window</tt> is the global object)
<
var tmp = window[a];
window[a] = window[b];
Line 1,662 ⟶ 1,942:
var y = 2;
swap('x', 'y');
</syntaxhighlight>
Another solution for swapping array items using destructing assignment:
<
[arr[0], arr[1]] = [arr[1], arr[0]]
</syntaxhighlight>
=={{header|Joy}}==
Provided that the stack contains at least two elements
<syntaxhighlight lang
changes the order of those elements
=={{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:<
Here is a filter that will swap the elements of a two-element array:
<syntaxhighlight lang
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:
<
=={{header|Julia}}==
Similar to Python, Julia has built-in support for swapping:
<
=={{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
Line 1,709 ⟶ 1,988:
println("d = $d")
println("e = $e")
}</
{{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}}==
<
1) using an Immediately Invoked Function Expression:
Line 1,739 ⟶ 2,038:
{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}}==
<
reverse # array</
=={{header|langur}}==
<syntaxhighlight lang="langur">var .abc = [1, 2, 3]
var .def = [5, 6, 7]
Line 1,755 ⟶ 2,078:
writeln .abc
writeln .def</
{{out}}
Line 1,766 ⟶ 2,085:
=={{header|Lasso}}==
<
local(a) = 'foo'
Line 1,773 ⟶ 2,092:
local(a,b) = swap(#a, #b)
stdoutnl(#a)
stdoutnl(#b)</
{{out}}
Line 1,781 ⟶ 2,100:
===Using Decompositional Assignment===
<
local(b) = 'moose'
local(a,b) = (: #b, #a)
stdoutnl(#a)
stdoutnl(#b)</
{{out}}
Line 1,794 ⟶ 2,113:
Lhogho is very similar except that it does not have a localmake opcode.
<
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>
=={{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:
<
return "tmp="&x&RETURN&x&"="&y&RETURN&y&"=tmp"
end</
Usage:
<
y = 2
do(swap("x","y"))
put x, y
-- 2 1</
=={{header|Lisaac}}==
<
=={{header|LiveCode}}==
<
put "last" into b2
swap a1,b2
Line 1,833 ⟶ 2,152:
put p1 into p2
put p3 into p1
end swap</
=={{header|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>
=={{header|Logtalk}}==
<
:- public(swap/4).
swap(First, Second, Second, First).
:- end_object.</
Usage examples:
<
X = oranges
Y = apples
Line 1,864 ⟶ 2,183:
| ?- paws::swap(3.14, ext(lgt), X, Y).
X = ext(lgt)
Y = 3.14</
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.
<
I HAS A foo ITZ "kittehz"
Line 1,880 ⟶ 2,199:
VISIBLE bar BTW, kittehz
KTHXBYE</
=={{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:
<
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>
Usage example:
<
x, y = 3, 4
print(x, y) --> 3 4
x, y = y, x -- swap
print(x, y) --> 4 3
</syntaxhighlight>
=={{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">
\\
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>
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
Line 2,015 ⟶ 2,334:
Print A()
Print B()
</syntaxhighlight>
=={{header|M4}}==
<
define(`swap', `def2(`$1',defn(`$2'),`$2',defn(`$1'))')dnl
dnl
Line 2,025 ⟶ 2,344:
a b
swap(`a',`b')
a b</
{{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">
> a, b := 2, "foo":
> a;
Line 2,050 ⟶ 2,369:
> b;
2
</syntaxhighlight>
=={{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.
<
SetAttributes[swap, HoldAll]</
=={{header|MATLAB}} / {{header|Octave}}==
Line 2,062 ⟶ 2,381:
Example:
<
a =
Line 2,078 ⟶ 2,397:
a =
40 30 60 50 70</
A generic swap (compatible with any variable type) can be performed with the ''deal'' command:
<syntaxhighlight lang="matlab">
>> a = 12
a = 12
Line 2,093 ⟶ 2,412:
b = 12
a = foo
</syntaxhighlight>
=={{header|Maxima}}==
<
b: foo$
Line 2,111 ⟶ 2,430:
a; /* 10 */
b; /* foo */</
=={{header|MAXScript}}==
<syntaxhighlight lang
=={{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)
<
save ?; string s_;
if boolean a: boolean ?
Line 2,130 ⟶ 2,449:
elseif transform a: transform ? fi;
? := a; a := b; b := ?
enddef;</
''Examples'':
<
i := 5;
show j, i;
Line 2,145 ⟶ 2,464:
show truth1, truth2;
swap(truth1,truth2);
show truth1, truth2;</
=={{header|min}}==
{{works with|min|0.19.3}}
Like many other stack languages, this is trivial.
<syntaxhighlight lang
=={{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.
<
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</
{{out}}
<pre>BEFORE: x=1, y=2
AFTER: x=2, y=1</pre>
=={{header|Modula-3}}==
<
PROCEDURE Swap(VAR left: Elem.T; VAR right: Elem.T);
END GenericSwap.</
<
PROCEDURE Swap(VAR left: Elem.T; VAR right: Elem.T) =
Line 2,185 ⟶ 2,504:
BEGIN
END GenericSwap.</
Here is an example usage for integers:
<
<
<
IMPORT IntSwap, IO, Fmt;
Line 2,201 ⟶ 2,520:
IntSwap.Swap(left, right);
IO.Put("Left = " & Fmt.Int(left) & "\n");
END Main.</
{{out}}
Line 2,211 ⟶ 2,530:
=={{header|Nemerle}}==
For pairs, namespace Nemerle.Utility.Pair contains Swap():
<
def invcoords = Swap(coords);</
Or to swap two mutable variables of the same type:<syntaxhighlight lang
But, enough about built in functionality, let's demonstrate using generics:
<
{
(b, a)
}</
=={{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.
<
options replace format comments java crossref symbols nobinary
Line 2,244 ⟶ 2,563:
return
</syntaxhighlight>
{{out}}
<pre>
Line 2,255 ⟶ 2,574:
=={{header|NewLISP}}==
<syntaxhighlight lang
=={{header|Nial}}==
Like J
<
=2 1</
=={{header|Nim}}==
Builtin procedure <code>swap</code>. Example usage:
<syntaxhighlight lang
=={{header|OASYS Assembler}}==
You can swap variable <tt>%A#</tt> with <tt>%B#</tt> by writing:
<
A method which can be called to implement it can be written like:
<
To call such method:
<syntaxhighlight lang
=={{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.
<
If the arguments are constrained to be reference values, a swap function is simple:
<
let temp = !x in
x := !y;
y := temp</
=={{header|Oforth}}==
<syntaxhighlight lang
=={{header|Oz}}==
Line 2,312 ⟶ 2,610:
We can write a swap procedure for cells, though. Cells are mutable references.
<
Tmp = @A
in
A := @B
B := Tmp
end</
Or shorter, if we exploit the fact that the assignment operator <code>:=</code> returns the old value of the cells:
<
B := A := @B
end</
A functional swap, operating on pairs:
<
B#A
end</
=={{header|PARI/GP}}==
Pari is near-typeless—everything is a GEN.
<
a=b;
b=tmp;</
{{works with|PARI/GP|2.6.0 and above}}
<
=={{header|Pascal}}==
{{works with|Free_Pascal|2.6.0}}
Standard Pascal does not have generics, but FreePascal has a start:
<
{$mode objfpc}
Line 2,369 ⟶ 2,667:
SwapInt(S, T);
writeln(S, T:2);
end.</
{{out}}
<pre>
Line 2,376 ⟶ 2,674:
</pre>
'''since FreePascal version 3.2.0:'''
<
{$mode objfpc}{H+}
uses
Line 2,398 ⟶ 2,696:
specialize GSwap<Integer>(I, J);
WriteLn('I = ', I, ', J = ', J);
end.</
{{out}}
<pre>
Line 2,408 ⟶ 2,706:
Perl has support for swapping built-in
<
Here's a generic swap routine:
<
=={{header|Phix}}==
{{libheader|Phix/basics}}
The following applies to any types. Subscripting and nesting may also be used freely on either side.
<!--<
<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>
<!--</
=={{header|Phixmonti}}==
Applies to any types.
<syntaxhighlight lang
=={{header|PHP}}==
<
list($a, $b) = array($b, $a);
}</
=={{header|Picat}}==
Picat supports re-assignment (<code>:=</code>), but it is not possible to swap two variables like this:
<
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:
<
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.
Line 2,453 ⟶ 2,751:
One way is to place the values in a list (or array) and use inline swapping of the list.
<
swap2(L) =>
swap_list(L,1,2).
Line 2,461 ⟶ 2,759:
T = L[I],
L[I] := L[J],
L[J] := T.</
Usage:
<
swap2(L),
% ...</
L is now [2,1]
Note: Placing the variables A, B in swap2
<syntaxhighlight lang
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:
<
Usage:
<
B = 2,
swap_pair([A,B],X),
% ...</
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
<
(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) )</
{{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 ====
<
%swap: procedure (a, b);
declare (a, b) character;
return ( 't=' || a || ';' || a || '=' || b || ';' || b '=t;' );
%end swap;
%activate swap;</
The statement:-
Line 2,517 ⟶ 2,856:
==== Using generic procedures ====
<
swapf when (float, float),
swapc when (char, char));
Line 2,532 ⟶ 2,871:
declare (r, s) character (5);
call swap (r, s);</
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 ====
<
dcl (x, y) char;
Line 2,576 ⟶ 2,915:
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);
Line 2,595 ⟶ 2,934:
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.
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:
<
%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;
Line 2,629 ⟶ 2,968:
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 <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:
<
Pop11 is dynamically typed, so the code above is "generic".
=={{header|PostScript}}==
Works with anything you can put on the operand stack:<syntaxhighlight lang
=={{header|PowerShell}}==
PowerShell allows swapping directly, through tuple assignment:
<
But one can also define a function which swaps the values of two references:
<
$a.Value, $b.Value = $b.Value, $a.Value
}</
When using this function the arguments have to be explicitly given as references:
<
=={{header|Prolog}}==
<
swap(A,B,B,A).
Line 2,664 ⟶ 3,007:
X = 2,
Y = 1.
</syntaxhighlight>
=={{header|Python}}==
Line 2,674 ⟶ 3,013:
Python has support for swapping built in:
<
But the task calls for a "generic swap method" to be written, so here it is:
<
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.
=={{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.
<
2swap dip put put ] is exchange ( s s --> )</
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:
<
{
temp <- get(name1, pos = envir)
assign(name1, get(name2, pos = envir), pos = envir)
assign(name2, temp, pos = envir)
}</
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.
<
#lang racket/load
Line 2,750 ⟶ 3,076:
(printf "x is ~a~n" x)
(printf "y is ~a~n" y))
</syntaxhighlight>
=={{header|Raku}}==
Line 2,759 ⟶ 3,085:
Alternatively, you can write it like this:
<syntaxhighlight lang="raku"
=={{header|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 "."]</
{{out}}
Line 2,786 ⟶ 3,112:
=={{header|Retro}}==
<syntaxhighlight lang
=={{header|REXX}}==
Line 2,792 ⟶ 3,118:
(This is the slowest of the three versions.)
===using temp===
<
b = -6
_temp_ = a /*swap ··· */
a = b /* A ··· */
b = _temp_ /* and B */ </
===using VALUE===
This version will work with any values.
<
b = 10
a= value('b', a) /*swap A and B */</
===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.)
<
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,
<br>others don't (particularly the older versions).
=={{header|Ring}}==
<
a = 1
b = 2
Line 2,829 ⟶ 3,155:
see "a = " + a + nl
see "b = " + b + nl
</syntaxhighlight>
=={{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">
swap = function(x,y)
{
Line 2,859 ⟶ 3,185:
>> b
1
</syntaxhighlight>
=={{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:
<
But the task calls for a "generic swap method", so here it is:
<
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:
<
y = "string"
x, y = swap x, y
puts x # prints string
puts y # prints 42</
=={{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.
<
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:
<
fn main() {
let mut a: String = "Alice".to_owned();
Line 2,913 ⟶ 3,262:
println!("c={}, d={}", c, d);
}
</syntaxhighlight>
{{out}}
<pre>
Line 2,923 ⟶ 3,272:
A possible way that needs the type of the objects to be specified:
<
swap(inout a, inout b:T) is
t ::= a;
Line 2,929 ⟶ 3,278:
b := t;
end;
end;</
<
main is
x ::= 10;
Line 2,938 ⟶ 3,287:
#OUT + x + ", " + y + "\n";
end;
end;</
=={{header|Scala}}==
Line 2,949 ⟶ 3,298:
To make up for that, it receives two values, and returns a tuple with the values inverted.
<
=={{header|Scheme}}==
<
; 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)</
=={{header|
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:
<
begin
Line 3,007 ⟶ 3,358:
end func;
end func;</
An instance of a swap function can be generated with:
<
generate_swap(string);</
A swap function can be called with:
<syntaxhighlight lang
=={{header|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>
Output:
<
13
Hello
Line 3,029 ⟶ 3,380:
Hello
13
</syntaxhighlight>
=={{header|Sidef}}==
<
var tmp = *a;
*a = *b;
*b = tmp;
}</
or:
<
(*a, *b) = (*b, *a);
}</
or:
<
[*a, *b] » (b, a);
}</
The swap functions must be called with variable references.
<
swap(\x, \y);</
=={{header|Slate}}==
This must be done with a macro method in Slate, but is in the standard library:
<
"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
].</
Usage:
<syntaxhighlight lang
=={{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.
<
swap: a and: b [
|t|
Line 3,080 ⟶ 3,431:
self at: b put: t
]
]</
=={{header|SNOBOL4}}==
Line 3,086 ⟶ 3,437:
The "canonical" version from M. Emmers tutorial:
<
* 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</
=={{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.
<
If the arguments are constrained to be reference values, a swap function is simple:
<
let temp = !x in x := !y; y := temp end</
=={{header|Stata}}==
The Mata '''[http://www.stata.com/help.cgi?mf_swap swap]''' function is built-in.
<
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)].
Line 3,116 ⟶ 3,467:
=={{header|Swift}}==
<
(a, b) = (b, a)
}</
'''Note:''' The Swift standard library has already a swap function.
Line 3,125 ⟶ 3,476:
{{works with|Tcl|>=8.5}}
<
upvar 1 $aName a $bName b
lassign [list $a $b] b a
}</
{{works with|Tcl|>=8.4}}
<
upvar 1 $aName a $bName b
foreach {b a} [list $a $b] break
}</
alternatively:
<
upvar 1 $aName a $bName b
set a $b[set b $a; list]
}</
<
set b 2
puts "before\ta=$a\tb=$b"
swap a b
puts "after\ta=$a\tb=$b"</
{{out}}
Line 3,155 ⟶ 3,506:
An idiomatic method:
<
set b 2
puts "before\ta=$a\tb=$b"
set a $b[set b $a;lindex {}]
puts "after\ta=$a\tb=$b"</
{{out}}
<pre>before a=1 b=2
after a=2 b=1</pre>
=={{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
=={{header|TXR}}==
Line 3,231 ⟶ 3,530:
This allows multiple evaluation of the argument expressions.
<
(with-gensyms (tmp)
^(let ((,tmp ,left))
(set ,left ,right
,right ,tmp))))</
====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:
<
(with-gensyms (tmp lpl rpl)
^(placelet ((,lpl ,left)
Line 3,247 ⟶ 3,546:
(let ((,tmp ,lpl))
(set ,lpl ,rpl
,rpl ,tmp)))))</
====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:
<
(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))))))</
<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|UNIX Shell}}==
{{works with|ksh93}}
<
$ a=1 b=2
$ echo $a $b
Line 3,281 ⟶ 3,573:
$ swap a b
$ echo $a $b
1 2</
{{works with|bash|4.2}}
<
$ a=1 b=2
$ echo $a $b
Line 3,293 ⟶ 3,585:
$ swap a b
$ echo $a $b
1 2</
=={{header|Ursala}}==
Line 3,299 ⟶ 3,591:
Swapping a pair is a very inexpensive operation because no actual copying or overwriting
is performed.
<
ugs = ~&rlX # the idiosyncratic Ursala way
Line 3,305 ⟶ 3,597:
#cast %sWL
test = <pmgs ('a','b'),ugs ('x','y')></
{{out}}
Line 3,313 ⟶ 3,605:
Using the view to shuffle the stack.
<
1 2 swap
= 2 1
'hello' 'hi' swap</
='hi' 'hello'
=={{header|Verbexx}}==
<
'<==> [_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;</
−
Line 3,387 ⟶ 3,639:
=={{header|Visual FoxPro}}==
Since Visual FoxPro is not strongly typed, this will work with any data types.
<
*!* Swap two variables
LOCAL a, b
Line 3,403 ⟶ 3,655:
v2 = dum
ENDPROC
</
{{out}}
<pre>
Line 3,412 ⟶ 3,664:
=={{header|Wart}}==
There's a primitive for modifying bindings.
<syntaxhighlight lang
New bindings can be created in parallel.
<
...</
=={{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.
<
var a = 6
Line 3,464 ⟶ 3,712:
e = e.v // ditto
System.print("d is now %(d)")
System.print("e is now %(e)")</
{{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===
<
set y=2;
log("Before Swap");
Line 3,486 ⟶ 3,734:
log("After Swap");
log(x);
log(y);</
{{out}}
<pre>
Line 3,497 ⟶ 3,745:
</pre>
===Swap Function===
<
set y = 2;
func Swap(a,b){
Line 3,506 ⟶ 3,754:
y=z[1];
log(x)
log(y);</
{{out}}
<pre>
Line 3,518 ⟶ 3,766:
the same size.
<
proc Exch(A, B, S);
Line 3,531 ⟶ 3,779:
Exch(addr X, addr Y, 8);
RlOut(0, X); RlOut(0, Y); CrLf(0);
]</
{{out}}
Line 3,537 ⟶ 3,785:
4.00000 3.00000
</pre>
=={{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:
<
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 <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.
<
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</
<
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, <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.
<
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 <code>LDI/LDD</code> commands can help us in this task.
<
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</
=={{header|zkl}}==
As a general case, no. Here a fake around for two known classes
(which are the same for ease of example):
<
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);</
{{out}}
<pre>
|