This commit is contained in:
Ingy döt Net 2013-04-10 21:29:02 -07:00
parent 764da6cbbb
commit db842d013d
19005 changed files with 197040 additions and 7 deletions

View file

@ -0,0 +1,13 @@
The task is to write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation. That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange.
Generic swap is a task which brings together a few separate issues in programming language semantics.
Dynamically typed languages deal with values in a generic way quite readily, but do not necessarily make it easy to write a function to destructively swap two variables, because this requires indirection upon storage places or upon the syntax designating storage places.
Functional languages, whether static or dynamic, do not necessarily allow a destructive operation such as swapping two variables regardless of their generic capabilities.
Some static languages have difficulties with generic programming due to a lack of support for ([[Parametric Polymorphism]]).
Do your best!

View file

@ -0,0 +1,2 @@
---
note: Basic language learning

View file

@ -0,0 +1,6 @@
(defun swap (pair)
(cons (cdr pair)
(car pair)))
(let ((p (cons 1 2)))
(cw "Before: ~x0~%After: ~x1~%" p (swap p)))

View file

@ -0,0 +1,13 @@
MODE GENMODE = STRING;
GENMODE v1:="Francis Gary Powers", v2:="Vilyam Fisher";
PRIO =:= = 1;
OP =:= = (REF GENMODE v1, v2)VOID: (
GENMODE tmp:=v1; v1:=v2; v2:=tmp
);
v1 =:= v2;
print(("v1: ",v1, ", v2: ", v2, new line))

View file

@ -0,0 +1,10 @@
generic
type Swap_Type is private; -- Generic parameter
procedure Generic_Swap(Left : in out Swap_Type; Right : in out Swap_Type);
procedure Generic_Swap(Left : in out Swap_Type; Right : in out Swap_Type) is
Temp : Swap_Type := Left;
begin
Left := Right;
Right := Temp;
end Generic_Swap;

View file

@ -0,0 +1,7 @@
with Generic_Swap;
...
type T is ...
package T_Swap is new Generic_Swap(Swap_Type => T);
A,B:T;
...
T_Swap(A,B);

View file

@ -0,0 +1,16 @@
PROC swap(a,b) IS b,a
PROC main()
DEF v1, v2, x
v1 := 10
v2 := 20
v1, v2 := swap(v1,v2)
WriteF('\d \d\n', v1,v2) -> 20 10
v1 := [ 10, 20, 30, 40 ]
v2 := [ 50, 60, 70, 80 ]
v1, v2 := swap(v1,v2)
ForAll({x}, v1, `WriteF('\d ',x)) -> 50 60 70 80
WriteF('\n')
ForAll({x}, v2, `WriteF('\d ',x)) -> 10 20 30 40
WriteF('\n')
ENDPROC

View file

@ -0,0 +1 @@
set {x,y} to {y,x}

View file

@ -0,0 +1,6 @@
Swap(ByRef Left, ByRef Right)
{
temp := Left
Left := Right
Right := temp
}

View file

@ -0,0 +1,7 @@
a = 1.23 : b = 4.56
SWAP a,b
PRINT a,b
a$ = "Hello " : b$ = "world!"
SWAP a$,b$
PRINT a$,b$

View file

@ -0,0 +1,15 @@
a = 1.23 : b = 4.56
PROCswap(^a,^b, 5)
PRINT a,b
a$ = "Hello " : b$ = "world!"
PROCswap(^a$,^b$, 6)
PRINT a$,b$
END
DEF PROCswap(a%, b%, s%)
LOCAL i%
FOR i% = 0 TO s%-1
SWAP a%?i%,b%?i%
NEXT
ENDPROC

View file

@ -0,0 +1,17 @@
@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

View file

@ -0,0 +1 @@
(!a.!b):(?b.?a)

View file

@ -0,0 +1 @@
\/

View file

@ -0,0 +1,6 @@
template<typename T> void swap(T& left, T& right)
{
T tmp(left);
left = right;
right = tmp;
}

View file

@ -0,0 +1 @@
std::swap(x,y);

View file

@ -0,0 +1,6 @@
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;
}

View file

@ -0,0 +1 @@
#define Swap(X,Y) do{ __typeof__ (X) _T = X; X = Y; Y = _T; }while(0)

View file

