Generic swap: Difference between revisions

Line 2,380:
list($a, $b) = array($b, $a);
}</lang>
 
=={{header|Picat}}==
Picat supports re-assignment (<code>:=</code>), but it is not possible to swap two variables like this:
<lang Picat>A = 1,
B = 2,
[A,B] := [B,A],
% ...</lang>
 
(This throws an error: "invalid left-hand side of assignment").
 
The following works, but it's probably not general enough for this task:
<lang Picat>A = 1,
B = 2,
T = A, % Assuming that T is not used elsewhere in the clause
A := B,
B := T,
% ...</lang>
 
Instead swaps has to be done by some other means.
 
===Inline swapping in a list===
One way is to place the values in a list (or array) and use inline swapping of the list.
 
<lang Picat>% Swapping positions in a list/array
swap2(L) =>
swap_list(L,1,2).
 
% Swap two elements in a list
swap_list(L,I,J) =>
T = L[I],
L[I] := L[J],
L[J] := T.</lang>
 
Usage:
<lang Picat>L = [1,2],
swap2(L),
% ...</lang>
 
L is now [2,1]
 
Note: Placing the variables A, B in swap2
<lang Picat>swap2([A,B])</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:
<lang Picat>swap_pair([A,B],[B,A]).</lang>
 
Usage:
<lang Picat>A = 1,
B = 2,
swap_pair([A,B],X),
% ...</lang>
 
X is now [2,1]. A is still 1 and B is still 2.
 
 
=={{header|PicoLisp}}==
495

edits