@ -0,0 +1,32 @@
#include <stdio.h>
#define Swap(X,Y) do{ __typeof__ (X) _T = X; X = Y; Y = _T; }while(0)
struct test
{
int a, b, c;
};
int main()
{
struct test t = { 1, 2, 3 };
struct test h = { 4, 5, 6 };
double alfa = 0.45, omega = 9.98;
struct test *pt = &t;
struct test *th = &h;
printf("%d %d %d\n", t.a, t.b, t.c );
Swap(t, h);
printf("%d %d %d\n", t.a, t.b, t.c );
printf("%d %d %d\n", h.a, h.b, h.c );
printf("%lf\n", alfa);
Swap(alfa, omega);
printf("%lf\n", alfa);
printf("%d\n", pt->a);
Swap(pt, th);
printf("%d\n", pt->a);
}

View file

@ -0,0 +1,5 @@
function(swap var1 var2)
set(_SWAP_TEMPORARY "${${var1}}")
set(${var1} "${${var2}}" PARENT_SCOPE)
set(${var2} "${_SWAP_TEMPORARY}" PARENT_SCOPE)
endfunction(swap)

View file

@ -0,0 +1,5 @@
set(x 42)
set(y "string")
swap(x y)
message(STATUS ${x}) # -- string
message(STATUS ${y}) # -- 42

View file

@ -0,0 +1,5 @@
set(x 42)
set(_SWAP_TEMPORARY "string")
swap(x _SWAP_TEMPORARY)
message(STATUS ${x}) # -- 42
message(STATUS ${_SWAP_TEMPORARY}) # -- 42

View file

@ -0,0 +1,3 @@
string(TOUPPER CACHE x)
set(y "string")
swap(x y) # CMake Error... set given invalid arguments for CACHE mode.

View file

@ -0,0 +1,3 @@
(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

View file

@ -0,0 +1,3 @@
<cfset temp = a />
<cfset a = b />
<cfset b = temp />

View file

@ -0,0 +1,3 @@
(rotatef a b)
(psetq a b b a)

View file

@ -0,0 +1,24 @@
import std.algorithm: swap; // from Phobos standard library
// The D solution uses templates and it's similar to the C++ one:
void mySwap(T)(ref T left, ref T right) {
auto temp = left;
left = right;
right = temp;
}
void main() {
import std.stdio;
int[] a = [10, 20];
writeln(a);
// The std.algorithm standard library module
// contains a generic swap:
swap(a[0], a[1]);
writeln(a);
// Using mySwap:
mySwap(a[0], a[1]);
writeln(a);
}

View file

@ -0,0 +1,8 @@
procedure Swap_T(var a, b: T);
var
temp: T;
begin
temp := a;
a := b;
b := temp;
end;

View file

@ -0,0 +1,5 @@
def swap(&left, &right) {
def t := left
left := right
right := t
}

View file

@ -0,0 +1,3 @@
def swap([left, right]) {
return [right, left]
}

View file

@ -0,0 +1,4 @@
1> L = [a, 2].
[a,2]
2> lists:reverse(L).
[2,a]

View file

@ -0,0 +1,4 @@
1> T = {2,a}.
{2,a}
2> list_to_tuple(lists:reverse(tuple_to_list(T))).
{a,2}

View file

@ -0,0 +1 @@
swap

View file

@ -0,0 +1,3 @@
a = 1
b = 2
a,b = arr = b,a

View file

@ -0,0 +1 @@
swap

View file

@ -0,0 +1,43 @@
MODULE Genericswap
IMPLICIT NONE
INTERFACE Swap
MODULE PROCEDURE Swapint, Swapreal, Swapstring
END INTERFACE
CONTAINS
SUBROUTINE Swapint(a, b)
INTEGER, INTENT(IN OUT) :: a, b
INTEGER :: temp
temp = a ; a = b ; b = temp
END SUBROUTINE Swapint
SUBROUTINE Swapreal(a, b)
REAL, INTENT(IN OUT) :: a, b
REAL :: temp
temp = a ; a = b ; b = temp
END SUBROUTINE Swapreal
SUBROUTINE Swapstring(a, b)
CHARACTER(*), INTENT(IN OUT) :: a, b
CHARACTER(len(a)) :: temp
temp = a ; a = b ; b = temp
END SUBROUTINE Swapstring
END MODULE Genericswap
PROGRAM EXAMPLE
USE Genericswap
IMPLICIT NONE
INTEGER :: i1 = 1, i2 = 2
REAL :: r1 = 1.0, r2 = 2.0
CHARACTER(3) :: s1="abc", s2="xyz"
CALL Swap(i1, i2)
CALL Swap(r1, r2)
CALL Swap(s1, s2)
WRITE(*,*) i1, i2 ! Prints 2 and 1
WRITE(*,*) r1, r2 ! Prints 2.0 and 1.0
WRITE(*,*) s1, s2 ! Prints xyz and abc
END PROGRAM EXAMPLE

View file

@ -0,0 +1 @@
[b,a] = [a,b]

View file

@ -0,0 +1 @@
1 !0 2 !1

View file

@ -0,0 +1 @@
&0 &1 !0 pop !1

View file

@ -0,0 +1 @@
a, b = b, a

View file

@ -0,0 +1,14 @@
package main
import "fmt"
func swap(a, b *interface{}) {
*a, *b = *b, *a
}
func main() {
var a, b interface{} = 3, "four"
fmt.Println(a, b)
swap(&a, &b)
fmt.Println(a, b)
}

View file

@ -0,0 +1,51 @@
package main
import (
"fmt"
"reflect"
)
func swap(a, b interface{}) error {
ta := reflect.TypeOf(a)
tb := reflect.TypeOf(b)
if ta != tb {
return fmt.Errorf("swap args are different types: %v and %v", ta, tb)
}
if ta.Kind() != reflect.Ptr {
return fmt.Errorf("swap args must be pointers")
}
ea := reflect.ValueOf(a).Elem()
eb := reflect.ValueOf(b).Elem()
temp := reflect.New(ea.Type()).Elem()
temp.Set(ea)
ea.Set(eb)
eb.Set(temp)
return nil
}
func main() {
a, b := 3, "cats"
fmt.Println("a b:", a, b)
err := swap(a, b)
fmt.Println(err, "\n")
c, d := 3, 4
fmt.Println("c d:", c, d)
err = swap(c, d)
fmt.Println(err, "\n")
e, f := 3, 4
fmt.Println("e f:", e, f)
swap(&e, &f)
fmt.Println("e f:", e, f, "\n")
type mult struct {
int
string
}
g, h := mult{3, "cats"}, mult{4, "dogs"}
fmt.Println("g h:", g, h)
swap(&g, &h)
fmt.Println("g h:", g, h)
}

View file

@ -0,0 +1 @@
(a, b) = [b, a]

View file

@ -0,0 +1,3 @@
def swap(a, b) {
[b, a]
}

View file

@ -0,0 +1,3 @@
def (x, y) = swap(1, 3)
assert x == 3
assert y == 1

View file

@ -0,0 +1,8 @@
def listSwap = { a, i, j ->
assert (0..<(a.size())).containsAll([i,j]);
a[[j,i]] = a[[i,j]]
}
def list = [2,4,6,8]
listSwap(list, 1, 3)
assert list == [2,8,6,4]

View file

@ -0,0 +1,2 @@
swap :: (a, b) -> (b, a)
swap (x, y) = (y, x)

View file

@ -0,0 +1,5 @@
pro swap, a, b
c = temporary(a)
a = temporary(b)
b = temporary(c)
end

View file

@ -0,0 +1,8 @@
procedure main()
x := 1
y := 2
x :=: y
write(x," ",y)
# swap that will reverse if surrounding expression fails
if x <-> y & x < y then write(x, " ", y)
end

View file

@ -0,0 +1,4 @@
(<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.

View file

@ -0,0 +1,4 @@
|.2 3
3 2
|.&.;:'one two'
two one

View file

@ -0,0 +1,6 @@
destructiveSwap=:4 :0
t=. do y
(y)=: do x
(x)=: t
i.0 0 NB. result is meaningless
)

View file

@ -0,0 +1,7 @@
V1=: 'cat'
V2=: 7
'V1' destructiveSwap 'V2'
V1
7
V2
cat

View file

@ -0,0 +1,9 @@
class Pair<T> {
T first;
T second;
}
public static <T> void swap(Pair<T> p) {
T temp = p.first;
p.first = p.second;
p.second = temp;
}

View file

@ -0,0 +1,5 @@
function swap(arr) {
var tmp = arr[0];
arr[0] = arr[1];
arr[1] = tmp;
}

View file

@ -0,0 +1,9 @@
function swap(aName, bName) {
return ('(function(){ arguments[0] = aName; aName = bName; bName = arguments[0] })()'
.replace(/aName/g, aName)
.replace(/bName/g, bName)
)
}
var x = 1
var y = 2
eval(swap('x', 'y'))

View file

@ -0,0 +1 @@
swap

View file

@ -0,0 +1,11 @@
HAI 1.3
I HAS A foo ITZ "kittehz"
I HAS A bar ITZ 42
foo, foo R bar, bar R IT
VISIBLE foo BTW, 42
VISIBLE bar BTW, kittehz
KTHXBYE

View file

@ -0,0 +1,2 @@
swap # stack
reverse # array

View file

@ -0,0 +1,11 @@
to swap :s1 :s2
local "t
make "t thing :s1
make :s1 thing :s2
make :s2 :t
end
make "a 4
make "b "dog
swap "a "b ; pass the names of the variables to swap
show list :a :b ; [dog 4]

View file

@ -0,0 +1 @@
(a, b) := (b, a);

View file

@ -0,0 +1,10 @@
to swap :s1 :s2
localmake "t thing :s1
make :s1 thing :s2
make :s2 :t
end
make "a 4
make "b "dog
swap "a "b ; pass the names of the variables to swap
show list :a :b ; [dog 4]

View file

@ -0,0 +1,6 @@
:- object(paws).
:- public(swap/4).
swap(First, Second, Second, First).
:- end_object.

View file

@ -0,0 +1,8 @@
| ?- paws::swap(apples, oranges, X, Y).
X = oranges
Y = apples
yes
| ?- paws::swap(3.14, ext(lgt), X, Y).
X = ext(lgt)
Y = 3.14

View file

@ -0,0 +1,2 @@
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

View file

@ -0,0 +1,4 @@
x, y = 3, 4
print(x, y) --> 3 4
x, y = y, x -- swap
print(x, y) --> 4 3

View file

@ -0,0 +1,8 @@
define(`def2', `define(`$1',`$2')define(`$3',`$4')')dnl
define(`swap', `def2(`$1',defn(`$2'),`$2',defn(`$1'))')dnl
dnl
define(`a',`x')dnl
define(`b',`y')dnl
a b
swap(`a',`b')
a b

View file

@ -0,0 +1,17 @@
>> a = [30 40 50 60 70]
a =
30 40 50 60 70
>> a([1 3]) = a([3 1]) %Single swap
a =
50 40 30 60 70
>> a([1 2 4 3]) = a([2 3 1 4]) %Multiple swap, a.k.a permutation.
a =
40 30 60 50 70

View file

@ -0,0 +1 @@
swap a b

View file

@ -0,0 +1,13 @@
> a, b := 2, "foo":
> a;
2
> b;
"foo"
> a, b := b, a: # SWAP
> a;
"foo"
> b;
2

View file

@ -0,0 +1,2 @@
swap[a_, b_] := {a, b} = {b, a}
SetAttributes[swap, HoldAll]

View file

@ -0,0 +1,16 @@
a: 10$
b: 20$
/* A simple way to swap values */
[a, b]: [b, a]$
a; /* 20 */
b; /* 10 */
/* A macro to hide this */
swap(x, y) ::= buildq([x, y], ([x, y]: [y, x], 'done))$
swap(a, b)$
a; /* 10 */
b; /* 20 */

View file

@ -0,0 +1,12 @@
vardef swap(suffix a, b) =
save ?; string s_;
if boolean a: boolean ?
elseif numeric a: numeric ? % this one could be omitted
elseif pair a: pair ?
elseif path a: path ?
elseif pen a: pen ?
elseif picture a: picture ?
elseif string a: string ?
elseif transform a: transform ? fi;
? := a; a := b; b := ?
enddef;

View file

@ -0,0 +1,12 @@
j := 10;
i := 5;
show j, i;
swap(j,i);
show j, i;
boolean truth[];
truth1 := true;
truth2 := false;
show truth1, truth2;
swap(truth1,truth2);
show truth1, truth2;

View file

@ -0,0 +1,5 @@
GENERIC INTERFACE GenericSwap(Elem);
PROCEDURE Swap(VAR left: Elem.T; VAR right: Elem.T);
END GenericSwap.

View file

@ -0,0 +1,11 @@
GENERIC MODULE GenericSwap(Elem);
PROCEDURE Swap(VAR left: Elem.T; VAR right: Elem.T) =
VAR temp: Elem.T := left;
BEGIN
left := right;
right := temp;
END Swap;
BEGIN
END GenericSwap.

View file

@ -0,0 +1 @@
INTERFACE IntSwap = GenericSwap(Integer) END IntSwap.

View file

@ -0,0 +1 @@
MODULE IntSwap = GenericSwap(Integer) END IntSwap.

View file

@ -0,0 +1,12 @@
MODULE Main;
IMPORT IntSwap, IO, Fmt;
VAR left := 10;
right := 20;
BEGIN
IO.Put("Left = " & Fmt.Int(left) & "\n");
IntSwap.Swap(left, right);
IO.Put("Left = " & Fmt.Int(left) & "\n");
END Main.

View file

@ -0,0 +1,3 @@
function swap(&$a, &$b) {
list($a, $b) = array($b, $a);
}

View file

@ -0,0 +1 @@
($y, $x) = ($x, $y);

View file

@ -0,0 +1 @@
sub swap {@_[0, 1] = @_[1, 0]}

View file

@ -0,0 +1,7 @@
(let (A 1 B 2)
(xchg 'A 'B)
(println A B) )
(let (Lst1 '(a b c) Lst2 '(d e f))
(xchg (cdr Lst1) (cdr Lst2))
(println Lst1 Lst2) )

View file

@ -0,0 +1,5 @@
swap(A,B,B,A).
?- swap(1,2,X,Y).
X = 2,
Y = 1.

View file

@ -0,0 +1 @@
a, b = b, a

View file

@ -0,0 +1,2 @@
def swap(a, b):
return b, a

View file

@ -0,0 +1,6 @@
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)
}

View file

@ -0,0 +1,6 @@
a = 'some value'
b = 6
_temp_ = a
a = b
b = _temp_

View file

@ -0,0 +1,4 @@
a = -199e-12
b = 12.
parse value a b with b a /*swaps A and B */

View file

@ -0,0 +1,24 @@
#lang racket/load
(module swap racket
(provide swap)
;; a simple macro to swap two variables
(define-syntax-rule (swap a b)
(let ([tmp a])
(set! a b)
(set! b tmp))))
;; works fine in a statically typed setting
(module typed typed/racket
(require 'swap)
(: x Integer)
(define x 3)
(: y Integer)
(define y 4)
(swap x y)
(printf "x is ~a~n" x)
(printf "y is ~a~n" y))

View file

@ -0,0 +1 @@
a, b = b, a

View file

@ -0,0 +1,3 @@
def swap(a, b)
return b, a
end

View file

@ -0,0 +1,5 @@
x = 42
y = "string"
x, y = swap x, y
puts x # prints string
puts y # prints 42

View file

@ -0,0 +1,7 @@
class SWAP{T} is
swap(inout a, inout b:T) is
t ::= a;
a := b;
b := t;
end;
end;

View file

@ -0,0 +1,8 @@
class MAIN is
main is
x ::= 10;
y ::= 20;
SWAP{INT}::swap(inout x, inout y);
#OUT + x + ", " + y + "\n";
end;
end;

View file

@ -0,0 +1 @@
def swap[A,B](a: A, b: B): (B, A) = (b, a)

View file

@ -0,0 +1,39 @@
; swap elements of a vector
; vector-swap! is not part of r5rs, so we define it
(define (vector-swap! v i j)
(let ((a (vector-ref v i)) (b (vector-ref v j)))
(vector-set! v i b)
(vector-set! v j a)))
(let ((vec (vector 1 2 3 4 5)))
(vector-swap! vec 0 4)
vec)
; #(5 2 3 4 1)
; we can swap also in lists
(define (list-swap! v i j)
(let* ((x (list-tail v i))
(y (list-tail v j))
(a (car x))
(b (car y)))
(set-car! x b)
(set-car! y a)))
(let ((lis (list 1 2 3 4 5)))
(list-swap! lis 0 4)
lis)
; (5 2 3 4 1)
; using macros (will work on variables, not on vectors or lists)
(define-syntax swap!
(syntax-rules ()
((_ a b)
(let ((tmp a))
(set! a b)
(set! b tmp)))))
; try it
(let ((a 1) (b 2)) (swap! a b) (list a b))
; (2 1)

View file

@ -0,0 +1,8 @@
OrderedCollection extend [
swap: a and: b [
|t|
t := self at: a.
self at: a put: (self at: b).
self at: b put: t
]
]

View file

@ -0,0 +1,4 @@
proc swap {aName bName} {
upvar 1 $aName a $bName b
lassign [list $a $b] b a
}

View file

@ -0,0 +1,4 @@
proc swap {aName bName} {
upvar 1 $aName a $bName b
foreach {b a} [list $a $b] break
}

Some files were not shown because too many files have changed in this diff Show more