Array concatenation: Difference between revisions
bash |
m →{{header|FutureBasic}}: added second option to concatenate arrays |
||
(296 intermediate revisions by more than 100 users not shown) | |||
Line 1: | Line 1: | ||
[[Category:Simple]] |
|||
{{task|Data Structures}}Show how to concatenate two arrays in your language. If this is as simple as <code><var>array1</var> + <var>array2</var></code>, so be it. |
|||
{{task|Data Structures}} |
|||
;Task: |
|||
Show how to concatenate two arrays in your language. |
|||
If this is as simple as <code><var>array1</var> + <var>array2</var></code>, so be it. |
|||
<br><br> |
|||
=={{header|11l}}== |
|||
<syntaxhighlight lang="11l">V arr1 = [1, 2, 3] |
|||
V arr2 = [4, 5, 6] |
|||
print(arr1 [+] arr2)</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
[1, 2, 3, 4, 5, 6] |
|||
</pre> |
|||
=={{header|68000 Assembly}}== |
|||
In order for this to work, you'll either need to use <code>malloc()</code> or know a memory location of "free space" at compile time. This example shall use the latter. |
|||
<syntaxhighlight lang="68000devpac">ArrayRam equ $00FF2000 ;this label points to 4k of free space. |
|||
;concatenate Array1 + Array2 |
|||
LEA ArrayRam,A0 |
|||
LEA Array1,A1 |
|||
MOVE.W #5-1,D1 ;LEN(Array1), measured in words. |
|||
JSR memcpy_w |
|||
;after this, A0 will point to the destination of the second array. |
|||
LEA Array2,A1 ;even though the source arrays are stored back-to-back in memory, we'll assume they're not just for demonstration purposes. |
|||
MOVE.W #5-1,D1 ;LEN(Array2), measured in words |
|||
JSR memcpy_w |
|||
JMP * ;halt the CPU |
|||
memcpy_w: |
|||
MOVE.W (A1)+,(A0)+ |
|||
DBRA D1,memcpy_w |
|||
rts |
|||
Array1: |
|||
DC.W 1,2,3,4,5 |
|||
Array2: |
|||
DC.W 6,7,8,9,10</syntaxhighlight> |
|||
=={{header|8th}}== |
|||
<syntaxhighlight lang="forth"> |
|||
[1,2,3] [4,5,6] a:+ . |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
[1,2,3,4,5,6] |
|||
</pre> |
|||
=={{header|AArch64 Assembly}}== |
|||
{{works with|as|Raspberry Pi 3B version Buster 64 bits}} |
|||
<syntaxhighlight lang="aarch64 assembly"> |
|||
/* ARM assembly AARCH64 Raspberry PI 3B */ |
|||
/* program concAreaString.s */ |
|||
/*******************************************/ |
|||
/* Constantes file */ |
|||
/*******************************************/ |
|||
/* for this file see task include a file in language AArch64 assembly*/ |
|||
.include "../includeConstantesARM64.inc" |
|||
.equ NBMAXITEMS, 20 // |
|||
/*******************************************/ |
|||
/* Initialized data */ |
|||
/*******************************************/ |
|||
.data |
|||
szMessLenArea: .asciz "The length of area 3 is : @ \n" |
|||
szCarriageReturn: .asciz "\n" |
|||
/* areas strings */ |
|||
szString1: .asciz "Apples" |
|||
szString2: .asciz "Oranges" |
|||
szString3: .asciz "Pommes" |
|||
szString4: .asciz "Raisins" |
|||
szString5: .asciz "Abricots" |
|||
/* pointer items area 1*/ |
|||
tablesPoi1: |
|||
pt1_1: .quad szString1 |
|||
pt1_2: .quad szString2 |
|||
ptVoid_1: .quad 0 |
|||
/* pointer items area 2*/ |
|||
tablesPoi2: |
|||
pt2_1: .quad szString3 |
|||
pt2_2: .quad szString4 |
|||
pt2_3: .quad szString5 |
|||
ptVoid_2: .quad 0 |
|||
/*******************************************/ |
|||
/* UnInitialized data */ |
|||
/*******************************************/ |
|||
.bss |
|||
tablesPoi3: .skip 8 * NBMAXITEMS |
|||
sZoneConv: .skip 30 |
|||
/*******************************************/ |
|||
/* code section */ |
|||
/*******************************************/ |
|||
.text |
|||
.global main |
|||
main: // entry of program |
|||
// copy area 1 -> area 3 |
|||
ldr x1,qAdrtablesPoi1 // begin pointer area 1 |
|||
ldr x3,qAdrtablesPoi3 // begin pointer area 3 |
|||
mov x0,0 // counter |
|||
1: |
|||
ldr x2,[x1,x0,lsl 3] // read string pointer address item x0 (8 bytes by pointer) |
|||
cbz x2,2f // is null ? |
|||
str x2,[x3,x0,lsl 3] // no store pointer in area 3 |
|||
add x0,x0,1 // increment counter |
|||
b 1b // and loop |
|||
2: // copy area 2 -> area 3 |
|||
ldr x1,qAdrtablesPoi2 // begin pointer area 2 |
|||
ldr x3,qAdrtablesPoi3 // begin pointer area 3 |
|||
mov x4,#0 // counter area 2 |
|||
3: // x0 contains the first void item in area 3 |
|||
ldr x2,[x1,x4,lsl #3] // read string pointer address item x0 (8 bytes by pointer) |
|||
cbz x2,4f // is null ? |
|||
str x2,[x3,x0,lsl #3] // no store pointer in area 3 |
|||
add x0,x0,1 // increment counter |
|||
add x4,x4,1 // increment counter |
|||
b 3b // and loop |
|||
4: |
|||
// count items number in area 3 |
|||
ldr x1,qAdrtablesPoi3 // begin pointer table |
|||
mov x0,#0 // counter |
|||
5: // begin loop |
|||
ldr x2,[x1,x0,lsl #3] // read string pointer address item x0 (8 bytes by pointer) |
|||
cmp x2,#0 // is null ? |
|||
cinc x0,x0,ne // no increment counter |
|||
bne 5b // and loop |
|||
ldr x1,qAdrsZoneConv // conversion decimal |
|||
bl conversion10S |
|||
ldr x0,qAdrszMessLenArea |
|||
ldr x1,qAdrsZoneConv |
|||
bl strInsertAtCharInc // insert result at @ character |
|||
bl affichageMess |
|||
100: // standard end of the program |
|||
mov x0,0 // return code |
|||
mov x8,EXIT // request to exit program |
|||
svc 0 // perform the system call |
|||
qAdrtablesPoi1: .quad tablesPoi1 |
|||
qAdrtablesPoi2: .quad tablesPoi2 |
|||
qAdrtablesPoi3: .quad tablesPoi3 |
|||
qAdrszMessLenArea: .quad szMessLenArea |
|||
qAdrsZoneConv: .quad sZoneConv |
|||
qAdrszCarriageReturn: .quad szCarriageReturn |
|||
/****************************************************/ |
|||
/* File Include fonctions */ |
|||
/********************************************************/ |
|||
/* for this file see task include a file in language AArch64 assembly */ |
|||
.include "../includeARM64.inc" |
|||
</syntaxhighlight> |
|||
=={{header|ABAP}}== |
|||
The concept of arrays does not exist in ABAP, instead internal tables are used. This works in ABAP version 7.40 and above. |
|||
<syntaxhighlight lang="abap"> |
|||
report z_array_concatenation. |
|||
data(itab1) = value int4_table( ( 1 ) ( 2 ) ( 3 ) ). |
|||
data(itab2) = value int4_table( ( 4 ) ( 5 ) ( 6 ) ). |
|||
append lines of itab2 to itab1. |
|||
loop at itab1 assigning field-symbol(<line>). |
|||
write <line>. |
|||
endloop. |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
1 2 3 4 5 6 |
|||
</pre> |
|||
=={{header|ACL2}}== |
=={{header|ACL2}}== |
||
This is for lists, not arrays; ACL2's array support is limited. |
This is for lists, not arrays; ACL2's array support is limited. |
||
<lang |
<syntaxhighlight lang="lisp">(append xs ys)</syntaxhighlight> |
||
=={{header|Action!}}== |
|||
<syntaxhighlight lang="action!">BYTE FUNC Concat(INT ARRAY src1,src2,dst BYTE size1,size2) |
|||
BYTE i |
|||
FOR i=0 TO size1-1 |
|||
DO |
|||
dst(i)=src1(i) |
|||
OD |
|||
FOR i=0 TO size2-1 |
|||
DO |
|||
dst(size1+i)=src2(i) |
|||
OD |
|||
RETURN (size1+size2) |
|||
PROC PrintArray(INT ARRAY a BYTE size) |
|||
BYTE i |
|||
Put('[) |
|||
FOR i=0 TO size-1 |
|||
DO |
|||
PrintI(a(i)) |
|||
IF i<size-1 THEN |
|||
Put(' ) |
|||
FI |
|||
OD |
|||
Put(']) |
|||
RETURN |
|||
PROC Test(INT ARRAY src1,src2 BYTE size1,size2) |
|||
INT ARRAY res(20) |
|||
BYTE size |
|||
size=Concat(src1,src2,res,size1,size2) |
|||
PrintArray(src1,size1) |
|||
Put('+) |
|||
PrintArray(src2,size2) |
|||
Put('=) |
|||
PrintArray(res,size) |
|||
PutE() PutE() |
|||
RETURN |
|||
PROC Main() |
|||
INT ARRAY |
|||
a1=[1 2 3 4], |
|||
a2=[5 6 7 8 9 10], |
|||
;a workaround for a3=[-1 -2 -3 -4 -5] |
|||
a3=[65535 65534 65533 65532 65531] |
|||
Test(a1,a2,4,6) |
|||
Test(a2,a1,6,4) |
|||
Test(a3,a2,5,4) |
|||
RETURN</syntaxhighlight> |
|||
{{out}} |
|||
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Array_concatenation.png Screenshot from Atari 8-bit computer] |
|||
<pre> |
|||
[1 2 3 4]+[5 6 7 8 9 10]=[1 2 3 4 5 6 7 8 9 10] |
|||
[5 6 7 8 9 10]+[1 2 3 4]=[5 6 7 8 9 10 1 2 3 4] |
|||
[-1 -2 -3 -4 -5]+[5 6 7 8]=[-1 -2 -3 -4 -5 5 6 7 8] |
|||
</pre> |
|||
=={{header|ActionScript}}== |
=={{header|ActionScript}}== |
||
< |
<syntaxhighlight lang="actionscript">var array1:Array = new Array(1, 2, 3); |
||
var array2:Array = new Array(4, 5, 6); |
var array2:Array = new Array(4, 5, 6); |
||
var array3:Array = array1.concat(array2); //[1, 2, 3, 4, 5, 6]</ |
var array3:Array = array1.concat(array2); //[1, 2, 3, 4, 5, 6]</syntaxhighlight> |
||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
In [[Ada]] arrays are concatenated using the operation &. It works with any one dimensioned array: |
In [[Ada]] arrays are concatenated using the operation &. It works with any one dimensioned array: |
||
< |
<syntaxhighlight lang="ada">type T is array (Positive range <>) of Integer; |
||
X : T := (1, 2, 3); |
X : T := (1, 2, 3); |
||
Y : T := X & (4, 5, 6); -- Concatenate X and (4, 5, 6)</ |
Y : T := X & (4, 5, 6); -- Concatenate X and (4, 5, 6)</syntaxhighlight> |
||
=={{header|Aime}}== |
|||
<syntaxhighlight lang="aime">ac(list a, b) |
|||
{ |
|||
list o; |
|||
o.copy(a); |
|||
b.ucall(l_append, 1, o); |
|||
o; |
|||
} |
|||
main(void) |
|||
{ |
|||
list a, b, c; |
|||
a = list(1, 2, 3, 4); |
|||
b = list(5, 6, 7, 8); |
|||
c = ac(a, b); |
|||
c.ucall(o_, 1, " "); |
|||
0; |
|||
}</syntaxhighlight> |
|||
{{Out}} |
|||
<pre> 1 2 3 4 5 6 7 8</pre> |
|||
=={{header|ALGOL 68}}== |
=={{header|ALGOL 68}}== |
||
Line 22: | Line 292: | ||
<!-- {{not tested 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.fc9.i386]}} --> |
<!-- {{not tested 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.fc9.i386]}} --> |
||
Includes operators for ''appending'' and ''prefixing'' an array to an existing flexible array: |
Includes operators for ''appending'' and ''prefixing'' an array to an existing flexible array: |
||
< |
<syntaxhighlight lang="algol68">MODE ARGTYPE = INT; |
||
MODE ARGLIST = FLEX[0]ARGTYPE; |
MODE ARGLIST = FLEX[0]ARGTYPE; |
||
Line 51: | Line 321: | ||
VOID(a +=: b); |
VOID(a +=: b); |
||
print(("a +=: b", b, new line))</ |
print(("a +=: b", b, new line))</syntaxhighlight> |
||
<pre> |
<pre> |
||
a + b +1 +2 +3 +4 +5 |
a + b +1 +2 +3 +4 +5 |
||
Line 57: | Line 327: | ||
a +=: b +1 +2 +3 +4 +5 +3 +4 +5 |
a +=: b +1 +2 +3 +4 +5 +3 +4 +5 |
||
</pre> |
</pre> |
||
=={{header|ALGOL W}}== |
|||
Algol W does not allow procedures to return arrays and has no mechanism for procedures to find the bounds of their parameters, so the caller must supply an array to concatenate into and the bounds of the arrays. |
|||
<syntaxhighlight lang="algolw">begin |
|||
integer array a ( 1 :: 5 ); |
|||
integer array b ( 2 :: 4 ); |
|||
integer array c ( 1 :: 8 ); |
|||
% concatenates the arrays a and b into c % |
|||
% the lower and upper bounds of each array must be specified in % |
|||
% the corresponding *Lb and *Ub parameters % |
|||
procedure arrayConcatenate ( integer array a ( * ) |
|||
; integer value aLb, aUb |
|||
; integer array b ( * ) |
|||
; integer value bLb, bUb |
|||
; integer array c ( * ) |
|||
; integer value cLb, cUb |
|||
) ; |
|||
begin |
|||
integer cPos; |
|||
assert( ( cUb - cLb ) + 1 >= ( ( aUb + bUb ) - ( aLb + bLb ) ) - 2 ); |
|||
cPos := cLb; |
|||
for aPos := aLb until aUb do begin |
|||
c( cPos ) := a( aPos ); |
|||
cPos := cPos + 1 |
|||
end for_aPos ; |
|||
for bPos := bLb until bUb do begin |
|||
c( cPos ) := b( bPos ); |
|||
cPos := cPos + 1 |
|||
end for_bPos |
|||
end arrayConcatenate ; |
|||
% test arrayConcatenate % |
|||
for aPos := 1 until 5 do a( aPos ) := aPos; |
|||
for bPos := 2 until 4 do b( bPos ) := - bPos; |
|||
arrayConcatenate( a, 1, 5, b, 2, 4, c, 1, 8 ); |
|||
for cPos := 1 until 8 do writeon( i_w := 1, s_w := 1, c( cPos ) ) |
|||
end.</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
1 2 3 4 5 -2 -3 -4 |
|||
</pre> |
|||
=={{header|Amazing Hopper}}== |
|||
<syntaxhighlight lang="amazing hopper"> |
|||
#include <hbasic.h> |
|||
Begin |
|||
a1 = {} |
|||
a2 = {} |
|||
Take(100,"Hola",0.056,"Mundo!"), and Push All(a1) |
|||
Take("Segundo",0,"array",~True,~False), and Push All(a2) |
|||
Concat (a1, a2) and Print ( a2, Newl ) |
|||
End |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Segundo,0,array,1,0,100,Hola,0.056,Mundo! |
|||
</pre> |
|||
=={{header|AntLang}}== |
|||
<syntaxhighlight lang="antlang">a:<1; <2; 3>> |
|||
b: <"Hello"; 42> |
|||
c: a,b</syntaxhighlight> |
|||
=={{header|Apex}}== |
|||
<syntaxhighlight lang="apex">List<String> listA = new List<String> { 'apple' }; |
|||
List<String> listB = new List<String> { 'banana' }; |
|||
listA.addAll(listB); |
|||
System.debug(listA); // Prints (apple, banana)</syntaxhighlight> |
|||
=={{header|APL}}== |
=={{header|APL}}== |
||
< |
<syntaxhighlight lang="apl"> |
||
1 2 3 , 4 5 6 |
1 2 3 , 4 5 6 |
||
1 2 3 4 5 6 |
1 2 3 4 5 6 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|AppleScript}}== |
|||
<syntaxhighlight lang="applescript"> |
|||
set listA to {1, 2, 3} |
|||
set listB to {4, 5, 6} |
|||
return listA & listB |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
{1, 2, 3, 4, 5, 6} |
|||
</pre> |
|||
Or, if we treat the concatenation of two lists as a special case of the more general problem of concatenating N lists, we can write: |
|||
{{trans|JavaScript}} |
|||
<syntaxhighlight lang="applescript">on run |
|||
concat([["alpha", "beta", "gamma"], ¬ |
|||
["delta", "epsilon", "zeta"], ¬ |
|||
["eta", "theta", "iota"]]) |
|||
end run |
|||
-- concat :: [[a]] -> [a] |
|||
on concat(xxs) |
|||
set lst to {} |
|||
repeat with xs in xxs |
|||
set lst to lst & xs |
|||
end repeat |
|||
return lst |
|||
end concat |
|||
</syntaxhighlight> |
|||
{{Out}} |
|||
<pre>{"alpha", "beta", "gamma", "delta", "epsilon", "zeta", "eta", "theta", "iota"}</pre> |
|||
=={{header|ARM Assembly}}== |
|||
{{works with|as|Raspberry Pi}} |
|||
<syntaxhighlight lang="arm assembly"> |
|||
/* ARM assembly Raspberry PI */ |
|||
/* program concAreaString.s */ |
|||
/* Constantes */ |
|||
.equ STDOUT, 1 @ Linux output console |
|||
.equ EXIT, 1 @ Linux syscall |
|||
.equ WRITE, 4 @ Linux syscall |
|||
.equ NBMAXITEMS, 20 @ |
|||
/* Initialized data */ |
|||
.data |
|||
szMessLenArea: .ascii "The length of area 3 is : " |
|||
sZoneconv: .fill 12,1,' ' |
|||
szCarriageReturn: .asciz "\n" |
|||
/* areas strings */ |
|||
szString1: .asciz "Apples" |
|||
szString2: .asciz "Oranges" |
|||
szString3: .asciz "Pommes" |
|||
szString4: .asciz "Raisins" |
|||
szString5: .asciz "Abricots" |
|||
/* pointer items area 1*/ |
|||
tablesPoi1: |
|||
pt1_1: .int szString1 |
|||
pt1_2: .int szString2 |
|||
ptVoid_1: .int 0 |
|||
/* pointer items area 2*/ |
|||
tablesPoi2: |
|||
pt2_1: .int szString3 |
|||
pt2_2: .int szString4 |
|||
pt2_3: .int szString5 |
|||
ptVoid_2: .int 0 |
|||
/* UnInitialized data */ |
|||
.bss |
|||
tablesPoi3: .skip 4 * NBMAXITEMS |
|||
/* code section */ |
|||
.text |
|||
.global main |
|||
main: /* entry of program */ |
|||
push {fp,lr} /* saves 2 registers */ |
|||
@ copy area 1 -> area 3 |
|||
ldr r1,iAdrtablesPoi1 @ begin pointer area 1 |
|||
ldr r3,iAdrtablesPoi3 @ begin pointer area 3 |
|||
mov r0,#0 @ counter |
|||
1: |
|||
ldr r2,[r1,r0,lsl #2] @ read string pointer address item r0 (4 bytes by pointer) |
|||
cmp r2,#0 @ is null ? |
|||
strne r2,[r3,r0,lsl #2] @ no store pointer in area 3 |
|||
addne r0,#1 @ increment counter |
|||
bne 1b @ and loop |
|||
@ copy area 2 -> area 3 |
|||
ldr r1,iAdrtablesPoi2 @ begin pointer area 2 |
|||
ldr r3,iAdrtablesPoi3 @ begin pointer area 3 |
|||
mov r4,#0 @ counter area 2 |
|||
2: @ r0 contains the first void item in area 3 |
|||
ldr r2,[r1,r4,lsl #2] @ read string pointer address item r0 (4 bytes by pointer) |
|||
cmp r2,#0 @ is null ? |
|||
strne r2,[r3,r0,lsl #2] @ no store pointer in area 3 |
|||
addne r0,#1 @ increment counter |
|||
addne r4,#1 @ increment counter |
|||
bne 2b @ and loop |
|||
@ count items number in area 3 |
|||
ldr r1,iAdrtablesPoi3 @ begin pointer table |
|||
mov r0,#0 @ counter |
|||
3: @ begin loop |
|||
ldr r2,[r1,r0,lsl #2] @ read string pointer address item r0 (4 bytes by pointer) |
|||
cmp r2,#0 @ is null ? |
|||
addne r0,#1 @ no increment counter |
|||
bne 3b @ and loop |
|||
ldr r1,iAdrsZoneconv @ conversion decimal |
|||
bl conversion10S |
|||
ldr r0,iAdrszMessLenArea |
|||
bl affichageMess |
|||
100: /* standard end of the program */ |
|||
mov r0, #0 @ return code |
|||
pop {fp,lr} @restaur 2 registers |
|||
mov r7, #EXIT @ request to exit program |
|||
swi 0 @ perform the system call |
|||
iAdrtablesPoi1: .int tablesPoi1 |
|||
iAdrtablesPoi2: .int tablesPoi2 |
|||
iAdrtablesPoi3: .int tablesPoi3 |
|||
iAdrszMessLenArea: .int szMessLenArea |
|||
iAdrsZoneconv: .int sZoneconv |
|||
iAdrszCarriageReturn: .int szCarriageReturn |
|||
/******************************************************************/ |
|||
/* display text with size calculation */ |
|||
/******************************************************************/ |
|||
/* r0 contains the address of the message */ |
|||
affichageMess: |
|||
push {fp,lr} /* save registres */ |
|||
push {r0,r1,r2,r7} /* save others registers */ |
|||
mov r2,#0 /* counter length */ |
|||
1: /* loop length calculation */ |
|||
ldrb r1,[r0,r2] /* read octet start position + index */ |
|||
cmp r1,#0 /* if 0 its over */ |
|||
addne r2,r2,#1 /* else add 1 in the length */ |
|||
bne 1b /* and loop */ |
|||
/* so here r2 contains the length of the message */ |
|||
mov r1,r0 /* address message in r1 */ |
|||
mov r0,#STDOUT /* code to write to the standard output Linux */ |
|||
mov r7, #WRITE /* code call system "write" */ |
|||
swi #0 /* call systeme */ |
|||
pop {r0,r1,r2,r7} /* restaur others registers */ |
|||
pop {fp,lr} /* restaur des 2 registres */ |
|||
bx lr /* return */ |
|||
/***************************************************/ |
|||
/* conversion register signed décimal */ |
|||
/***************************************************/ |
|||
/* r0 contient le registre */ |
|||
/* r1 contient l adresse de la zone de conversion */ |
|||
conversion10S: |
|||
push {r0-r5,lr} /* save des registres */ |
|||
mov r2,r1 /* debut zone stockage */ |
|||
mov r5,#'+' /* par defaut le signe est + */ |
|||
cmp r0,#0 /* nombre négatif ? */ |
|||
movlt r5,#'-' /* oui le signe est - */ |
|||
mvnlt r0,r0 /* et inversion en valeur positive */ |
|||
addlt r0,#1 |
|||
mov r4,#10 /* longueur de la zone */ |
|||
1: /* debut de boucle de conversion */ |
|||
bl divisionpar10 /* division */ |
|||
add r1,#48 /* ajout de 48 au reste pour conversion ascii */ |
|||
strb r1,[r2,r4] /* stockage du byte en début de zone r5 + la position r4 */ |
|||
sub r4,r4,#1 /* position précedente */ |
|||
cmp r0,#0 |
|||
bne 1b /* boucle si quotient different de zéro */ |
|||
strb r5,[r2,r4] /* stockage du signe à la position courante */ |
|||
subs r4,r4,#1 /* position précedente */ |
|||
blt 100f /* si r4 < 0 fin */ |
|||
/* sinon il faut completer le debut de la zone avec des blancs */ |
|||
mov r3,#' ' /* caractere espace */ |
|||
2: |
|||
strb r3,[r2,r4] /* stockage du byte */ |
|||
subs r4,r4,#1 /* position précedente */ |
|||
bge 2b /* boucle si r4 plus grand ou egal a zero */ |
|||
100: /* fin standard de la fonction */ |
|||
pop {r0-r5,lr} /*restaur desregistres */ |
|||
bx lr |
|||
/***************************************************/ |
|||
/* division par 10 signé */ |
|||
/* Thanks to http://thinkingeek.com/arm-assembler-raspberry-pi/* |
|||
/* and http://www.hackersdelight.org/ */ |
|||
/***************************************************/ |
|||
/* r0 contient le dividende */ |
|||
/* r0 retourne le quotient */ |
|||
/* r1 retourne le reste */ |
|||
divisionpar10: |
|||
/* r0 contains the argument to be divided by 10 */ |
|||
push {r2-r4} /* save registers */ |
|||
mov r4,r0 |
|||
ldr r3, .Ls_magic_number_10 /* r1 <- magic_number */ |
|||
smull r1, r2, r3, r0 /* r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0) */ |
|||
mov r2, r2, ASR #2 /* r2 <- r2 >> 2 */ |
|||
mov r1, r0, LSR #31 /* r1 <- r0 >> 31 */ |
|||
add r0, r2, r1 /* r0 <- r2 + r1 */ |
|||
add r2,r0,r0, lsl #2 /* r2 <- r0 * 5 */ |
|||
sub r1,r4,r2, lsl #1 /* r1 <- r4 - (r2 * 2) = r4 - (r0 * 10) */ |
|||
pop {r2-r4} |
|||
bx lr /* leave function */ |
|||
bx lr /* leave function */ |
|||
.Ls_magic_number_10: .word 0x66666667 |
|||
</syntaxhighlight> |
|||
=={{header|Arturo}}== |
|||
<syntaxhighlight lang="rebol">arr1: [1 2 3] |
|||
arr2: ["four" "five" "six"] |
|||
print arr1 ++ arr2</syntaxhighlight> |
|||
{{out}} |
|||
<pre>1 2 3 four five six</pre> |
|||
=={{header|ATS}}== |
|||
The following may seem frightening. However, it probably compiles down to two calls to __builtin_memcpy. All the complexity is to make sure those calls are done ''correctly''. |
|||
<syntaxhighlight lang="ats">(* The Rosetta Code array concatenation task, in ATS2. *) |
|||
(* In a way, the task is misleading: in a language such as ATS, one |
|||
can always devise a very-easy-to-use array type, put the code for |
|||
that in a library, and overload operators. Thus we can have |
|||
"array1 + array2" as array concatenation in ATS, complete with |
|||
garbage collection when the result no longer is needed. |
|||
It depends on what libraries are in one's repertoire. |
|||
Nevertheless, it seems fair to demonstrate how to concatenate two |
|||
barebones arrays at the nitpicking lowest level, without anything |
|||
but the barest contents of the ATS2 prelude. It will make ATS |
|||
programming look difficult; but ATS programming *is* difficult, |
|||
when you are using it to overcome the programming safety |
|||
deficiencies of a language such as C, without losing the runtime |
|||
efficiency of C code. |
|||
What we want is the kind of routine that would be used *in the |
|||
implementation* of "array1 + array2". So let us begin ... *) |
|||
#include "share/atspre_staload.hats" (* Loads some needed template |
|||
code. *) |
|||
fn {t : t@ype} |
|||
(* The demonstration will be for arrays of a non-linear type t. Were |
|||
the arrays to contain a *linear* type (vt@ype), then either the old |
|||
arrays would have to be destroyed or a copy procedure would be |
|||
needed for the elements. *) |
|||
arrayconcat1 {m, n : nat} |
|||
{pa, pb, pc : addr} |
|||
(pfa : !(@[t][m]) @ pa, |
|||
pfb : !(@[t][n]) @ pb, |
|||
pfc : !(@[t?][m + n]) @ pc >> @[t][m + n] @ pc | |
|||
pa : ptr pa, |
|||
pb : ptr pb, |
|||
pc : ptr pc, |
|||
m : size_t m, |
|||
n : size_t n) : void = |
|||
(* The routine takes as arguments three low-level arrays, passed by |
|||
value, as pointers with associated views. The first array is of |
|||
length m, with elements of type t, and the array must have been |
|||
initialized; the second is a similar array of length n. The third |
|||
array is uninitialized (thus the "?" character) and must have |
|||
length m+n; its type will change to "initialized". *) |
|||
{ |
|||
prval (pfleft, pfright) = array_v_split {t?} {pc} {m + n} {m} pfc |
|||
(* We have had to split the view of array c into a left part pfleft, |
|||
of length m, and a right part pfright of length n. Arrays a and b |
|||
will be copied into the respective parts of c. *) |
|||
val _ = array_copy<t> (!pc, !pa, m) |
|||
val _ = array_copy<t> (!(ptr_add<t> (pc, m)), !pb, n) |
|||
(* Copying an array *safely* is more complex than what we are doing |
|||
here, but above the task has been given to the "array_copy" |
|||
template in the prelude. The "!" signs appear because array_copy is |
|||
call-by-reference but we are passing it pointers. *) |
|||
(* pfleft and pfright now refer to *initialized* arrays: one of length |
|||
m, starting at address pc; the other of length n, starting at |
|||
address pc+(m*sizeof<t>). *) |
|||
prval _ = pfc := array_v_unsplit {t} {pc} {m, n} (pfleft, pfright) |
|||
(* Before we can exit, the view of array c has to be replaced. It is |
|||
replaced by "unsplitting" the (now initialized) left and right |
|||
parts of the array. *) |
|||
(* We are done. Everything should now work, and the result will be |
|||
safe from buffer overruns or underruns, and against accidental |
|||
misuse of uninitialized data. *) |
|||
} |
|||
(* arrayconcat2 is a pass-by-reference interface to arrayconcat1. *) |
|||
fn {t : t@ype} |
|||
arrayconcat2 {m, n : nat} |
|||
(a : &(@[t][m]), |
|||
b : &(@[t][n]), |
|||
c : &(@[t?][m + n]) >> @[t][m + n], |
|||
m : size_t m, |
|||
n : size_t n) : void = |
|||
arrayconcat1 (view@ a, view@ b, view@ c | |
|||
addr@ a, addr@ b, addr@ c, m, n) |
|||
(* Overloads to let you say "arrayconcat" for either routine above. *) |
|||
overload arrayconcat with arrayconcat1 |
|||
overload arrayconcat with arrayconcat2 |
|||
implement |
|||
main0 () = |
|||
(* A demonstration program. *) |
|||
let |
|||
(* Some arrays on the stack. Because they are on the stack, they |
|||
will not need explicit freeing. *) |
|||
var a = @[int][3] (1, 2, 3) |
|||
var b = @[int][4] (5, 6, 7, 8) |
|||
var c : @[int?][7] |
|||
in |
|||
(* Compute c as the concatenation of a and b. *) |
|||
arrayconcat<int> (a, b, c, i2sz 3, i2sz 4); |
|||
(* The following simply prints the result. *) |
|||
let |
|||
(* Copy c to a linear linked list, because the prelude provides |
|||
means to easily print such a list. *) |
|||
val lst = array2list (c, i2sz 7) |
|||
in |
|||
println! (lst); (* Print the list. *) |
|||
free lst (* The list is linear and must be freed. *) |
|||
end |
|||
end</syntaxhighlight> |
|||
{{out}} |
|||
<pre>$ patscc -O2 -DATS_MEMALLOC_LIBC arrayconcat.dats && ./a.out |
|||
1, 2, 3, 5, 6, 7, 8</pre> |
|||
Footnotes: |
|||
* The ATS prelude does in fact translate calls to array_copy into C calls to memcpy. On a GNU system, the memcpy calls will likely become calls to __builtin_memcpy. The prelude's implementation is a practical one, rather than a strict demonstration of ATS methods. |
|||
* The "-DATS_MEMALLOC_LIBC" is needed due to the copying of an array to a linear linked list, which has to be both malloc'd and free'd. The arrays themselves are allocated on the stack, in this example. |
|||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
=== True Arrays === |
=== True Arrays === |
||
{{works with|AutoHotkey_L}} |
{{works with|AutoHotkey_L}} |
||
< |
<syntaxhighlight lang="ahk">List1 := [1, 2, 3] |
||
List2 := [4, 5, 6] |
List2 := [4, 5, 6] |
||
cList := Arr_concatenate(List1, List2) |
cList := Arr_concatenate(List1, List2) |
||
Line 83: | Line 788: | ||
res .= ", " value |
res .= ", " value |
||
return "[" SubStr(res, 3) "]" |
return "[" SubStr(res, 3) "]" |
||
}</ |
}</syntaxhighlight> |
||
=== Legacy versions === |
=== Legacy versions === |
||
[[AutoHotkey_Basic]] does not have real Arrays, but the user can implement them quite easily. For example: |
[[AutoHotkey_Basic]] does not have real Arrays, but the user can implement them quite easily. For example: |
||
< |
<syntaxhighlight lang="autohotkey">List1 = 1,2,3 |
||
List2 = 4,5,6 |
List2 = 4,5,6 |
||
Line 122: | Line 827: | ||
List .= (A_Index = 1 ? "" : ",") %Array%%A_Index% |
List .= (A_Index = 1 ? "" : ",") %Array%%A_Index% |
||
Return, List |
Return, List |
||
}</ |
}</syntaxhighlight> |
||
Message box shows: |
Message box shows: |
||
<pre>1,2,3,4,5,6</pre> |
<pre>1,2,3,4,5,6</pre> |
||
Line 132: | Line 837: | ||
<syntaxhighlight lang="autoit"> |
|||
<lang AutoIt> |
|||
_ArrayConcatenate($avArray, $avArray2) |
_ArrayConcatenate($avArray, $avArray2) |
||
Func _ArrayConcatenate(ByRef $avArrayTarget, Const ByRef $avArraySource, $iStart = 0) |
Func _ArrayConcatenate(ByRef $avArrayTarget, Const ByRef $avArraySource, $iStart = 0) |
||
Line 151: | Line 856: | ||
Return $iUBoundTarget + $iUBoundSource |
Return $iUBoundTarget + $iUBoundSource |
||
EndFunc ;==>_ArrayConcatenate |
EndFunc ;==>_ArrayConcatenate |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Avail}}== |
|||
<syntaxhighlight lang="avail"><1, 2, 3> ++ <¢a, ¢b, ¢c></syntaxhighlight> |
|||
=={{header|AWK}}== |
=={{header|AWK}}== |
||
< |
<syntaxhighlight lang="awk">#!/usr/bin/awk -f |
||
BEGIN { |
BEGIN { |
||
split("cul-de-sac",a,"-") |
split("cul-de-sac",a,"-") |
||
Line 165: | Line 873: | ||
} |
} |
||
function concat_array(a,b,c) { |
function concat_array(a,b,c, nc) { |
||
for (i in a) { |
for (i in a) { |
||
c[++nc]=a[i] |
c[++nc]=a[i] |
||
Line 172: | Line 880: | ||
c[++nc]=b[i] |
c[++nc]=b[i] |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Babel}}== |
=={{header|Babel}}== |
||
< |
<syntaxhighlight lang="babel">[1 2 3] [4 5 6] cat ;</syntaxhighlight> |
||
{{Out}} |
|||
<pre>[val 0x1 0x2 0x3 0x4 0x5 0x6 ]</pre> |
|||
=={{header|bash}}== |
=={{header|bash}}== |
||
< |
<syntaxhighlight lang="bash">x=("1 2" "3 4") |
||
y=(5 6) |
y=(5 6) |
||
sum=( "${x[@]}" "${y[@]}" ) |
sum=( "${x[@]}" "${y[@]}" ) |
||
Line 186: | Line 897: | ||
3 4 |
3 4 |
||
5 |
5 |
||
6</ |
6</syntaxhighlight> |
||
=={{header| |
=={{header|BASIC}}== |
||
==={{header|Applesoft BASIC}}=== |
|||
{{works with|Chipmunk Basic}} |
|||
<syntaxhighlight lang="gwbasic"> 10 LET X = 4:Y = 5 |
|||
20 DIM A(X - 1),B(Y - 1),C(X + Y - 1) |
|||
30 FOR I = 1 TO X:A(I - 1) = I: NEXT |
|||
40 FOR I = 1 TO Y:B(I - 1) = I * 10: NEXT |
|||
50 FOR I = 1 TO X:C(I - 1) = A(I - 1): NEXT |
|||
60 FOR I = 1 TO Y:C(X + I - 1) = B(I - 1): NEXT |
|||
70 FOR I = 1 TO X + Y: PRINT MID$ (" ",1,I > 1)C(I - 1);: NEXT</syntaxhighlight> |
|||
==={{header|Chipmunk Basic}}=== |
|||
{{works with|Chipmunk Basic|3.6.4}} |
|||
The [[#GW-BASIC|GW-BASIC]] solution works without any changes. |
|||
==={{header|GW-BASIC}}=== |
|||
{{works with|PC-BASIC|any}} |
|||
{{works with|BASICA}} |
|||
{{works with|Chipmunk Basic}} |
|||
{{works with|QBasic}} |
|||
{{works with|MSX BASIC}} |
|||
<syntaxhighlight lang="qbasic">100 U1 = 3: U2 = 4 |
|||
110 DIM A$(3) |
|||
120 DATA "The","quick","brown","fox" |
|||
130 FOR I = 0 TO U1 : READ A$(I) : NEXT I |
|||
140 DIM B$(4) |
|||
150 DATA "jumped","over","the","lazy","dog" |
|||
160 FOR I = 0 TO U2 : READ B$(I) : NEXT I |
|||
170 'SU2 ConcatArrays |
|||
180 X = U1 + 1 |
|||
190 Y = U2 + 1 |
|||
200 Z = X + Y |
|||
210 DIM C$(Z-1) |
|||
220 FOR I = 0 TO X-1 |
|||
230 C$(I) = A$(I) |
|||
240 NEXT I |
|||
250 FOR I = 0 TO Y-1 |
|||
260 C$(U1+I+1) = B$(I) |
|||
270 NEXT I |
|||
280 ' |
|||
290 FOR I = 0 TO Z-1 |
|||
300 PRINT C$(I); " "; |
|||
310 NEXT I |
|||
320 END</syntaxhighlight> |
|||
==={{header|Minimal BASIC}}=== |
|||
{{trans|Applesoft BASIC}} |
|||
{{works with|GW-BASIC}} |
|||
{{works with|Chipmunk Basic}} |
|||
{{works with|QBasic}} |
|||
{{works with|Quite BASIC}} |
|||
{{works with|MSX BASIC}} |
|||
<syntaxhighlight lang="qbasic">10 LET X = 4 |
|||
20 LET Y = 5 |
|||
30 DIM A(3) |
|||
40 DIM B(4) |
|||
50 DIM C(8) |
|||
60 FOR I = 1 TO X |
|||
70 LET A(I-1) = I |
|||
80 NEXT I |
|||
90 FOR I = 1 TO Y |
|||
100 LET B(I-1) = I*10 |
|||
110 NEXT I |
|||
120 FOR I = 1 TO X |
|||
130 LET C(I-1) = A(I-1) |
|||
140 NEXT I |
|||
150 FOR I = 1 TO Y |
|||
160 LET C(X+I-1) = B(I-1) |
|||
170 NEXT I |
|||
180 FOR I = 1 TO X+Y |
|||
190 PRINT C(I-1); |
|||
200 NEXT I |
|||
210 END</syntaxhighlight> |
|||
==={{header|MSX Basic}}=== |
|||
{{works with|MSX BASIC|any}} |
|||
The [[#GW-BASIC|GW-BASIC]] solution works without any changes. |
|||
==={{header|Quite BASIC}}=== |
|||
{{trans|GW-BASIC}} |
|||
<syntaxhighlight lang="qbasic">100 LET U1 = 3 |
|||
105 LET U2 = 4 |
|||
110 ARRAY A$ |
|||
120 DATA "The","quick","brown","fox" |
|||
130 FOR I = 0 TO U1 : READ A$(I) : NEXT I |
|||
140 ARRAY B$ |
|||
150 DATA "jumped","over","the","lazy","dog" |
|||
160 FOR I = 0 TO U2 : READ B$(I) : NEXT I |
|||
170 rem Sub ConcatArrays |
|||
180 LET X = U1 + 1 |
|||
190 LET Y = U2 + 1 |
|||
200 LET Z = X + Y |
|||
210 ARRAY C |
|||
220 FOR I = 0 TO X-1 |
|||
230 LET C$(I) = A$(I) |
|||
240 NEXT I |
|||
250 FOR I = 0 TO Y-1 |
|||
260 LET C$(U1 + I + 1) = B$(I) |
|||
270 NEXT I |
|||
280 rem |
|||
290 FOR I = 0 TO Z-1 |
|||
300 PRINT C$(I);" "; |
|||
310 NEXT I |
|||
320 END</syntaxhighlight> |
|||
==={{header|BaCon}}=== |
|||
<syntaxhighlight lang="bacon">DECLARE a[] = { 1, 2, 3, 4, 5 } |
|||
DECLARE b[] = { 6, 7, 8, 9, 10 } |
|||
DECLARE c ARRAY UBOUND(a) + UBOUND(b) |
|||
FOR x = 0 TO 4 |
|||
c[x] = a[x] |
|||
c[x+5] = b[x] |
|||
NEXT</syntaxhighlight> |
|||
==={{header|BBC BASIC}}=== |
|||
{{works with|BBC BASIC for Windows}} |
{{works with|BBC BASIC for Windows}} |
||
< |
<syntaxhighlight lang="bbcbasic"> DIM a(3), b(4) |
||
a() = 1, 2, 3, 4 |
a() = 1, 2, 3, 4 |
||
b() = 5, 6, 7, 8, 9 |
b() = 5, 6, 7, 8, 9 |
||
Line 208: | Line 1,035: | ||
SYS "RtlMoveMemory", ^c(0), ^a(0), s%*na% |
SYS "RtlMoveMemory", ^c(0), ^a(0), s%*na% |
||
SYS "RtlMoveMemory", ^c(na%), ^b(0), s%*nb% |
SYS "RtlMoveMemory", ^c(na%), ^b(0), s%*nb% |
||
ENDPROC</ |
ENDPROC</syntaxhighlight> |
||
==={{header|Commodore BASIC}}=== |
|||
(Based on ZX Spectrum BASIC version) |
|||
<syntaxhighlight lang="basic">10 X=4 : Y=5 |
|||
20 DIM A(X) : DIM B(Y) : DIM C(X+Y) |
|||
30 FOR I=1 TO X |
|||
40 : A(I) = I |
|||
50 NEXT |
|||
60 FOR I=1 TO Y |
|||
70 : B(I) = I*10 |
|||
80 NEXT |
|||
90 FOR I=1 TO X |
|||
100 : C(I) = A(I) |
|||
110 NEXT |
|||
120 FOR I=1 TO Y |
|||
130 : C(X+I) = B(I) |
|||
140 NEXT |
|||
150 FOR I=1 TO X+Y |
|||
160 : PRINT C(I); |
|||
170 NEXT</syntaxhighlight> |
|||
==={{header|Run BASIC}}=== |
|||
{{works with|Just BASIC}} |
|||
{{works with|Liberty BASIC}} |
|||
The [[#Liberty BASIC|Liberty BASIC]] solution works without any changes. |
|||
=={{header|BASIC256}}== |
|||
<syntaxhighlight lang="basic256">arraybase 1 |
|||
global c |
|||
dimen = 5 |
|||
dim a(dimen) |
|||
dim b(dimen) |
|||
# Array initialization |
|||
for i = 1 to dimen |
|||
a[i] = i |
|||
b[i] = i + dimen |
|||
next i |
|||
nt = ConcatArrays(a, b) |
|||
for i = 1 to nt |
|||
print c[i]; |
|||
if i < nt then print ", "; |
|||
next i |
|||
end |
|||
function ConcatArrays(a, b) |
|||
ta = a[?] |
|||
tb = b[?] |
|||
nt = ta + tb |
|||
redim c(nt) |
|||
for i = 1 to ta |
|||
c[i] = a[i] |
|||
next i |
|||
for i = 1 to tb |
|||
c[i + ta] = b[i] |
|||
next i |
|||
return nt |
|||
end function</syntaxhighlight> |
|||
{{out}} |
|||
<pre>1, 2, 3, 4, 5, 6, 7, 8, 9, 10</pre> |
|||
=={{header|Binary Lambda Calculus}}== |
|||
BLC uses lists instead of arrays. List concatenation is (see also https://github.com/tromp/AIT/blob/master/lists/cat.lam) |
|||
<pre>00011001000110100000000000010110111100101111001111110111110110</pre> |
|||
=={{header|BQN}}== |
|||
<syntaxhighlight lang="bqn">1‿2‿3 ∾ 4‿5‿6</syntaxhighlight> |
|||
=={{header|Bracmat}}== |
=={{header|Bracmat}}== |
||
Line 232: | Line 1,133: | ||
=={{header|Burlesque}}== |
=={{header|Burlesque}}== |
||
< |
<syntaxhighlight lang="burlesque"> |
||
blsq ) {1 2 3}{4 5 6}_+ |
blsq ) {1 2 3}{4 5 6}_+ |
||
{1 2 3 4 5 6} |
{1 2 3 4 5 6} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|C}}== |
=={{header|C}}== |
||
A way to concatenate two C arrays when you know their size (and usually so it is) |
A way to concatenate two C arrays when you know their size (and usually so it is) |
||
< |
<syntaxhighlight lang="c">#include <stdlib.h> |
||
#include <stdio.h> |
#include <stdio.h> |
||
#include <string.h> |
#include <string.h> |
||
Line 270: | Line 1,171: | ||
free(c); |
free(c); |
||
return EXIT_SUCCCESS; |
return EXIT_SUCCCESS; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|C sharp|C#}}== |
|||
<syntaxhighlight lang="csharp">using System; |
|||
namespace RosettaCode |
|||
{ |
|||
class Program |
|||
{ |
|||
static void Main(string[] args) |
|||
{ |
|||
int[] a = { 1, 2, 3 }; |
|||
int[] b = { 4, 5, 6 }; |
|||
int[] c = new int[a.Length + b.Length]; |
|||
a.CopyTo(c, 0); |
|||
b.CopyTo(c, a.Length); |
|||
foreach(int n in c) |
|||
{ |
|||
Console.WriteLine(n.ToString()); |
|||
} |
|||
} |
|||
} |
|||
}</syntaxhighlight> |
|||
Alternatively, using LINQ extension methods: |
|||
{{works with|C sharp|C#|3}} |
|||
<syntaxhighlight lang="csharp">using System.Linq; |
|||
class Program |
|||
{ |
|||
static void Main(string[] args) |
|||
{ |
|||
int[] a = { 1, 2, 3 }; |
|||
int[] b = { 4, 5, 6 }; |
|||
int[] c = a.Concat(b).ToArray(); |
|||
} |
|||
}</syntaxhighlight> |
|||
=={{header|C++}}== |
=={{header|C++}}== |
||
< |
<syntaxhighlight lang="cpp">#include <vector> |
||
#include <iostream> |
#include <iostream> |
||
Line 286: | Line 1,227: | ||
for (int i = 0; i < a.size(); ++i) |
for (int i = 0; i < a.size(); ++i) |
||
std::cout << "a[" << i << "] = " << a[i] << "\n"; |
std::cout << "a[" << i << "] = " << a[i] << "\n"; |
||
}</ |
}</syntaxhighlight> |
||
{{works with|C++11}} |
{{works with|C++11}} |
||
Similar to above but using initialization schematics. |
Similar to above but using initialization schematics. |
||
< |
<syntaxhighlight lang="cpp">#include <vector> |
||
#include <iostream> |
#include <iostream> |
||
Line 303: | Line 1,244: | ||
std::cout << std::endl; |
std::cout << std::endl; |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
This is another solution with function level templates and pointers. |
|||
=={{header|C sharp}}== |
|||
<lang csharp>using System; |
|||
<syntaxhighlight lang="cpp">#include <iostream> |
|||
namespace RosettaCode |
|||
{ |
|||
class Program |
|||
{ |
|||
static void Main(string[] args) |
|||
{ |
|||
int[] a = { 1, 2, 3 }; |
|||
int[] b = { 4, 5, 6 }; |
|||
using namespace std; |
|||
int[] c = new int[a.Length + b.Length]; |
|||
a.CopyTo(c, 0); |
|||
b.CopyTo(c, a.Length); |
|||
template <typename T1, typename T2> |
|||
foreach(int n in c) |
|||
int* concatArrays( T1& array_1, T2& array_2) { |
|||
{ |
|||
int arrayCount_1 = sizeof(array_1) / sizeof(array_1[0]); |
|||
Console.WriteLine(n.ToString()); |
|||
int arrayCount_2 = sizeof(array_2) / sizeof(array_2[0]); |
|||
} |
|||
int newArraySize = arrayCount_1 + arrayCount_2; |
|||
} |
|||
} |
|||
}</lang> |
|||
int *p = new int[newArraySize]; |
|||
Alternatively, using LINQ extension methods: |
|||
for (int i = 0; i < arrayCount_1; i++) { |
|||
{{works with|C sharp|C#|3}} |
|||
p[i] = array_1[i]; |
|||
<lang csharp>using System.Linq; |
|||
} |
|||
for (int i = arrayCount_1; i < newArraySize; i++) { |
|||
class Program |
|||
int newIndex = i-arrayCount_2; |
|||
{ |
|||
static void Main(string[] args) |
|||
{ |
|||
int[] a = { 1, 2, 3 }; |
|||
int[] b = { 4, 5, 6 }; |
|||
if (newArraySize % 2 == 1) |
|||
int[] c = a.Concat(b).ToArray(); |
|||
newIndex--; |
|||
} |
|||
}</lang> |
|||
p[i] = array_2[newIndex]; |
|||
cout << "i: " << i << endl; |
|||
cout << "array_2[i]: " << array_2[newIndex] << endl; |
|||
cout << endl; |
|||
} |
|||
return p; |
|||
} |
|||
int main() { |
|||
int ary[4] = {1, 2, 3, 123}; |
|||
int anotherAry[3] = {4, 5, 6}; |
|||
int *r = concatArrays(ary, anotherAry); |
|||
cout << *(r + 0) << endl; |
|||
cout << *(r + 1) << endl; |
|||
cout << *(r + 2) << endl; |
|||
cout << *(r + 3) << endl; |
|||
cout << *(r + 4) << endl; |
|||
cout << *(r + 5) << endl; |
|||
cout << *(r + 6) << endl; |
|||
delete r; |
|||
return 0; |
|||
}</syntaxhighlight> |
|||
=={{header|Ceylon}}== |
|||
<syntaxhighlight lang="ceylon">shared void arrayConcatenation() { |
|||
value a = Array {1, 2, 3}; |
|||
value b = Array {4, 5, 6}; |
|||
value c = concatenate(a, b); |
|||
print(c); |
|||
}</syntaxhighlight> |
|||
=={{header|Clojure}}== |
=={{header|Clojure}}== |
||
< |
<syntaxhighlight lang="clojure">(concat [1 2 3] [4 5 6])</syntaxhighlight> |
||
The inputs can be any collection, including Java arrays, and returns a lazy sequence of the elements. |
The inputs can be any collection, including Java arrays, and returns a lazy sequence of the elements. |
||
A vector is the closest Clojure thing to an array. If a vector is wanted, then use |
|||
<syntaxhighlight lang="clojure">(into [1 2 3] [4 5 6])</syntaxhighlight> |
|||
=={{header|COBOL}}== |
|||
{{works with|COBOL 2014}} |
|||
<syntaxhighlight lang="cobolfree">IDENTIFICATION DIVISION. |
|||
PROGRAM-ID. array-concat. |
|||
DATA DIVISION. |
|||
WORKING-STORAGE SECTION. |
|||
01 table-one. |
|||
05 int-field PIC 999 OCCURS 0 TO 5 TIMES DEPENDING ON t1. |
|||
01 table-two. |
|||
05 int-field PIC 9(4) OCCURS 0 TO 10 TIMES DEPENDING ON t2. |
|||
77 tally USAGE IS INDEX. |
|||
77 t1 PIC 99. |
|||
77 t2 PIC 99. |
|||
77 show PIC Z(4) USAGE IS DISPLAY. |
|||
PROCEDURE DIVISION. |
|||
array-concat-main. |
|||
PERFORM initialize-tables |
|||
PERFORM concatenate-tables |
|||
PERFORM display-result |
|||
GOBACK. |
|||
initialize-tables. |
|||
MOVE 4 TO t1 |
|||
PERFORM VARYING tally FROM 1 BY 1 UNTIL tally > t1 |
|||
COMPUTE int-field OF table-one(tally) = tally * 3 |
|||
END-PERFORM |
|||
MOVE 3 TO t2 |
|||
PERFORM VARYING tally FROM 1 BY 1 UNTIL tally > t2 |
|||
COMPUTE int-field OF table-two(tally) = tally * 6 |
|||
END-PERFORM. |
|||
concatenate-tables. |
|||
PERFORM VARYING tally FROM 1 BY 1 UNTIL tally > t1 |
|||
ADD 1 TO t2 |
|||
MOVE int-field OF table-one(tally) |
|||
TO int-field OF table-two(t2) |
|||
END-PERFORM. |
|||
display-result. |
|||
PERFORM VARYING tally FROM 1 BY 1 UNTIL tally = t2 |
|||
MOVE int-field OF table-two(tally) TO show |
|||
DISPLAY FUNCTION TRIM(show) ", " WITH NO ADVANCING |
|||
END-PERFORM |
|||
MOVE int-field OF table-two(tally) TO show |
|||
DISPLAY FUNCTION TRIM(show). |
|||
END PROGRAM array-concat.</syntaxhighlight> |
|||
{{out}} |
|||
<pre>$ cobc -xjd array-concatenation.cob --std=cobol2014 # COBOL 2014 needed for FUNCTION TRIM |
|||
6, 12, 18, 3, 6, 9, 12 |
|||
</pre> |
|||
=={{header|CoffeeScript}}== |
=={{header|CoffeeScript}}== |
||
< |
<syntaxhighlight lang="coffeescript"> |
||
# like in JavaScript |
# like in JavaScript |
||
a = [1, 2, 3] |
a = [1, 2, 3] |
||
b = [4, 5, 6] |
b = [4, 5, 6] |
||
c = a.concat b |
c = a.concat b |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
<code>[http://www.lispworks.com/documentation/HyperSpec/Body/f_concat.htm concatenate]</code> is a general function for concatenating any type of sequence. It takes the type of sequence to produce, followed by any number of sequences of any type. |
<code>[http://www.lispworks.com/documentation/HyperSpec/Body/f_concat.htm concatenate]</code> is a general function for concatenating any type of sequence. It takes the type of sequence to produce, followed by any number of sequences of any type. |
||
< |
<syntaxhighlight lang="lisp">(concatenate 'vector #(0 1 2 3) #(4 5 6 7)) |
||
=> #(0 1 2 3 4 5 6 7)</ |
=> #(0 1 2 3 4 5 6 7)</syntaxhighlight> |
||
===Alternate solution=== |
|||
I use [https://franz.com/downloads/clp/survey Allegro CL 10.1] |
|||
<syntaxhighlight lang="lisp"> |
|||
(setf arr1 (make-array '(3) :initial-contents '(1 2 3))) |
|||
(setf arr2 (make-array '(3) :initial-contents '(4 5 6))) |
|||
(setf arr3 (make-array '(3) :initial-contents '(7 8 9))) |
|||
(setf arr4 (make-array '(6))) |
|||
(setf arr5 (make-array '(9))) |
|||
(setf arr4 (concatenate `(vector ,(array-element-type arr1)) arr1 arr2)) |
|||
(format t "~a" "concatenate arr1 and arr2: ") |
|||
(write arr4) |
|||
(terpri) |
|||
(setf arr5 (concatenate `(vector ,(array-element-type arr1)) arr4 arr3)) |
|||
(format t "~a" "concatenate arr4 and arr3: ") |
|||
(write arr5) |
|||
(terpri) |
|||
</syntaxhighlight> |
|||
Output: |
|||
<pre> |
|||
concatenate arr1 and arr2: #(1 2 3 4 5 6) |
|||
concatenate arr4 and arr3: #(1 2 3 4 5 6 7 8 9) |
|||
</pre> |
|||
=={{header|Component Pascal}}== |
=={{header|Component Pascal}}== |
||
BlackBox Component Builder |
BlackBox Component Builder |
||
< |
<syntaxhighlight lang="oberon2"> |
||
MODULE ArrayConcat; |
MODULE ArrayConcat; |
||
IMPORT StdLog; |
IMPORT StdLog; |
||
Line 421: | Line 1,462: | ||
END ArrayConcat. |
END ArrayConcat. |
||
</syntaxhighlight> |
|||
</lang> |
|||
Execute: ^Q ArrayConcat.Do <br/> |
Execute: ^Q ArrayConcat.Do <br/> |
||
{{out}} |
|||
Output: |
|||
<pre> |
<pre> |
||
1> [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] |
1> [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] |
||
Line 430: | Line 1,471: | ||
</pre> |
</pre> |
||
=={{header|Crystal}}== |
|||
<syntaxhighlight lang="ruby">arr1 = [1, 2, 3] |
|||
arr2 = ["foo", "bar", "baz"] |
|||
arr1 + arr2 #=> [1, 2, 3, "foo", "bar", "baz"]</syntaxhighlight> |
|||
=={{header|D}}== |
=={{header|D}}== |
||
< |
<syntaxhighlight lang="d">import std.stdio: writeln; |
||
void main() { |
void main() { |
||
Line 438: | Line 1,485: | ||
writeln(a, " ~ ", b, " = ", a ~ b); |
writeln(a, " ~ ", b, " = ", a ~ b); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
|||
Output: |
|||
<pre>[1, 2] ~ [4, 5, 6] = [1, 2, 4, 5, 6]</pre> |
<pre>[1, 2] ~ [4, 5, 6] = [1, 2, 4, 5, 6]</pre> |
||
=={{header|Delphi}}== |
=={{header|Delphi}}== |
||
2022/07/13 |
|||
<lang delphi>type |
|||
<syntaxhighlight lang="delphi"> |
|||
// This example works on stuff as old as Delphi 5 (maybe older) |
|||
// Modern Delphi / Object Pascal has both |
|||
// • generic types |
|||
// • the ability to concatenate arrays with the '+' operator |
|||
// So I could just say: |
|||
// myarray := [1] + [2, 3]; |
|||
// But if you do not have access to the latest/greatest, then: |
|||
{$apptype console} |
|||
type |
|||
// Array types must be declared in order to return them from functions |
|||
// They can also be used with open array parameters. |
|||
TArrayOfString = array of string; |
|||
function Concat( a, b : array of string ): TArrayOfString; overload; |
|||
{ |
|||
Every array type needs its own 'Concat' function: |
|||
function Concat( a, b : array of integer ): TArrayOfInteger; overload; |
|||
function Concat( a, b : array of double ): TArrayOfDouble; overload; |
|||
etc |
|||
Also, dynamic and open array types ALWAYS start at 0. No need to complicate indexing here. |
|||
} |
|||
var |
|||
n : Integer; |
|||
begin |
|||
SetLength( result, Length(a)+Length(b) ); |
|||
for n := 0 to High(a) do result[ n] := a[n]; |
|||
for n := 0 to High(b) do result[Length(a)+n] := b[n] |
|||
end; |
|||
// Example time! |
|||
function Join( a : array of string; sep : string = ' ' ): string; |
|||
var |
|||
n : integer; |
|||
begin |
|||
if Length(a) > 0 then result := a[0]; |
|||
for n := 1 to High(a) do result := result + sep + a[n] |
|||
end; |
|||
var |
|||
names : TArrayOfString; |
|||
begin |
|||
// Here we use the open array parameter constructor as a convenience |
|||
names := Concat( ['Korra', 'Asami'], ['Bolin', 'Mako'] ); |
|||
WriteLn( Join(names) ); |
|||
// Also convenient: open array parameters are assignment-compatible with our array type! |
|||
names := Concat( names, ['Varrick', 'Zhu Li'] ); |
|||
WriteLn( #13#10, Join(names, ', ') ); |
|||
names := Concat( ['Tenzin'], names ); |
|||
Writeln( #13#10, Join(names, #13#10 ) ); |
|||
end. |
|||
</syntaxhighlight> |
|||
Output: |
|||
Korra Asami Bolin Mako |
|||
Korra, Asami, Bolin, Mako, Varrick, Zhu Li |
|||
Tenzin |
|||
Korra |
|||
Asami |
|||
Bolin |
|||
Mako |
|||
Varrick |
|||
Zhu Li |
|||
<br> |
|||
What follows is older content found on this page.<br> |
|||
It has running commentary about memory management that isn’t exactly correct.<br> |
|||
Delphi handles dynamic array memory very well. |
|||
<syntaxhighlight lang="delphi">type |
|||
TReturnArray = array of integer; //you need to define a type to be able to return it |
TReturnArray = array of integer; //you need to define a type to be able to return it |
||
Line 480: | Line 1,600: | ||
Finalize(r1); //IMPORTANT! |
Finalize(r1); //IMPORTANT! |
||
ShowMessage(IntToStr(High(r1))); |
ShowMessage(IntToStr(High(r1))); |
||
end;</ |
end;</syntaxhighlight> |
||
=={{header|Diego}}== |
|||
<syntaxhighlight lang="diego">set_namespace(rosettacode)_me(); |
|||
add_ary(a)_values(1,2,3); |
|||
add_ary(b)_values(4,5,6); |
|||
me_msg()_ary[a]_concat[b] |
|||
me_msg()_ary[a]_concat()_ary[b]; // alternative |
|||
me_msg()_calc([a]+[b]); // alternative |
|||
reset_namespace[];</syntaxhighlight> |
|||
=={{header|Dyalect}}== |
|||
<syntaxhighlight lang="dyalect">var xs = [1,2,3] |
|||
var ys = [4,5,6] |
|||
var alls = Array.Concat(xs, ys) |
|||
print(alls)</syntaxhighlight> |
|||
{{out}} |
|||
<pre>[1, 2, 3, 4, 5, 6]</pre> |
|||
=={{header|E}}== |
=={{header|E}}== |
||
< |
<syntaxhighlight lang="e">? [1,2] + [3,4] |
||
# value: [1, 2, 3, 4]</ |
# value: [1, 2, 3, 4]</syntaxhighlight> |
||
=={{header|EasyLang}}== |
|||
<syntaxhighlight lang="text">a[] = [ 1 2 3 ] |
|||
b[] = [ 4 5 6 ] |
|||
c[] = a[] |
|||
for h in b[] |
|||
c[] &= h |
|||
. |
|||
print c[]</syntaxhighlight> |
|||
=={{header|EchoLisp}}== |
|||
The native operators are '''append''' for lists, and '''vector-append''' for vectors (1-dim arrays). |
|||
<syntaxhighlight lang="scheme"> |
|||
;;;; VECTORS |
|||
(vector-append (make-vector 6 42) (make-vector 4 666)) |
|||
→ #( 42 42 42 42 42 42 666 666 666 666) |
|||
;;;; LISTS |
|||
(append (iota 5) (iota 6)) |
|||
→ (0 1 2 3 4 0 1 2 3 4 5) |
|||
;; NB - append may also be used with sequences (lazy lists) |
|||
(lib 'sequences) |
|||
(take (append [1 .. 7] [7 6 .. 0]) #:all) |
|||
→ (1 2 3 4 5 6 7 6 5 4 3 2 1) |
|||
</syntaxhighlight> |
|||
=={{header|ECL}}== |
=={{header|ECL}}== |
||
<lang> |
<syntaxhighlight lang="text"> |
||
A := [1, 2, 3, 4]; |
A := [1, 2, 3, 4]; |
||
B := [5, 6, 7, 8]; |
B := [5, 6, 7, 8]; |
||
C := A + B;</ |
C := A + B;</syntaxhighlight> |
||
=={{header|Ecstasy}}== |
|||
It is as simple as <code><var>array1</var> + <var>array2</var></code>: |
|||
<syntaxhighlight lang="java">String[] fruits = ["apples", "oranges"]; |
|||
String[] grains = ["wheat", "corn"]; |
|||
String[] all = fruits + grains;</syntaxhighlight> |
|||
=={{header|Efene}}== |
=={{header|Efene}}== |
||
Line 501: | Line 1,676: | ||
using the ++ operator and the lists.append function |
using the ++ operator and the lists.append function |
||
< |
<syntaxhighlight lang="efene"> |
||
@public |
@public |
||
run = fn () { |
run = fn () { |
||
Line 512: | Line 1,687: | ||
io.format("~p~n", [C]) |
io.format("~p~n", [C]) |
||
io.format("~p~n", [D]) |
io.format("~p~n", [D]) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|EGL}}== |
=={{header|EGL}}== |
||
{{works with|EDT}} |
{{works with|EDT}} |
||
<syntaxhighlight lang="egl"> |
|||
<lang EGL> |
|||
program ArrayConcatenation |
program ArrayConcatenation |
||
function main() |
function main() |
||
Line 530: | Line 1,705: | ||
end |
end |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Ela}}== |
|||
<syntaxhighlight lang="ela">xs = [1,2,3] |
|||
ys = [4,5,6] |
|||
xs ++ ys</syntaxhighlight> |
|||
{{out}}<pre>[1,2,3,4,5,6]</pre> |
|||
=={{header|Elena}}== |
=={{header|Elena}}== |
||
ELENA 5.0 : |
|||
<lang elena>#define extensions. |
|||
<syntaxhighlight lang="elena">import extensions; |
|||
public program() |
|||
{ |
|||
[ |
|||
var a := new int[]{1,2,3}; |
|||
var b := new int[]{4,5}; |
|||
console.printLine( |
|||
"(",a.asEnumerable(),") + (",b.asEnumerable(), |
|||
") = (",(a + b).asEnumerable(),")").readChar(); |
|||
}</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
(1,2,3) + (4,5) = (1,2,3,4,5) |
|||
</pre> |
|||
=={{header|Elixir}}== |
|||
<syntaxhighlight lang="elixir">iex(1)> [1, 2, 3] ++ [4, 5, 6] |
|||
[1, 2, 3, 4, 5, 6] |
|||
iex(2)> Enum.concat([[1, [2], 3], [4], [5, 6]]) |
|||
[1, [2], 3, 4, 5, 6] |
|||
iex(3)> Enum.concat([1..3, [4,5,6], 7..9]) |
|||
[1, 2, 3, 4, 5, 6, 7, 8, 9]</syntaxhighlight> |
|||
=={{header|Elm}}== |
|||
<syntaxhighlight lang="elm">import Element exposing (show, toHtml) -- elm-package install evancz/elm-graphics |
|||
import Html.App exposing (beginnerProgram) |
|||
import Array exposing (Array, append, initialize) |
|||
xs : Array Int |
|||
xs = |
|||
initialize 3 identity -- [0, 1, 2] |
|||
ys : Array Int |
|||
ys = |
|||
initialize 3 <| (+) 3 -- [3, 4, 5] |
|||
main = beginnerProgram { model = () |
|||
, view = \_ -> toHtml (show (append xs ys)) |
|||
, update = \_ _ -> () |
|||
} |
|||
-- Array.fromList [0,1,2,3,4,5]</syntaxhighlight> |
|||
consoleEx writeLine:"(":a:") + (":b:") = (":(a + b):")". |
|||
].</lang> |
|||
=={{header|Emacs Lisp}}== |
=={{header|Emacs Lisp}}== |
||
The ''vconcat'' function returns a new array containing all the elements of it's arguments. |
|||
:''See [[Array_concatenation#Scheme|Scheme]]'' |
|||
<syntaxhighlight lang="lisp">(vconcat '[1 2 3] '[4 5] '[6 7 8 9]) |
|||
=> [1 2 3 4 5 6 7 8 9]</syntaxhighlight> |
|||
=={{header|EMal}}== |
|||
<syntaxhighlight lang="emal"> |
|||
^|EMal has the concept of list expansion, |
|||
|you can expand a list to function arguments |
|||
|by prefixing it with the unary plus. |
|||
|^ |
|||
List a = int[1,2,3] |
|||
List b = int[4,5,6] |
|||
List c = int[+a, +b] |
|||
writeLine(c) |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
[1,2,3,4,5,6] |
|||
</pre> |
|||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
Line 551: | Line 1,787: | ||
On the shell, |
On the shell, |
||
< |
<syntaxhighlight lang="erlang"> |
||
1> [1, 2, 3] ++ [4, 5, 6]. |
1> [1, 2, 3] ++ [4, 5, 6]. |
||
[1,2,3,4,5,6] |
[1,2,3,4,5,6] |
||
Line 557: | Line 1,793: | ||
[1,2,3,4,5,6] |
[1,2,3,4,5,6] |
||
3> |
3> |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|ERRE}}== |
|||
<syntaxhighlight lang="text"> |
|||
PROGRAM ARRAY_CONCAT |
|||
DIM A[5],B[5],C[10] |
|||
! |
|||
! for rosettacode.org |
|||
! |
|||
BEGIN |
|||
DATA(1,2,3,4,5) |
|||
DATA(6,7,8,9,0) |
|||
FOR I=1 TO 5 DO ! read array A[.] |
|||
READ(A[I]) |
|||
END FOR |
|||
FOR I=1 TO 5 DO ! read array B[.] |
|||
READ(B[I]) |
|||
END FOR |
|||
FOR I=1 TO 10 DO ! append B[.] to A[.] |
|||
IF I>5 THEN |
|||
C[I]=B[I-5] |
|||
ELSE |
|||
C[I]=A[I] |
|||
END IF |
|||
PRINT(C[I];) ! print single C value |
|||
END FOR |
|||
PRINT |
|||
END PROGRAM |
|||
</syntaxhighlight> |
|||
=={{header|Euphoria}}== |
=={{header|Euphoria}}== |
||
< |
<syntaxhighlight lang="euphoria">sequence s1,s2,s3 |
||
s1 = {1,2,3} |
s1 = {1,2,3} |
||
s2 = {4,5,6} |
s2 = {4,5,6} |
||
s3 = s1 & s2 |
s3 = s1 & s2 |
||
? s3</ |
? s3</syntaxhighlight> |
||
{{out}} |
|||
Output: |
|||
{1,2,3,4,5,6} |
{1,2,3,4,5,6} |
||
=={{header|F Sharp|F#}}== |
=={{header|F Sharp|F#}}== |
||
Array concatenation. |
Array concatenation. |
||
< |
<syntaxhighlight lang="fsharp">let a = [|1; 2; 3|] |
||
let b = [|4; 5; 6;|] |
let b = [|4; 5; 6;|] |
||
let c = Array.append a b</ |
let c = Array.append a b</syntaxhighlight> |
||
List concatenation (@ and List.append are equivalent). |
List concatenation (@ and List.append are equivalent). |
||
< |
<syntaxhighlight lang="fsharp">let x = [1; 2; 3] |
||
let y = [4; 5; 6] |
let y = [4; 5; 6] |
||
let z1 = x @ y |
let z1 = x @ y |
||
let z2 = List.append x y</ |
let z2 = List.append x y</syntaxhighlight> |
||
=={{header|FBSL}}== |
|||
Array concatenation: |
|||
<lang qbasic>#APPTYPE CONSOLE |
|||
DIM aint[] ={1, 2, 3}, astr[] ={"one", "two", "three"}, asng[] ={!1, !2, !3} |
|||
FOREACH DIM e IN ARRAYMERGE(aint, astr, asng) |
|||
PRINT e, " "; |
|||
NEXT |
|||
PAUSE</lang> |
|||
Output: |
|||
<pre>1 2 3 one two three 1.000000 2.000000 3.000000 |
|||
Press any key to continue...</pre> |
|||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
<lang |
<syntaxhighlight lang="factor">append</syntaxhighlight> |
||
'''Example''': |
'''Example''': |
||
< |
<syntaxhighlight lang="factor">( scratchpad ) USE: sequences |
||
( scratchpad ) { 1 2 } { 3 4 } append . |
( scratchpad ) { 1 2 } { 3 4 } append . |
||
{ 1 2 3 4 }</ |
{ 1 2 3 4 }</syntaxhighlight> |
||
=={{header|Fantom}}== |
=={{header|Fantom}}== |
||
Line 607: | Line 1,863: | ||
In fansh: |
In fansh: |
||
< |
<syntaxhighlight lang="fantom"> |
||
> a := [1,2,3] |
> a := [1,2,3] |
||
> b := [4,5,6] |
> b := [4,5,6] |
||
Line 613: | Line 1,869: | ||
> a |
> a |
||
[1,2,3,4,5,6] |
[1,2,3,4,5,6] |
||
</syntaxhighlight> |
|||
</lang> |
|||
Note 'addAll' is destructive. Write 'a.dup.addAll(b)' to create a fresh list. |
Note 'addAll' is destructive. Write 'a.dup.addAll(b)' to create a fresh list. |
||
=={{header|FBSL}}== |
|||
Array concatenation: |
|||
<syntaxhighlight lang="qbasic">#APPTYPE CONSOLE |
|||
DIM aint[] ={1, 2, 3}, astr[] ={"one", "two", "three"}, asng[] ={!1, !2, !3} |
|||
FOREACH DIM e IN ARRAYMERGE(aint, astr, asng) |
|||
PRINT e, " "; |
|||
NEXT |
|||
PAUSE</syntaxhighlight> |
|||
{{out}} |
|||
<pre>1 2 3 one two three 1.000000 2.000000 3.000000 |
|||
Press any key to continue...</pre> |
|||
=={{header|Forth}}== |
=={{header|Forth}}== |
||
< |
<syntaxhighlight lang="forth">: $!+ ( a u a' -- a'+u ) |
||
2dup + >r swap move r> ; |
2dup + >r swap move r> ; |
||
: cat ( a2 u2 a1 u1 -- a3 u1+u2 ) |
: cat ( a2 u2 a1 u1 -- a3 u1+u2 ) |
||
Line 631: | Line 1,902: | ||
801842600: 03 00 00 00 00 00 00 00 - 04 00 00 00 00 00 00 00 ................ |
801842600: 03 00 00 00 00 00 00 00 - 04 00 00 00 00 00 00 00 ................ |
||
801842610: 05 00 00 00 00 00 00 00 - ........ |
801842610: 05 00 00 00 00 00 00 00 - ........ |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Fortran}}== |
=={{header|Fortran}}== |
||
{{works with|Fortran|90 and later}} |
{{works with|Fortran|90 and later}} |
||
< |
<syntaxhighlight lang="fortran">program Concat_Arrays |
||
implicit none |
implicit none |
||
! Note: in Fortran 90 you must use the old array delimiters (/ , /) |
|||
integer, dimension(3) :: a = [ 1, 2, 3 ] |
|||
integer, dimension(3) :: |
integer, dimension(3) :: a = [1, 2, 3] ! (/1, 2, 3/) |
||
integer, dimension( |
integer, dimension(3) :: b = [4, 5, 6] ! (/4, 5, 6/) |
||
integer, dimension(:), allocatable :: c, d |
|||
allocate(c(size(a)+size(b))) |
allocate(c(size(a)+size(b))) |
||
c(1:size(a)) = a |
c(1 : size(a)) = a |
||
c(size(a)+1:size(a)+size(b)) = b |
c(size(a)+1 : size(a)+size(b)) = b |
||
print*, c |
|||
! alternative |
|||
write(*,*) c |
|||
d = [a, b] ! (/a, b/) |
|||
print*, d |
|||
end program Concat_Arrays</syntaxhighlight> |
|||
=={{header|Free Pascal}}== |
|||
end program Concat_Arrays</lang> |
|||
Since FPC (Free Pascal compiler) version 3.2.0., the dynamic array concatenation operator <code>+</code> is available, provided <code>{$modeSwitch arrayOperators+}</code> (which is enabled by default in <code>{$mode Delphi}</code>). |
|||
<syntaxhighlight lang="pascal"> array2 := array0 + array1</syntaxhighlight> |
|||
Alternatively, one could use <code>concat()</code> which is independent of above modeswitch and mode. Neither option requires the use of any libraries.: |
|||
<syntaxhighlight lang="pascal"> array2 := concat(array0, array1);</syntaxhighlight> |
|||
A more complete example: |
|||
{{works with|Fortran|2003 and later}} |
|||
<syntaxhighlight lang="pascal"> |
|||
<lang fortran>program Concat_Arrays |
|||
Program arrayConcat; |
|||
implicit none |
|||
{$mode delphi} |
|||
integer, dimension(3) :: a = [ 1, 2, 3 ] |
|||
integer, dimension(3) :: b = [ 4, 5, 6 ] |
|||
type |
|||
integer, dimension(:), allocatable :: c |
|||
TDynArr = array of integer; |
|||
var |
|||
i: integer; |
|||
arr1, arr2, arrSum : TDynArr; |
|||
begin |
|||
arr1 := [1, 2, 3]; |
|||
arr2 := [4, 5, 6]; |
|||
arrSum := arr1 + arr2; |
|||
for i in arrSum do |
|||
write(i, ' '); |
|||
writeln; |
|||
end. |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
1 2 3 4 5 6 |
|||
</pre> |
|||
=={{header|FreeBASIC}}== |
|||
write(*,*) c |
|||
<syntaxhighlight lang="freebasic"> |
|||
' FB 1.05.0 Win64 |
|||
Sub ConcatArrays(a() As String, b() As String, c() As String) |
|||
end program Concat_Arrays</lang> |
|||
Dim aSize As Integer = UBound(a) - LBound(a) + 1 |
|||
Dim bSize As Integer = UBound(b) - LBound(b) + 1 |
|||
Dim cSize As Integer = aSize + bSize |
|||
Redim c(0 To cSize - 1) |
|||
Dim i As Integer |
|||
For i = 0 To aSize - 1 |
|||
c(i) = a(LBound(a) + i) |
|||
Next |
|||
For i = 0 To bSize - 1 |
|||
c(UBound(a) + i + 1) = b(LBound(b) + i) |
|||
Next |
|||
End Sub |
|||
Dim a(3) As String = {"The", "quick", "brown", "fox"} |
|||
Dim b(4) As String = {"jumped", "over", "the", "lazy", "dog"} |
|||
Dim c() As String |
|||
ConcatArrays(a(), b(), c()) |
|||
For i As Integer = LBound(c) To UBound(c) |
|||
Print c(i); " "; |
|||
Next |
|||
Print : Print |
|||
Print "Press any key to quit the program" |
|||
Sleep |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
The quick brown fox jumped over the lazy dog |
|||
</pre> |
|||
=={{header|Frink}}== |
=={{header|Frink}}== |
||
< |
<syntaxhighlight lang="frink"> |
||
a = [1,2] |
a = [1,2] |
||
b = [3,4] |
b = [3,4] |
||
a.pushAll[b] |
a.pushAll[b] |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|FunL}}== |
=={{header|FunL}}== |
||
< |
<syntaxhighlight lang="funl">arr1 = array( [1, 2, 3] ) |
||
arr2 = array( [4, 5, 6] ) |
arr2 = array( [4, 5, 6] ) |
||
arr3 = array( [7, 8, 9] ) |
arr3 = array( [7, 8, 9] ) |
||
println( arr1 + arr2 + arr3 )</ |
println( arr1 + arr2 + arr3 )</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 682: | Line 2,012: | ||
<pre> |
<pre> |
||
ArraySeq(1, 2, 3, 4, 5, 6, 7, 8, 9) |
ArraySeq(1, 2, 3, 4, 5, 6, 7, 8, 9) |
||
</pre> |
|||
=={{header|Futhark}}== |
|||
Array concatenation is done with the built-in function <code>concat</code>, which can take any number of arguments: |
|||
<syntaxhighlight lang="futhark"> |
|||
concat as bs cd |
|||
</syntaxhighlight> |
|||
=={{header|FutureBasic}}== |
|||
Option 1 |
|||
<syntaxhighlight lang="futurebasic">void local fn DoIt |
|||
CFArrayRef array = @[@"Alpha",@"Bravo",@"Charlie"] |
|||
print array |
|||
array = fn ArrayByAddingObjectsFromArray( array, @[@"Delta",@"Echo",@"FutureBasic"] ) |
|||
print array |
|||
end fn |
|||
window 1 |
|||
fn DoIt |
|||
HandleEvents</syntaxhighlight> |
|||
Output: |
|||
<pre> |
|||
( |
|||
Alpha, |
|||
Bravo, |
|||
Charlie |
|||
) |
|||
( |
|||
Alpha, |
|||
Bravo, |
|||
Charlie, |
|||
Delta, |
|||
Echo, |
|||
FutureBasic |
|||
) |
|||
</pre> |
|||
Option 2 |
|||
<syntaxhighlight lang="futurebasic"> |
|||
void local fn ConcatArrays |
|||
CFArrayRef array1 = @[@1,@2,@3], array2 = @[@4,@5,@6] |
|||
CFArrayRef array3 = concat(array1,array2) // any number of arguments |
|||
print array3 |
|||
end fn |
|||
fn DoIt |
|||
HandleEvents |
|||
</syntaxhighlight> |
|||
{{output}} |
|||
<pre> |
|||
( |
|||
1, |
|||
2, |
|||
3, |
|||
4, |
|||
5, |
|||
6 |
|||
) |
|||
</pre> |
|||
=={{header|Gambas}}== |
|||
'''[https://gambas-playground.proko.eu/?gist=314bea6fba7f177a1cfaec8a7a8b5ccb Click this link to run this code]''' |
|||
<syntaxhighlight lang="gambas">Public Sub Main() |
|||
Dim sString1 As String[] = ["The", "quick", "brown", "fox"] |
|||
Dim sString2 As String[] = ["jumped", "over", "the", "lazy", "dog"] |
|||
sString1.Insert(sString2) |
|||
Print sString1.Join(" ") |
|||
End</syntaxhighlight> |
|||
Output: |
|||
<pre> |
|||
The quick brown fox jumped over the lazy dog |
|||
</pre> |
</pre> |
||
=={{header|GAP}}== |
=={{header|GAP}}== |
||
< |
<syntaxhighlight lang="gap"># Concatenate arrays |
||
Concatenation([1, 2, 3], [4, 5, 6], [7, 8, 9]); |
Concatenation([1, 2, 3], [4, 5, 6], [7, 8, 9]); |
||
# [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ] |
# [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ] |
||
Line 694: | Line 2,105: | ||
Append(a, [7, 8, 9]); |
Append(a, [7, 8, 9]); |
||
a; |
a; |
||
# [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]</ |
# [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]</syntaxhighlight> |
||
=={{header|Genie}}== |
|||
<syntaxhighlight lang="genie">[indent=4] |
|||
/* |
|||
Array concatenation, in Genie |
|||
Tectonics: valac array-concat.gs |
|||
*/ |
|||
/* Creates a new array */ |
|||
def int_array_concat(x:array of int, y:array of int):array of int |
|||
var a = new Array of int(false, true, 0) /* (zero-terminated, clear, size) */ |
|||
a.append_vals (x, x.length) |
|||
a.append_vals (y, y.length) |
|||
z:array of int = (owned) a.data |
|||
return z |
|||
def int_show_array(a:array of int) |
|||
for element in a do stdout.printf("%d ", element) |
|||
stdout.printf("\n") |
|||
init |
|||
x: array of int = {1, 2, 3} |
|||
y: array of int = {3, 2, 1, 0, -1} |
|||
z: array of int = int_array_concat(x, y) |
|||
stdout.printf("x: "); int_show_array(x) |
|||
stdout.printf("y: "); int_show_array(y) |
|||
stdout.printf("z: "); int_show_array(z) |
|||
print "%d elements in new array", z.length</syntaxhighlight> |
|||
{{out}} |
|||
<pre>prompt$ valac array-concat.gs |
|||
prompt$ ./array-concat |
|||
x: 1 2 3 |
|||
y: 3 2 1 0 -1 |
|||
z: 1 2 3 3 2 1 0 -1 |
|||
8 elements in new array</pre> |
|||
=={{header|GLSL}}== |
|||
This macro concatenates two arrays to form a new array. The first parameter is the type of the array: |
|||
<syntaxhighlight lang="glsl"> |
|||
#define array_concat(T,a1,a2,returned) \ |
|||
T[a1.length()+a2.length()] returned; \ |
|||
{ \ |
|||
for(int i = 0; i < a1.length(); i++){ \ |
|||
returned[i] = a1[i]; \ |
|||
} \ |
|||
for(int i = 0; i < a2.length(); i++){ \ |
|||
returned[i+a1.length()] = a2[i]; \ |
|||
} \ |
|||
} |
|||
</syntaxhighlight> |
|||
The macro can be used like this: |
|||
<syntaxhighlight lang="glsl"> |
|||
array_concat(float,float[](1.,2.,3.),float[](4.,5.,6.),returned); |
|||
int i = returned.length(); |
|||
</syntaxhighlight> |
|||
=={{header|Go}}== |
=={{header|Go}}== |
||
< |
<syntaxhighlight lang="go">package main |
||
import "fmt" |
import "fmt" |
||
Line 731: | Line 2,200: | ||
fmt.Println(n) |
fmt.Println(n) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
|||
Output: |
|||
<pre> |
<pre> |
||
[1 2 3 7 12 60] |
[1 2 3 7 12 60] |
||
Line 739: | Line 2,208: | ||
</pre> |
</pre> |
||
Array concatenation needs can vary. Here is another set of examples that illustrate different techniques. |
Array concatenation needs can vary. Here is another set of examples that illustrate different techniques. |
||
< |
<syntaxhighlight lang="go">package main |
||
import ( |
import ( |
||
Line 795: | Line 2,264: | ||
test2_c := ArrayConcat(test2_a, test2_b).([]string) |
test2_c := ArrayConcat(test2_a, test2_b).([]string) |
||
fmt.Println(test2_a, " + ", test2_b, " = ", test2_c) |
fmt.Println(test2_a, " + ", test2_b, " = ", test2_c) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
|||
Output: |
|||
<pre> |
<pre> |
||
[1 2 3] + [4 5 6] = [1 2 3 4 5 6] |
[1 2 3] + [4 5 6] = [1 2 3 4 5 6] |
||
Line 804: | Line 2,273: | ||
=={{header|Gosu}}== |
=={{header|Gosu}}== |
||
< |
<syntaxhighlight lang="gosu"> |
||
var listA = { 1, 2, 3 } |
var listA = { 1, 2, 3 } |
||
var listB = { 4, 5, 6 } |
var listB = { 4, 5, 6 } |
||
Line 811: | Line 2,280: | ||
print( listC ) // prints [1, 2, 3, 4, 5, 6] |
print( listC ) // prints [1, 2, 3, 4, 5, 6] |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Groovy}}== |
=={{header|Groovy}}== |
||
Solution: |
Solution: |
||
< |
<syntaxhighlight lang="groovy">def list = [1, 2, 3] + ["Crosby", "Stills", "Nash", "Young"]</syntaxhighlight> |
||
Test: |
Test: |
||
<lang |
<syntaxhighlight lang="groovy">println list</syntaxhighlight> |
||
{{out}} |
|||
Output: |
|||
<pre>[1, 2, 3, Crosby, Stills, Nash, Young]</pre> |
<pre>[1, 2, 3, Crosby, Stills, Nash, Young]</pre> |
||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
A list is in Haskell one of the most common composite data types (constructed from other types). In the documentation we read for the append operation ++: |
A list is in Haskell one of the most common composite data types (constructed from other types). In the documentation we read for the append operation ++: |
||
< |
<syntaxhighlight lang="haskell">(++) :: [a] -> [a] -> [a]</syntaxhighlight> |
||
Append two lists, i.e.:<pre> |
Append two lists, i.e.:<pre> |
||
[x1, ..., xm] ++ [y1, ..., yn] == [x1, ..., xm, y1, ..., yn] |
[x1, ..., xm] ++ [y1, ..., yn] == [x1, ..., xm, y1, ..., yn] |
||
[x1, ..., xm] ++ [y1, ...] == [x1, ..., xm, y1, ...]</pre> |
[x1, ..., xm] ++ [y1, ...] == [x1, ..., xm, y1, ...]</pre> |
||
If the first list is not finite, the result is the first list. |
If the first list is not finite, the result is the first list. |
||
This operator could be defined from the scratch using explicit recursion: |
|||
<syntaxhighlight lang="haskell"> |
|||
[] ++ x = x |
|||
(h:t) ++ y = h : (t ++ y) |
|||
</syntaxhighlight> |
|||
or folding |
|||
<syntaxhighlight lang="haskell"> |
|||
x ++ y = foldr (:) y x |
|||
</syntaxhighlight> |
|||
=={{header|HicEst}}== |
=={{header|HicEst}}== |
||
< |
<syntaxhighlight lang="hicest">REAL :: a(7), b(3), c(10) |
||
c = a |
c = a |
||
DO i = 1, LEN(b) |
DO i = 1, LEN(b) |
||
c(i + LEN(a)) = b(i) |
c(i + LEN(a)) = b(i) |
||
ENDDO</ |
ENDDO</syntaxhighlight> |
||
=={{header|Hy}}== |
|||
<syntaxhighlight lang="hy">=> (setv a [1 2 3]) |
|||
=> a |
|||
[1, 2, 3] |
|||
=> (+ a [4 5 6]) ; returns the concatenation |
|||
[1, 2, 3, 4, 5, 6] |
|||
=> a |
|||
[1, 2, 3] |
|||
=> (.extend a [7 8 9]) ; modifies the list in place |
|||
=> a |
|||
[1, 2, 3, 7, 8, 9] |
|||
=> (+ [1 2] [3 4] [5 6]) ; can accept multiple arguments |
|||
[1, 2, 3, 4, 5, 6]</syntaxhighlight> |
|||
=={{header|i}}== |
|||
<syntaxhighlight lang="i">main |
|||
a $= [1, 2, 3] |
|||
b $= [4, 5, 6] |
|||
print(a + b) |
|||
}</syntaxhighlight> |
|||
=={{header|Icon}} and {{header|Unicon}}== |
=={{header|Icon}} and {{header|Unicon}}== |
||
Both languages have list concatenation built in. Lists are fully dynamic arrays which can be truncated or extended at either end. |
Both languages have list concatenation built in. Lists are fully dynamic arrays which can be truncated or extended at either end. |
||
< |
<syntaxhighlight lang="icon"> |
||
procedure main() |
procedure main() |
||
L1 := [1, 2, 3, 4] |
L1 := [1, 2, 3, 4] |
||
Line 852: | Line 2,356: | ||
write() |
write() |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|IDL}}== |
=={{header|IDL}}== |
||
Array concatenation can mean different things, depending on the number of dimensions of the arguments and the result. In the simplest case, with 1-dimensional arrays to begin with, there are two obvious ways to concatenate them. If my arrays are these: |
Array concatenation can mean different things, depending on the number of dimensions of the arguments and the result. In the simplest case, with 1-dimensional arrays to begin with, there are two obvious ways to concatenate them. If my arrays are these: |
||
<syntaxhighlight lang="idl"> |
|||
<lang IDL> |
|||
> a = [1,2,3] |
> a = [1,2,3] |
||
> b = [4,5,6] |
> b = [4,5,6] |
||
Line 868: | Line 2,372: | ||
> print,b |
> print,b |
||
4 5 6 |
4 5 6 |
||
</syntaxhighlight> |
|||
</lang> |
|||
Then they can be concatenated "at the ends": |
Then they can be concatenated "at the ends": |
||
<syntaxhighlight lang="idl"> |
|||
<lang IDL> |
|||
> help,[a,b] |
> help,[a,b] |
||
<Expression> INT = Array[6] |
<Expression> INT = Array[6] |
||
> print,[a,b] |
> print,[a,b] |
||
1 2 3 4 5 6 |
1 2 3 4 5 6 |
||
</syntaxhighlight> |
|||
</lang> |
|||
or "at the sides": |
or "at the sides": |
||
<syntaxhighlight lang="idl"> |
|||
<lang IDL> |
|||
> help,[[a],[b]] |
> help,[[a],[b]] |
||
<Expression> INT = Array[3, 2] |
<Expression> INT = Array[3, 2] |
||
Line 883: | Line 2,387: | ||
1 2 3 |
1 2 3 |
||
4 5 6 |
4 5 6 |
||
</syntaxhighlight> |
|||
</lang> |
|||
Note that this requires that the arrays have the same size at the side at which they are concatenated: |
Note that this requires that the arrays have the same size at the side at which they are concatenated: |
||
<syntaxhighlight lang="idl"> |
|||
<lang IDL> |
|||
> b = transpose(b) |
> b = transpose(b) |
||
> help,b |
> help,b |
||
Line 899: | Line 2,403: | ||
Unable to concatenate variables because the dimensions do not agree: B. |
Unable to concatenate variables because the dimensions do not agree: B. |
||
Execution halted at: $MAIN$ |
Execution halted at: $MAIN$ |
||
</syntaxhighlight> |
|||
</lang> |
|||
This can get a lot more complicated as a 3x4x5-element three-dimensional array can be concatenated with a 5x2x3-element array at exactly two "surfaces". |
This can get a lot more complicated as a 3x4x5-element three-dimensional array can be concatenated with a 5x2x3-element array at exactly two "surfaces". |
||
=={{header|Idris}}== |
|||
Idris will disambiguate functions based on type, so both <code>List</code> (arbitrary length) and <code>Vect</code> (fixed length) can be concatenated in the same way: |
|||
<pre>Idris> [1, 2] ++ [4, 5, 6] |
|||
[1, 2, 3, 4, 5] : List Integer |
|||
Idris> :module Data.Vect |
|||
*Data/Vect> (the (Vect 2 Nat) [1, 2]) ++ (the (Vect 3 Nat) [3, 4, 5]) |
|||
[1, 2, 3, 4, 5] : Vect 5 Nat</pre> |
|||
=={{header|Inform 7}}== |
=={{header|Inform 7}}== |
||
< |
<syntaxhighlight lang="inform7">let A be {1, 2, 3}; |
||
let B be {4, 5, 6}; |
let B be {4, 5, 6}; |
||
add B to A;</ |
add B to A;</syntaxhighlight> |
||
=={{header|Insitux}}== |
|||
<syntaxhighlight lang="insitux">(into [1 2 3] [4 5 6])</syntaxhighlight> |
|||
<syntaxhighlight lang="insitux">(.. vec [1 2 3] [4 5 6])</syntaxhighlight> |
|||
=={{header|Ioke}}== |
=={{header|Ioke}}== |
||
< |
<syntaxhighlight lang="ioke">iik> [1,2,3] + [3,2,1] |
||
[1,2,3] + [3,2,1] |
[1,2,3] + [3,2,1] |
||
+> [1, 2, 3, 3, 2, 1]</ |
+> [1, 2, 3, 3, 2, 1]</syntaxhighlight> |
||
=={{header|J}}== |
=={{header|J}}== |
||
Line 916: | Line 2,433: | ||
'''Example''': |
'''Example''': |
||
< |
<syntaxhighlight lang="j"> array1 =: 1 2 3 |
||
array2 =: 4 5 6 |
array2 =: 4 5 6 |
||
array1 , array2 |
array1 , array2 |
||
1 2 3 4 5 6</ |
1 2 3 4 5 6</syntaxhighlight> |
||
Of course, in J, array concatenation works (consistently) on arrays of any rank or dimension. |
Of course, in J, array concatenation works (consistently) on arrays of any rank or dimension. |
||
Line 925: | Line 2,442: | ||
The verb <code>,</code> concatenates by treating the argument array with the largest number of dimensions as a list. Other primary verbs concatenate along other axes. |
The verb <code>,</code> concatenates by treating the argument array with the largest number of dimensions as a list. Other primary verbs concatenate along other axes. |
||
< |
<syntaxhighlight lang="j"> ]ab=: 3 3 $ 'aaabbbccc' |
||
aaa |
aaa |
||
bbb |
bbb |
||
Line 957: | Line 2,474: | ||
3 6 |
3 6 |
||
$ ab ,: wx NB. applies to new (higher) axis |
$ ab ,: wx NB. applies to new (higher) axis |
||
2 3 3</ |
2 3 3</syntaxhighlight> |
||
=={{header| |
=={{header|Jakt}}== |
||
<syntaxhighlight lang="jakt"> |
|||
From [http://forums.sun.com/thread.jspa?messageID=1762690#1762690]: |
|||
fn main() { |
|||
<lang java5>public static Object[] objArrayConcat(Object[] o1, Object[] o2) |
|||
let a = ["Apple", "Banana"] |
|||
{ |
|||
let b = ["Cherry", "Durian"] |
|||
Object[] ret = new Object[o1.length + o2.length]; |
|||
mut c: [String] = [] |
|||
c.push_values(&a) |
|||
c.push_values(&b) |
|||
println("{}", c) |
|||
} |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
System.arraycopy(o1, 0, ret, 0, o1.length); |
|||
<pre> |
|||
System.arraycopy(o2, 0, ret, o1.length, o2.length); |
|||
["Apple", "Banana", "Cherry", "Durian"] |
|||
</pre> |
|||
return ret; |
|||
}</lang> |
|||
=={{header|Java}}== |
|||
Or with <code>Collection</code>s simply call <code>addAll</code>: |
|||
In Java, arrays are immutable, so you'll have to create a new array, and copy the contents of the two arrays into it.<br /> |
|||
<lang java5>Collection list1, list2, list1And2; |
|||
Luckily, Java offers the ''System.arraycopy'' method, which will save you the effort of creating the for-loops.<br /> |
|||
//...list1 and list2 are instantiated... |
|||
<syntaxhighlight lang="java"> |
|||
list1And2 = new ArrayList(list1); //or any other Collection you want |
|||
int[] concat(int[] arrayA, int[] arrayB) { |
|||
list1And2.addAll(list2);</lang> |
|||
int[] array = new int[arrayA.length + arrayB.length]; |
|||
System.arraycopy(arrayA, 0, array, 0, arrayA.length); |
|||
System.arraycopy(arrayB, 0, array, arrayA.length, arrayB.length); |
|||
return array; |
|||
} |
|||
</syntaxhighlight> |
|||
If you wanted to use for-loops, possibly to mutate the data as it's concatenated, you can use the following. |
|||
<syntaxhighlight lang="java"> |
|||
int[] concat(int[] arrayA, int[] arrayB) { |
|||
int[] array = new int[arrayA.length + arrayB.length]; |
|||
for (int index = 0; index < arrayA.length; index++) |
|||
array[index] = arrayA[index]; |
|||
for (int index = 0; index < arrayB.length; index++) |
|||
array[index + arrayA.length] = arrayB[index]; |
|||
return array; |
|||
} |
|||
</syntaxhighlight> |
|||
A less idiomatic approach would be to use a ''List'', which is a mutable array, similar to a "vector" in other languages.<br /> |
|||
I have used both arrays and ''List''s extensively and have not noticed any sort of performance degradation, they appear to work equally as fast.<br /> |
|||
It's worth noting that the Java Collections Framework, which contains the ''List'' class, is built specifically for Objects and not necessarily primitive data-types. Despite this, it's still worth using for primitives, although the conversion to and from arrays is somewhat abstruse. |
|||
<syntaxhighlight lang="java"> |
|||
int[] concat(int[] arrayA, int[] arrayB) { |
|||
List<Integer> list = new ArrayList<>(); |
|||
for (int value : arrayA) list.add(value); |
|||
for (int value : arrayB) list.add(value); |
|||
int[] array = new int[list.size()]; |
|||
for (int index = 0; index < list.size(); index++) |
|||
array[index] = list.get(index); |
|||
return array; |
|||
} |
|||
</syntaxhighlight> |
|||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
The <code>Array.concat()</code> method returns a new array comprised of this array joined with other array(s) and/or value(s). |
The <code>Array.concat()</code> method returns a new array comprised of this array joined with other array(s) and/or value(s). |
||
< |
<syntaxhighlight lang="javascript">var a = [1,2,3], |
||
b = [4,5,6], |
|||
c = a.concat(b); //=> [1,2,3,4,5,6]</syntaxhighlight> |
|||
b = [4,5,6], |
|||
c = a.concat(b); // [1,2,3,4,5,6]</lang> |
|||
Or, if we consider the concatenation of two arrays as a particular instance of the more general problem of concatenating 2 or more arrays, we can write a generic function: |
|||
{{trans|Haskell}} |
|||
See, for a function with an analogous type signature, '''concat''' in the Haskell Prelude. |
|||
<syntaxhighlight lang="javascript">(function () { |
|||
'use strict'; |
|||
// concat :: [[a]] -> [a] |
|||
function concat(xs) { |
|||
return [].concat.apply([], xs); |
|||
} |
|||
return concat( |
|||
[["alpha", "beta", "gamma"], |
|||
["delta", "epsilon", "zeta"], |
|||
["eta", "theta", "iota"]] |
|||
); |
|||
})();</syntaxhighlight> |
|||
{{Out}} |
|||
<pre>["alpha", "beta", "gamma", "delta", "epsilon", "zeta", "eta", "theta", "iota"]</pre> |
|||
=={{header|Joy}}== |
|||
<syntaxhighlight lang="joy">[1 2 3] [4 5 6] concat.</syntaxhighlight> |
|||
=={{header|jq}}== |
=={{header|jq}}== |
||
If a and b are two arrays, then a+b is their concatenation. |
If a and b are two arrays, then a+b is their concatenation. |
||
Similarly for a+b+c. |
|||
Similarly for a+b+c. To concatenate the component arrays of an array, A, the <tt>flatten</tt> filter is available in recent versions of jq. If your jq does not have flatten, then the task can be accomplished by: |
|||
To concatenate the component arrays of an array, A, the <tt>add</tt> filter can be used: <tt>A|add</tt> |
|||
reduce A[] as $a ([]. + $a) |
|||
jq also supports streams, which are somewhat array-like, so it may be worth mentioning that the concatenation of two or more streams can be accomplished using "," instead of "+". < |
jq also supports streams, which are somewhat array-like, so it may be worth mentioning that the concatenation of two or more streams can be accomplished using "," instead of "+". <syntaxhighlight lang="jq">[1,2] + [3] + [null] # => [1,2,3,null] |
||
[range(1;3), 3, null] # => [1,2,3,null] |
[range(1;3), 3, null] # => [1,2,3,null] |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
< |
<syntaxhighlight lang="julia">a = [1,2,3] |
||
b = [4,5,6] |
b = [4,5,6] |
||
ab = [a |
ab = [a;b] |
||
# the above bracket notation simply generates a call to vcat |
# the above bracket notation simply generates a call to vcat |
||
ab = vcat(a,b) |
ab = vcat(a,b) |
||
Line 1,004: | Line 2,586: | ||
ab = hcat(a,b) #ab -> 3x2 matrix |
ab = hcat(a,b) #ab -> 3x2 matrix |
||
# the append!(a,b) method is mutating, appending `b` to `a` |
# the append!(a,b) method is mutating, appending `b` to `a` |
||
append!(a,b) # a now equals [1,2,3,4,5,6]</ |
append!(a,b) # a now equals [1,2,3,4,5,6]</syntaxhighlight> |
||
=={{header|K}}== |
=={{header|K}}== |
||
<syntaxhighlight lang="k"> |
|||
<lang K> |
|||
a: 1 2 3 |
a: 1 2 3 |
||
b: 4 5 6 |
b: 4 5 6 |
||
a,b |
a,b |
||
1 2 3 4 5 6</ |
1 2 3 4 5 6</syntaxhighlight> |
||
Concatenations on larger dimensions also use ",", often combined with other operations. |
Concatenations on larger dimensions also use ",", often combined with other operations. |
||
<syntaxhighlight lang="k"> |
|||
<lang K> |
|||
ab:3 3#"abcdefghi" |
ab:3 3#"abcdefghi" |
||
("abc" |
("abc" |
||
Line 1,047: | Line 2,629: | ||
("abc036" |
("abc036" |
||
"def147" |
"def147" |
||
"ghi258")</ |
"ghi258")</syntaxhighlight> |
||
=={{header| |
=={{header|Klingphix}}== |
||
<syntaxhighlight lang="klingphix">include ..\Utilitys.tlhy |
|||
There is no operator or standard library function for concatenating <code>Array</code> types. One option is to convert to <code>Collection</code>s, concatenate, and convert back: |
|||
<lang kotlin>val a : Array<T> = // initialise a |
|||
val b : Array<T> = // initialise b |
|||
val c = (a.toList() + b.toList()).copyToArray()</lang> |
|||
( 1.0 "Hello" 3 2 / 4 2.1 power ) ( 5 6 7 8 ) chain print |
|||
Alternatively, we can write our own concatenation function: |
|||
<lang kotlin>fun arrayConcat(a : Array<Any>, b : Array<Any>) |
|||
= Array<Any>(a.size + b.size, {if (it in a.indices) a[it] else b[it - a.size]})</lang> |
|||
" " input</syntaxhighlight> |
|||
When working directly with <code>Collection</code>s, we can simply use the <code>+</code> operator: |
|||
{{out}} |
|||
<lang kotlin>val a : Collection<T> // initialise a |
|||
<pre>(1, "Hello", 1.5, 18.379173679952562, 5, 6, 7, 8)</pre> |
|||
val b : Collection<T> = // initialise b |
|||
val c : Collection = a + b</lang> |
|||
=={{header|Klong}}== |
|||
<syntaxhighlight lang="k"> |
|||
[1 2 3],[4 5 6] :" join " |
|||
[1 2 3 4 5 6] |
|||
[1 2],:\[[3 4] [5 6] [7 8]] :" join each-left " |
|||
[[1 2 3 4] [1 2 5 6] [1 2 7 8]] |
|||
[1 2],:/[[3 4] [5 6] [7 8]] :" join each-right " |
|||
[[3 4 1 2] [5 6 1 2] [7 8 1 2]] |
|||
</syntaxhighlight> |
|||
=={{header|Kotlin}}== |
|||
<syntaxhighlight lang="kotlin">fun main() { |
|||
val a = intArrayOf(1, 2, 3) |
|||
val b = intArrayOf(4, 5, 6) |
|||
val c = a + b // [1, 2, 3, 4, 5, 6] |
|||
println(c.contentToString()) |
|||
}</syntaxhighlight> |
|||
=={{header|LabVIEW}}== |
=={{header|LabVIEW}}== |
||
Use the Build Array function.<br/>{{VI snippet}}<br/> |
Use the Build Array function.<br/>{{VI snippet}}<br/> |
||
[[File:LabVIEW_Array_concatenation.png]] |
[[File:LabVIEW_Array_concatenation.png]] |
||
=={{header|Lambdatalk}}== |
|||
<syntaxhighlight lang="scheme"> |
|||
{def A {A.new 1 2 3 4 5 6}} -> [1,2,3,4,5,6] |
|||
{def B {A.new 7 8 9}} -> [7,8,9] |
|||
{A.concat {A} {B}} -> [1,2,3,4,5,6,7,8,9] |
|||
</syntaxhighlight> |
|||
=={{header|Lang}}== |
|||
<syntaxhighlight lang="lang"> |
|||
&a $= [1, 2, 3] |
|||
&b $= [4, 5, 6] |
|||
&c $= &a ||| &b |
|||
fn.println(&c) |
|||
</syntaxhighlight> |
|||
=={{header|Lang5}}== |
=={{header|Lang5}}== |
||
< |
<syntaxhighlight lang="lang5">[1 2] [3 4] append collapse .</syntaxhighlight> |
||
=={{header|langur}}== |
|||
<syntaxhighlight lang="langur">val a = [1, 2, 3] |
|||
val b = [7, 8, 9] |
|||
val c = a ~ b |
|||
writeln c</syntaxhighlight> |
|||
{{out}} |
|||
<pre>[1, 2, 3, 7, 8, 9]</pre> |
|||
=={{header|Lasso}}== |
|||
<syntaxhighlight lang="lasso"> |
|||
local(arr1 = array(1, 2, 3)) |
|||
local(arr2 = array(4, 5, 6)) |
|||
local(arr3 = #arr1->asCopy) // make arr3 a copy of arr2 |
|||
#arr3->merge(#arr2) // concatenate 2 arrays |
|||
Result: |
|||
arr1 = array(1, 2, 3) |
|||
arr2 = array(4, 5, 6) |
|||
arr3 = array(4, 5, 6) |
|||
arr3 = array(1, 2, 3, 4, 5, 6)</syntaxhighlight> |
|||
=={{header|LDPL}}== |
|||
{{libheader|ldpl-std}} |
|||
<syntaxhighlight lang="ldpl">include "std-list.ldpl" |
|||
data: |
|||
arr1 is number list |
|||
arr2 is number list |
|||
procedure: |
|||
push 1 to arr1 |
|||
push 2 to arr1 |
|||
push 3 to arr2 |
|||
push 4 to arr2 |
|||
append list arr2 to list arr1 |
|||
display list arr1 |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
[1, 2, 3, 4] |
|||
</pre> |
|||
=={{header|LFE}}== |
=={{header|LFE}}== |
||
< |
<syntaxhighlight lang="lisp"> |
||
> (++ '(1 2 3) '(4 5 6)) |
> (++ '(1 2 3) '(4 5 6)) |
||
(1 2 3 4 5 6) |
(1 2 3 4 5 6) |
||
> (: lists append '(1 2 3) '(4 5 6)) |
> (: lists append '(1 2 3) '(4 5 6)) |
||
(1 2 3 4 5 6) |
(1 2 3 4 5 6) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Liberty BASIC}}== |
=={{header|Liberty BASIC}}== |
||
{{works with|Just BASIC}} |
|||
<lang lb> x=10 |
|||
{{works with|Run BASIC}} |
|||
<syntaxhighlight lang="lb"> x=10 |
|||
y=20 |
y=20 |
||
dim array1(x) |
dim array1(x) |
||
Line 1,097: | Line 2,755: | ||
for i = 1 to x + y |
for i = 1 to x + y |
||
print array3(i) |
print array3(i) |
||
next</ |
next</syntaxhighlight> |
||
=={{header|LIL}}== |
|||
LIL uses lists instead of arrays. The builtin '''append''' command could be used as '''append a $b'''. That would add the entire list in variable '''b''' as one item to list '''a'''. Below '''quote''' is used to flatten the lists into a single new list of all items. |
|||
<syntaxhighlight lang="tcl">## |
|||
=={{header|Lasso}}== |
|||
Array concatenation in LIL |
|||
<lang Lasso> |
|||
## |
|||
local(arr1 = array(1, 2, 3)) |
|||
set a [list 1 2 3] |
|||
local(arr2 = array(4, 5, 6)) |
|||
set b [list 4 5 6] |
|||
local(arr3 = #arr1->asCopy) // make arr3 a copy of arr2 |
|||
set c [quote $a $b] |
|||
#arr3->merge(#arr2) // concatenate 2 arrays |
|||
print $c |
|||
print "[index $c 0] [index $c 3]"</syntaxhighlight> |
|||
{{out}} |
|||
Result: |
|||
<pre>prompt$ lil arrayConcatenation.lil |
|||
1 2 3 4 5 6 |
|||
1 4</pre> |
|||
=={{header|Limbo}}== |
|||
arr1 = array(1, 2, 3) |
|||
<syntaxhighlight lang="limbo">implement Command; |
|||
arr2 = array(4, 5, 6) |
|||
arr3 = array(4, 5, 6) |
|||
include "sys.m"; |
|||
arr3 = array(1, 2, 3, 4, 5, 6)</lang> |
|||
sys: Sys; |
|||
include "draw.m"; |
|||
include "sh.m"; |
|||
init(nil: ref Draw->Context, nil: list of string) |
|||
{ |
|||
sys = load Sys Sys->PATH; |
|||
a := array[] of {1, 2}; |
|||
b := array[] of {3, 4, 5}; |
|||
c := array[len a + len b] of int; |
|||
c[:] = a; |
|||
c[len a:] = b; |
|||
for (i := 0; i < len c; i++) |
|||
sys->print("%d\n", c[i]); |
|||
}</syntaxhighlight> |
|||
=={{header|Lingo}}== |
|||
<syntaxhighlight lang="lingo">a = [1,2] |
|||
b = [3,4,5] |
|||
repeat with v in b |
|||
a.append(v) |
|||
end repeat |
|||
put a |
|||
-- [1, 2, 3, 4, 5]</syntaxhighlight> |
|||
=={{header|Little}}== |
|||
<syntaxhighlight lang="c">void main() { |
|||
int a[] = {0, 1, 2, 3, 4}; |
|||
int b[] = {5, 6, 7, 8, 9}; |
|||
int c[] = {(expand)a, (expand)b}; |
|||
puts(c); |
|||
}</syntaxhighlight> |
|||
=={{header|Logo}}== |
=={{header|Logo}}== |
||
COMBINE is used to combine lists or words. SENTENCE is used to combine lists and words into a single list. |
COMBINE is used to combine lists or words. SENTENCE is used to combine lists and words into a single list. |
||
< |
<syntaxhighlight lang="logo"> |
||
to combine-arrays :a1 :a2 |
to combine-arrays :a1 :a2 |
||
output listtoarray sentence arraytolist :a1 arraytolist :a2 |
output listtoarray sentence arraytolist :a1 arraytolist :a2 |
||
end |
end |
||
show combine-arrays {1 2 3} {4 5 6} ; {1 2 3 4 5 6} |
show combine-arrays {1 2 3} {4 5 6} ; {1 2 3 4 5 6} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
< |
<syntaxhighlight lang="lua">a = {1, 2, 3} |
||
b = {4,5,6} |
b = {4, 5, 6} |
||
table.foreach(b,function(i,v)table.insert(a,v)end) |
|||
for |
for _, v in pairs(b) do |
||
table.insert(a, v) |
|||
end |
|||
print(table.concat(a, ", "))</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
1, 2, 3, 4, 5, 6 |
|||
</pre> |
|||
=={{header|M2000 Interpreter}}== |
|||
<syntaxhighlight lang="m2000 interpreter"> |
|||
a=(1,2,3,4,5) |
|||
b=Cons(a, (6,7,8),a) |
|||
Print b |
|||
1 2 3 4 5 6 7 8 1 2 3 4 5 |
|||
</syntaxhighlight> |
|||
Adding 2 dimension arrays |
|||
<syntaxhighlight lang="m2000 interpreter"> |
|||
Dim Base 0, A(2,2)=1, B(1,2)=6 |
|||
A()=Cons(A(), B(), A(), B()) |
|||
\\ Restore the dimensions (without erasing items) |
|||
Dim A(Dimension(A(),1)/2, 2) |
|||
For I=0 to Dimension(A(),1)-1 { |
|||
For j=0 to Dimension(A(),2)-1 { |
|||
Print A(i, j), |
|||
} |
|||
Print |
|||
} |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
1 1 |
|||
1 1 |
|||
6 6 |
|||
1 1 |
|||
1 1 |
|||
6 6 |
|||
</pre > |
|||
Adding 2 dimension arrays using OLE clause |
|||
<syntaxhighlight lang="m2000 interpreter"> |
|||
Dim OLE Base 0, A(2,2)=1, B(1,2)=6 |
|||
A()=Cons(A(), B(), A(), B()) |
|||
\\ Restore the dimensions (without erasing items) |
|||
Dim A(Dimension(A(),1)/2, 2) |
|||
For I=0 to Dimension(A(),1)-1 { |
|||
For j=0 to Dimension(A(),2)-1 { |
|||
Print A(i, j), |
|||
} |
|||
Print |
|||
} |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
1 1 |
|||
1 1 |
|||
1 1 |
|||
1 1 |
|||
6 6 |
|||
6 6 |
|||
</pre > |
|||
=={{header|Maple}}== |
=={{header|Maple}}== |
||
There is a built-in procedure for concatenating arrays (and similar objects such as matrices or vectors). Arrays can be concatenated along any given dimension, which is specified as the first argument. |
There is a built-in procedure for concatenating arrays (and similar objects such as matrices or vectors). Arrays can be concatenated along any given dimension, which is specified as the first argument. |
||
<syntaxhighlight lang="maple"> |
|||
<lang Maple> |
|||
> A := Array( [ 1, 2, 3 ] ); |
> A := Array( [ 1, 2, 3 ] ); |
||
A := [1, 2, 3] |
A := [1, 2, 3] |
||
Line 1,158: | Line 2,926: | ||
[ ] |
[ ] |
||
[1 2 3] |
[1 2 3] |
||
</syntaxhighlight> |
|||
</lang> |
|||
Of course, the order of the arguments is important. |
Of course, the order of the arguments is important. |
||
<syntaxhighlight lang="maple"> |
|||
<lang Maple> |
|||
> ArrayTools:-Concatenate( 1, A, M ); |
> ArrayTools:-Concatenate( 1, A, M ); |
||
[1 2 3] |
[1 2 3] |
||
Line 1,167: | Line 2,935: | ||
[ ] |
[ ] |
||
[d e f] |
[d e f] |
||
</syntaxhighlight> |
|||
</lang> |
|||
Lists, in Maple, might be considered to be a kind of "array" (in the sense that they look like arrays in memory), though they are actually immutable objects. However, they can be concatenated as follows. |
Lists, in Maple, might be considered to be a kind of "array" (in the sense that they look like arrays in memory), though they are actually immutable objects. However, they can be concatenated as follows. |
||
<syntaxhighlight lang="maple"> |
|||
<lang Maple> |
|||
> L1 := [ 1, 2, 3 ]; |
> L1 := [ 1, 2, 3 ]; |
||
L1 := [1, 2, 3] |
L1 := [1, 2, 3] |
||
Line 1,181: | Line 2,949: | ||
> [ L1[], L2[] ]; # equivalent, just different syntax |
> [ L1[], L2[] ]; # equivalent, just different syntax |
||
[1, 2, 3, a, b, c] |
[1, 2, 3, a, b, c] |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header| |
=={{header|Mathcad}}== |
||
<lang Mathematica>Join[{1,2,3}, {4,5,6}] |
|||
Ref: [https://community.ptc.com/t5/PTC-Mathcad/Rosetta-Code-Array-Concatenation/m-p/665686#M190150] Mathcad Community Topic |
|||
-> {1, 2, 3, 4, 5, 6}</lang> |
|||
=={{header|MATLAB}} / {{header|Octave}}== |
|||
Two arrays are concatenated by placing the two arrays between a pair of square brackets. A space between the two array names will concatenate them horizontally, and a semi-colon between array names will concatenate vertically. |
|||
<lang MATLAB>>> a = [1 2 3] |
|||
Mathcad has a built-in array type that includes a natural 2D matrix-style format. |
|||
a = |
|||
Mathcad can concatenate arrays in several ways. The easiest way is to use the built-in stack and augment functions. |
|||
1 2 3 |
|||
stack concatenates arrays row-wise. The two (or more) arrays must have the same number of columns, and the resulting array row count is equal to the total number of rows in the stacked arrays. |
|||
>> b = [4 5 6] |
|||
b = |
|||
augment concatenates arrays column-wise. The two (or more) arrays must have the same number of rows, and the resulting array column count is equal to the total number of columns in the augmented arrays. |
|||
4 5 6 |
|||
<syntaxhighlight lang="mathcad"> |
|||
>> concat = [a b] |
|||
create a pair of arbitrary array: |
|||
a:=matrix(2,2,max) b:=a+3 |
|||
a=|0 1| b=|3 4| |
|||
|1 1| |4 4| |
|||
concatentate them vertically: |
|||
concat = |
|||
|0 1| |
|||
stack(a,b) = |1 1| |
|||
|3 4| |
|||
|4 4| |
|||
augment(a,b) = |0 1 3 4| |
|||
|1 1 3 4| |
|||
</syntaxhighlight> |
|||
>> concat = [a;b] |
|||
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
|||
concat = |
|||
<syntaxhighlight lang="mathematica">Join[{1,2,3}, {4,5,6}] |
|||
-> {1, 2, 3, 4, 5, 6}</syntaxhighlight> |
|||
=={{header|MATLAB}} / {{header|Octave}}== |
|||
Two arrays are concatenated by placing the two arrays between a pair of square brackets. A space between the two array names will concatenate them horizontally, and a semi-colon between array names will concatenate vertically. |
|||
<syntaxhighlight lang="matlab">>> a = [1 2 3]; |
|||
>> b = [4 5 6]; |
|||
>> c = [a b] |
|||
c = |
|||
1 2 3 4 5 6 |
|||
>> c = [a;b] |
|||
c = |
|||
1 2 3 |
1 2 3 |
||
4 5 6</ |
4 5 6</syntaxhighlight> |
||
For |
For concatenation along higher dimensions, use cat(): |
||
< |
<syntaxhighlight lang="matlab">>> a = randn([3 4 5]); |
||
>> |
>> b = randn([3 4 7]); |
||
>> |
>> c = cat(3,a,b); |
||
>> size( |
>> size(c) |
||
ans = |
ans = |
||
3 4 12</syntaxhighlight> |
|||
3 4 12 |
|||
</lang> |
|||
=={{header|Maxima}}== |
=={{header|Maxima}}== |
||
<lang>u: [1, 2, 3, 4]$ |
<syntaxhighlight lang="text">u: [1, 2, 3, 4]$ |
||
v: [5, 6, 7, 8, 9, 10]$ |
v: [5, 6, 7, 8, 9, 10]$ |
||
append(u, v); |
append(u, v); |
||
Line 1,249: | Line 3,031: | ||
[1, 0, 0], |
[1, 0, 0], |
||
[0, 1, 0], |
[0, 1, 0], |
||
[0, 0, 1]) */</ |
[0, 0, 1]) */</syntaxhighlight> |
||
=={{header|Mercury}}== |
=={{header|Mercury}}== |
||
< |
<syntaxhighlight lang="mercury">A `append` B = C</syntaxhighlight> |
||
It ''could'' be "as simple as array1 + array2", but the 'array' module names the operation 'append' rather than '+'. It's tempting to just say that Mercury supports ad-hoc polymorphism - it can infer that a bare '+' refers to 'float.+' or 'int.+' (or that the 'append' above is array.append, rather than list.append), by the types involved - but it also handles other ambiguities in the same way. For instance, Mercury (like Prolog and Erlang) treats the arity of a function as part of its name, where ''a(1, 2)'' and ''a(1)'' involve the distinct functions a/2 and a/1. But Mercury also (unlike Prolog and Erlang) supports [[currying]], where ''a(1)'' is a function that accepts a/2's second argument. So, is ''[a(X), a(Y), a(Z)]'' a list of whatever type a/1 evaluates to, or is it a list of curried a/2? |
It ''could'' be "as simple as array1 + array2", but the 'array' module names the operation 'append' rather than '+'. It's tempting to just say that Mercury supports ad-hoc polymorphism - it can infer that a bare '+' refers to 'float.+' or 'int.+' (or that the 'append' above is array.append, rather than list.append), by the types involved - but it also handles other ambiguities in the same way. For instance, Mercury (like Prolog and Erlang) treats the arity of a function as part of its name, where ''a(1, 2)'' and ''a(1)'' involve the distinct functions a/2 and a/1. But Mercury also (unlike Prolog and Erlang) supports [[currying]], where ''a(1)'' is a function that accepts a/2's second argument. So, is ''[a(X), a(Y), a(Z)]'' a list of whatever type a/1 evaluates to, or is it a list of curried a/2? |
||
=={{header|min}}== |
|||
{{works with|min|0.19.3}} |
|||
<syntaxhighlight lang="min">(1 2 3) (4 "apple" 6) concat print</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
(1 2 3 4 "apple" 6) |
|||
</pre> |
|||
=={{header|MiniScript}}== |
|||
<syntaxhighlight lang="miniscript"> |
|||
arrOne = [1, 2, 3] |
|||
arrTwo = [4, 5, 6] |
|||
print arrOne + arrTwo |
|||
</syntaxhighlight> |
|||
=={{header|Nanoquery}}== |
|||
Assuming a and b are array or list objects, they may concatenated using the '+' operator. |
|||
<syntaxhighlight lang="nanoquery">a + b</syntaxhighlight> |
|||
The '*' operator may also be used to create a specific number of copies of a list or array. |
|||
<pre>% a = list() |
|||
% append a "a" "b" "c" |
|||
% println a |
|||
[a, b, c] |
|||
% println a * 5 |
|||
[a, b, c, a, b, c, a, b, c, a, b, c, a, b, c]</pre> |
|||
=={{header|Neko}}== |
|||
<syntaxhighlight lang="actionscript">/* |
|||
Array concatenation, in Neko |
|||
*/ |
|||
var a1 = $array(1,2,3,4) |
|||
var a2 = $array("abc", "def") |
|||
/* $array(a1, a2) creates an array of two arrays, $aconcat merges to one */ |
|||
var ac = $aconcat($array(a1, a2)) |
|||
$print(ac, "\n")</syntaxhighlight> |
|||
{{out}} |
|||
<pre>prompt$ nekoc array-concatenation.neko |
|||
prompt$ neko array-concatenation.n |
|||
[1,2,3,4,abc,def]</pre> |
|||
=={{header|Nemerle}}== |
=={{header|Nemerle}}== |
||
< |
<syntaxhighlight lang="nemerle">using System.Console; |
||
using Nemerle.Collections; |
using Nemerle.Collections; |
||
Line 1,269: | Line 3,094: | ||
foreach (i in arr12) Write($"$i "); |
foreach (i in arr12) Write($"$i "); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|NetRexx}}== |
=={{header|NetRexx}}== |
||
NetRexx arrays are identical to [[Java|Java's]] so all the techniques described in the [[#Java|Java]] section apply to NetRexx too. This example uses the <tt>Collection</tt> classes to merge two arrays. |
NetRexx arrays are identical to [[Java|Java's]] so all the techniques described in the [[#Java|Java]] section apply to NetRexx too. This example uses the <tt>Collection</tt> classes to merge two arrays. |
||
< |
<syntaxhighlight lang="netrexx">/* NetRexx */ |
||
options replace format comments java crossref |
options replace format comments java crossref nobinary |
||
cymru = [ 'Ogof Ffynnon Ddu', 'Ogof Draenen' ] |
cymru = [ 'Ogof Ffynnon Ddu', 'Ogof Draenen' ] |
||
Line 1,300: | Line 3,125: | ||
loop m_ = 0 to merged.length - 1 |
loop m_ = 0 to merged.length - 1 |
||
say m_ merged[m_] |
say m_ merged[m_] |
||
end m_ |
end m_</syntaxhighlight> |
||
{{out}} |
|||
</lang> |
|||
'''Output:''' |
|||
<pre> |
<pre> |
||
---------------------------------------- |
---------------------------------------- |
||
Line 1,318: | Line 3,142: | ||
=={{header|NewLISP}}== |
=={{header|NewLISP}}== |
||
< |
<syntaxhighlight lang="newlisp">; file: arraycon.lsp |
||
; url: http://rosettacode.org/wiki/Array_concatenation |
; url: http://rosettacode.org/wiki/Array_concatenation |
||
; author: oofoe 2012-01-28 |
; author: oofoe 2012-01-28 |
||
Line 1,333: | Line 3,157: | ||
(append '((x 56) (b 99)) '((z 34) (c 23) (r 88)))) |
(append '((x 56) (b 99)) '((z 34) (c 23) (r 88)))) |
||
(exit)</ |
(exit)</syntaxhighlight> |
||
Sample output: |
|||
{{out}} |
|||
<pre>Append lists: (3 a 5 3 1 2 3 4 5 6 7 8 9) |
<pre>Append lists: (3 a 5 3 1 2 3 4 5 6 7 8 9) |
||
Multi append: (this is a test of the emergency 3 2 1) |
Multi append: (this is a test of the emergency 3 2 1) |
||
Line 1,342: | Line 3,165: | ||
</pre> |
</pre> |
||
=={{header| |
=={{header|Nial}}== |
||
Examples tested to work with Q'Nial7 |
|||
<syntaxhighlight lang="nial"> a:= 1 2 3 |
|||
+-+-+-+ |
|||
|1|2|3| |
|||
+-+-+-+ |
|||
b:= 4 5 6 |
|||
+-+-+-+ |
|||
|4|5|6| |
|||
+-+-+-+</syntaxhighlight> |
|||
Table of lists: |
|||
<syntaxhighlight lang="nial"> a b |
|||
+-------+-------+ |
|||
|+-+-+-+|+-+-+-+| |
|||
||1|2|3|||4|5|6|| |
|||
|+-+-+-+|+-+-+-+| |
|||
+-------+-------+</syntaxhighlight> |
|||
Simple concatenation of two arrays/lists: |
|||
<syntaxhighlight lang="nial"> link a b |
|||
+-+-+-+-+-+-+ |
|||
|1|2|3|4|5|6| |
|||
+-+-+-+-+-+-+</syntaxhighlight> |
|||
Convert list of lists to table: |
|||
<syntaxhighlight lang="nial"> mix a b |
|||
+-+-+-+ |
|||
|1|2|3| |
|||
+-+-+-+ |
|||
|4|5|6| |
|||
+-+-+-+</syntaxhighlight> |
|||
Interchange levels of a list of lists: |
|||
<syntaxhighlight lang="nial"> pack a b |
|||
+-----+-----+-----+ |
|||
|+-+-+|+-+-+|+-+-+| |
|||
||1|4|||2|5|||3|6|| |
|||
|+-+-+|+-+-+|+-+-+| |
|||
+-----+-----+-----+</syntaxhighlight> |
|||
=={{header|Nim}}== |
|||
Dynamic sized Sequences can simply be concatenated: |
Dynamic sized Sequences can simply be concatenated: |
||
<syntaxhighlight lang="nim">var |
|||
<lang nimrod>var |
|||
x = @[1,2,3,4,5,6] |
x = @[1,2,3,4,5,6] |
||
y = @[7,8,9,10,11] |
y = @[7,8,9,10,11] |
||
z = x & y</ |
z = x & y</syntaxhighlight> |
||
Static sized Arrays: |
Static sized Arrays: |
||
<syntaxhighlight lang="nim">var |
|||
<lang nimrod>var |
|||
a = [1,2,3,4,5,6] |
a = [1,2,3,4,5,6] |
||
b = [7,8,9,10,11] |
b = [7,8,9,10,11] |
||
Line 1,356: | Line 3,225: | ||
c[0..5] = a |
c[0..5] = a |
||
c[6..10] = b</ |
c[6..10] = b</syntaxhighlight> |
||
=={{header|Nu}}== |
|||
<syntaxhighlight lang="nu"> |
|||
let a = [1 2 3] |
|||
let b = [4 5 6] |
|||
</syntaxhighlight> |
|||
By using the <code>++</code> operator: |
|||
<syntaxhighlight lang="nu">$a ++ $b</syntaxhighlight> |
|||
By using the spread operator (<code>...</code>): |
|||
<syntaxhighlight lang="nu">[...$a ...$b]</syntaxhighlight> |
|||
With <code>append</code> or <code>prepend</code>: |
|||
<syntaxhighlight lang="nu">$a | append $b</syntaxhighlight> |
|||
<syntaxhighlight lang="nu">$b | prepend $a</syntaxhighlight> |
|||
With <code>flatten</code>: |
|||
<syntaxhighlight lang="nu">[$a $b] | flatten</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
╭───┬───╮ |
|||
│ 0 │ 1 │ |
|||
│ 1 │ 2 │ |
|||
│ 2 │ 3 │ |
|||
│ 3 │ 4 │ |
|||
│ 4 │ 5 │ |
|||
│ 5 │ 6 │ |
|||
╰───┴───╯ |
|||
</pre> |
|||
=={{header|Oberon-2}}== |
|||
<syntaxhighlight lang="oberon2"> |
|||
MODULE ArrayConcat; |
|||
IMPORT |
|||
Out; |
|||
TYPE |
|||
IntArray = POINTER TO ARRAY OF INTEGER; |
|||
VAR |
|||
x, y, z: IntArray; |
|||
PROCEDURE InitArray(VAR x: IntArray;from: INTEGER); |
|||
VAR |
|||
i: LONGINT; |
|||
BEGIN |
|||
FOR i := 0 TO LEN(x^) - 1 DO |
|||
x[i] := from; |
|||
INC(from) |
|||
END |
|||
END InitArray; |
|||
PROCEDURE Concat(x,y: IntArray; VAR z: IntArray); |
|||
VAR |
|||
i: LONGINT; |
|||
BEGIN |
|||
ASSERT(LEN(x^) + LEN(y^) <= LEN(z^)); |
|||
FOR i := 0 TO LEN(x^) - 1 DO z[i] := x[i] END; |
|||
FOR i := 0 TO LEN(y^) - 1 DO z[i + LEN(x^)] := y[i] END |
|||
END Concat; |
|||
PROCEDURE Show(x: IntArray); |
|||
VAR |
|||
i: INTEGER; |
|||
BEGIN |
|||
i := 0; |
|||
Out.Char('['); |
|||
WHILE (i < LEN(x^)) DO |
|||
Out.LongInt(x[i],3);IF i < LEN(x^) - 1 THEN Out.Char(',') END; |
|||
INC(i) |
|||
END; |
|||
Out.Char(']');Out.Ln |
|||
END Show; |
|||
BEGIN |
|||
(* Standard types *) |
|||
NEW(x,5);InitArray(x,1); |
|||
NEW(y,10);InitArray(y,6); |
|||
NEW(z,LEN(x^) + LEN(y^)); |
|||
Concat(x,y,z); |
|||
Show(z) |
|||
END ArrayConcat. |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] |
|||
</pre> |
|||
=={{header|Objeck}}== |
=={{header|Objeck}}== |
||
< |
<syntaxhighlight lang="objeck"> |
||
bundle Default { |
bundle Default { |
||
class Arithmetic { |
class Arithmetic { |
||
Line 1,391: | Line 3,344: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Objective-C}}== |
=={{header|Objective-C}}== |
||
with immutable arrays: |
with immutable arrays: |
||
< |
<syntaxhighlight lang="objc">NSArray *arr1 = @[@1, @2, @3]; |
||
NSArray *arr2 = @[@4, @5, @6]; |
NSArray *arr2 = @[@4, @5, @6]; |
||
NSArray *arr3 = [arr1 arrayByAddingObjectsFromArray:arr2];</ |
NSArray *arr3 = [arr1 arrayByAddingObjectsFromArray:arr2];</syntaxhighlight> |
||
or adding onto a mutable array: |
or adding onto a mutable array: |
||
< |
<syntaxhighlight lang="objc">NSArray *arr1 = @[@1, @2, @3]; |
||
NSArray *arr2 = @[@4, @5, @6]; |
NSArray *arr2 = @[@4, @5, @6]; |
||
NSMutableArray *arr3 = [NSMutableArray arrayWithArray:arr1]; |
NSMutableArray *arr3 = [NSMutableArray arrayWithArray:arr1]; |
||
[arr3 addObjectsFromArray:arr2];</ |
[arr3 addObjectsFromArray:arr2];</syntaxhighlight> |
||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
It is more natural in OCaml to use lists instead of arrays: |
It is more natural in OCaml to use lists instead of arrays: |
||
< |
<syntaxhighlight lang="ocaml"># let list1 = [1; 2; 3];; |
||
val list1 : int list = [1; 2; 3] |
val list1 : int list = [1; 2; 3] |
||
# let list2 = [4; 5; 6];; |
# let list2 = [4; 5; 6];; |
||
val list2 : int list = [4; 5; 6] |
val list2 : int list = [4; 5; 6] |
||
# let list1and2 = list1 @ list2;; |
# let list1and2 = list1 @ list2;; |
||
val list1and2 : int list = [1; 2; 3; 4; 5; 6]</ |
val list1and2 : int list = [1; 2; 3; 4; 5; 6]</syntaxhighlight> |
||
If you want to use arrays: |
If you want to use arrays: |
||
< |
<syntaxhighlight lang="ocaml"># let array1 = [|1; 2; 3|];; |
||
val array1 : int array = [|1; 2; 3|] |
val array1 : int array = [|1; 2; 3|] |
||
# let array2 = [|4; 5; 6|];; |
# let array2 = [|4; 5; 6|];; |
||
val array2 : int array = [|4; 5; 6|] |
val array2 : int array = [|4; 5; 6|] |
||
# let array1and2 = Array.append array1 array2;; |
# let array1and2 = Array.append array1 array2;; |
||
val array1and2 : int array = [|1; 2; 3; 4; 5; 6|]</ |
val array1and2 : int array = [|1; 2; 3; 4; 5; 6|]</syntaxhighlight> |
||
=={{header|Odin}}== |
|||
<syntaxhighlight lang="odin">package main |
|||
import "core:fmt" |
|||
import "core:slice" |
|||
main :: proc() { |
|||
x: [3]int = {1, 2, 3} |
|||
y: [3]int = {4, 5, 6} |
|||
xy: [len(x) + len(y)]int |
|||
copy(xy[:], x[:]) |
|||
copy(xy[len(x):], y[:]) |
|||
fmt.println(xy) |
|||
}</syntaxhighlight> |
|||
===Using slices=== |
|||
<syntaxhighlight lang="odin">package main |
|||
import "core:fmt" |
|||
import "core:slice" |
|||
main :: proc() { |
|||
x: [3]int = {1, 2, 3} |
|||
y: [3]int = {4, 5, 6} |
|||
xy := slice.concatenate([][]int{x[:], y[:]}) |
|||
defer delete(xy) |
|||
fmt.println(xy) |
|||
}</syntaxhighlight> |
|||
=={{header|Oforth}}== |
|||
<syntaxhighlight lang="oforth">import: mapping |
|||
[1, 2, 3 ] [ 4, 5, 6, 7 ] + </syntaxhighlight> |
|||
=={{header|Onyx}}== |
|||
<syntaxhighlight lang="onyx"># With two arrays on the stack, cat pops |
|||
# them, concatenates them, and pushes the result back |
|||
# on the stack. This works with arrays of integers, |
|||
# strings, or whatever. For example, |
|||
[1 2 3] [4 5 6] cat # result: [1 2 3 4 5 6] |
|||
[`abc' `def'] [`ghi' `jkl'] cat # result: [`abc' `def' `ghi' `jkl'] |
|||
# To concatenate more than two arrays, push the number of arrays |
|||
# to concatenate onto the stack and use ncat. For example, |
|||
[1 true `a'] [2 false `b'] [`3rd array'] 3 ncat |
|||
# leaves [1 true `a' 2 false `b' `3rd array'] on the stack</syntaxhighlight> |
|||
=={{header|ooRexx}}== |
=={{header|ooRexx}}== |
||
<syntaxhighlight lang="oorexx">a = .array~of(1,2,3) |
|||
<lang ooRexx> |
|||
a = .array~of(1,2,3) |
|||
say "Array a has " a~items "items" |
say "Array a has " a~items "items" |
||
b = .array~of(4,5,6) |
b = .array~of(4,5,6) |
||
say "Array b has " b~items "items" |
say "Array b has " b~items "items" |
||
a~appendall(b) -- adds all items from b to a |
a~appendall(b) -- adds all items from b to a |
||
say "Array a now has " a~items " |
say "Array a now has " a~items "items"</syntaxhighlight> |
||
{{out}} |
|||
</lang> |
|||
<pre>Array a has 3 items |
|||
Array b has 3 items |
|||
Array a now has 6 items</pre> |
|||
=={{header|Order}}== |
=={{header|Order}}== |
||
Order supports two main aggregate types: tuples and sequences (similar to lists in other languages). Most "interesting" operations are limited to sequences, but both support an append operation, and each can be converted to the other. |
Order supports two main aggregate types: tuples and sequences (similar to lists in other languages). Most "interesting" operations are limited to sequences, but both support an append operation, and each can be converted to the other. |
||
< |
<syntaxhighlight lang="c">#include <order/interpreter.h> |
||
ORDER_PP( 8tuple_append(8tuple(1, 2, 3), 8tuple(4, 5, 6), 8pair(7, 8)) ) |
ORDER_PP( 8tuple_append(8tuple(1, 2, 3), 8tuple(4, 5, 6), 8pair(7, 8)) ) |
||
Line 1,440: | Line 3,449: | ||
ORDER_PP( 8seq_append(8seq(1, 2, 3), 8seq(4, 5, 6), 8seq(7, 8)) ) |
ORDER_PP( 8seq_append(8seq(1, 2, 3), 8seq(4, 5, 6), 8seq(7, 8)) ) |
||
// -> (1)(2)(3)(4)(5)(6)(7)(8)</ |
// -> (1)(2)(3)(4)(5)(6)(7)(8)</syntaxhighlight> |
||
=={{header|OxygenBasic}}== |
=={{header|OxygenBasic}}== |
||
< |
<syntaxhighlight lang="oxygenbasic"> |
||
'CREATE DYNAMIC ARRAY SPACES USING STRINGS |
'CREATE DYNAMIC ARRAY SPACES USING STRINGS |
||
Line 1,466: | Line 3,475: | ||
print a[7] 'result 70 |
print a[7] 'result 70 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Oz}}== |
=={{header|Oz}}== |
||
List are concatenated with <code>List.append</code> (shortcut: <code>Append</code>). Tuples are concatened with <code>Tuple.append</code>. Arrays do exist in Oz, but are rarely used. |
List are concatenated with <code>List.append</code> (shortcut: <code>Append</code>). Tuples are concatened with <code>Tuple.append</code>. Arrays do exist in Oz, but are rarely used. |
||
< |
<syntaxhighlight lang="oz">%% concatenating 2 lists |
||
{Append [a b] [c d]} = [a b c d] |
{Append [a b] [c d]} = [a b c d] |
||
%% concatenating 2 tuples |
%% concatenating 2 tuples |
||
{Tuple.append t(1 2 3) u(4 5 6)} = u(1 2 3 4 5 6)</ |
{Tuple.append t(1 2 3) u(4 5 6)} = u(1 2 3 4 5 6)</syntaxhighlight> |
||
=={{header|PARI/GP}}== |
=={{header|PARI/GP}}== |
||
<lang |
<syntaxhighlight lang="parigp">concat(u,v)</syntaxhighlight> |
||
=={{header|Pascal}}== |
=={{header|Pascal}}== |
||
''See [[#Delphi|Delphi]] and [[#Free Pascal|Free Pascal]]'' |
|||
=={{header|PascalABC.NET}}== |
|||
<syntaxhighlight lang="perl"> |
|||
## |
|||
var a := |1,2,3,4|; |
|||
var b := Arr(5..8); |
|||
var c := a + b; |
|||
c.Println; |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
1 2 3 4 5 6 7 8 |
|||
</pre> |
|||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
In Perl, arrays placed into list context are flattened: |
In Perl, arrays placed into list context are flattened: |
||
< |
<syntaxhighlight lang="perl">my @arr1 = (1, 2, 3); |
||
my @arr2 = (4, 5, 6); |
my @arr2 = (4, 5, 6); |
||
my @arr3 = (@arr1, @arr2);</ |
my @arr3 = (@arr1, @arr2);</syntaxhighlight> |
||
The <code>[http://perldoc.perl.org/functions/push.html push]</code> function appends elements onto an existing array: |
The <code>[http://perldoc.perl.org/functions/push.html push]</code> function appends elements onto an existing array: |
||
< |
<syntaxhighlight lang="perl">my @arr1 = (1, 2, 3); |
||
my @arr2 = (4, 5, 6); |
my @arr2 = (4, 5, 6); |
||
push @arr1, @arr2; |
push @arr1, @arr2; |
||
print "@arr1\n"; # prints "1 2 3 4 5 6"</ |
print "@arr1\n"; # prints "1 2 3 4 5 6"</syntaxhighlight> |
||
=={{header| |
=={{header|Phix}}== |
||
{{libheader|Phix/basics}} |
|||
<!--<syntaxhighlight lang="phix">--> |
|||
<span style="color: #004080;">sequence</span> <span style="color: #000000;">s1</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{<span style="color: #000000;">1<span style="color: #0000FF;">,<span style="color: #000000;">2<span style="color: #0000FF;">,<span style="color: #000000;">3<span style="color: #0000FF;">}<span style="color: #0000FF;">,</span> <span style="color: #000000;">s2</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{<span style="color: #000000;">4<span style="color: #0000FF;">,<span style="color: #000000;">5<span style="color: #0000FF;">,<span style="color: #000000;">6<span style="color: #0000FF;">}</span> |
|||
<span style="color: #0000FF;">?</span> <span style="color: #000000;">s1</span> <span style="color: #0000FF;">&</span> <span style="color: #000000;">s2 |
|||
<!--</syntaxhighlight>--> |
|||
{{out}} |
|||
<pre> |
|||
{1,2,3,4,5,6} |
|||
</pre> |
|||
=={{header|Phixmonti}}== |
|||
<lang perl6># the comma ',' can be used to concatenate arrays: |
|||
<syntaxhighlight lang="phixmonti">1.0 "Hello" 3 2 / 4 2.1 power 4 tolist 5 6 7 8 4 tolist chain print</syntaxhighlight> |
|||
sub concatenateArrays(@a, @b) { |
|||
With syntactic sugar |
|||
@a, @b |
|||
<syntaxhighlight lang="phixmonti">include ..\Utilitys.pmt |
|||
} |
|||
( 1.0 "Hello" 3 2 / 4 2.1 power ) ( 5 6 7 8 ) chain print</syntaxhighlight> |
|||
my @a1 = (1,2,3); |
|||
my @a2 = (2,3,4); |
|||
concatenateArrays(@a1,@a2).join(", ").say;</lang> |
|||
=={{header|PHP}}== |
=={{header|PHP}}== |
||
< |
<syntaxhighlight lang="php">$arr1 = array(1, 2, 3); |
||
$arr2 = array(4, 5, 6); |
$arr2 = array(4, 5, 6); |
||
$arr3 = array_merge($arr1, $arr2);</ |
$arr3 = array_merge($arr1, $arr2);</syntaxhighlight> |
||
=={{header|Picat}}== |
|||
Picat has support for both lists and arrays and arrays can be much faster. Some list functions works with both |
|||
lists and arrays, but some doesn't, e.g. append/3. In those cases one have to convert arrays to a list with to_list/1, |
|||
and back again with to_array/1. |
|||
<syntaxhighlight lang="picat">go => |
|||
L1 = {1,2,3,4,5}, % define an array with {} |
|||
L2 = {6,7,8,9}, |
|||
% The built-in array/list concatenation |
|||
println(L1 ++ L2), |
|||
% Using the built-in append/3 works only on lists |
|||
% so the arrays must be converted to lists. |
|||
append(L1.to_list,L2.to_list,L3), |
|||
println(L3.to_array), |
|||
nl.</syntaxhighlight> |
|||
{{out}} |
|||
<pre>{1,2,3,4,5,6,7,8,9} |
|||
{1,2,3,4,5,6,7,8,9} |
|||
</pre> |
|||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
Line 1,514: | Line 3,566: | ||
There are destructive concatenations: |
There are destructive concatenations: |
||
< |
<syntaxhighlight lang="picolisp">: (setq A (1 2 3) B '(a b c)) |
||
-> (a b c) |
-> (a b c) |
||
: (conc A B) # Concatenate lists in 'A' and 'B' |
: (conc A B) # Concatenate lists in 'A' and 'B' |
||
-> (1 2 3 a b c) |
-> (1 2 3 a b c) |
||
: A |
: A |
||
-> (1 2 3 a b c) # Side effect: List in 'A' is modified!</ |
-> (1 2 3 a b c) # Side effect: List in 'A' is modified!</syntaxhighlight> |
||
and non-destructive concatenations: |
and non-destructive concatenations: |
||
< |
<syntaxhighlight lang="picolisp">: (setq A (1 2 3) B '(a b c)) |
||
-> (a b c) |
-> (a b c) |
||
: (append A B) # Append lists in 'A' and 'B' |
: (append A B) # Append lists in 'A' and 'B' |
||
Line 1,528: | Line 3,580: | ||
-> (1 2 3) |
-> (1 2 3) |
||
: B |
: B |
||
-> (a b c) # Arguments are not modified</ |
-> (a b c) # Arguments are not modified</syntaxhighlight> |
||
=={{header|Pike}}== |
|||
<syntaxhighlight lang="pike">int main() { |
|||
array arr1 = ({1, 2, 3}); |
|||
array arr2 = ({4, 5, 6}); |
|||
array arr3 = arr1 + arr2; |
|||
}</syntaxhighlight> |
|||
=={{header|PL/I}}== |
=={{header|PL/I}}== |
||
Trivial example requires no computational statement. |
Trivial example requires no computational statement. |
||
Note that the arrays are not in static storage: |
Note that the arrays are not in static storage: |
||
<syntaxhighlight lang="pl/i"> |
|||
<lang PL/I> |
|||
declare x(12) fixed; |
declare x(12) fixed; |
||
declare b(5) fixed defined x; |
declare b(5) fixed defined x; |
||
declare c(7) fixed defined x(1sub+5); |
declare c(7) fixed defined x(1sub+5); |
||
</syntaxhighlight> |
|||
</lang> |
|||
A more general example using dynamic bounds. |
A more general example using dynamic bounds. |
||
Again, no computation statement is required. |
Again, no computation statement is required. |
||
<lang> |
<syntaxhighlight lang="text"> |
||
declare x(m+n) fixed; |
declare x(m+n) fixed; |
||
declare b(m) fixed defined x; |
declare b(m) fixed defined x; |
||
declare c(n) fixed defined x(1sub+hbound(b,1)); |
declare c(n) fixed defined x(1sub+hbound(b,1)); |
||
</syntaxhighlight> |
|||
</lang> |
|||
An alternative, that can be used to advantage for matrices |
An alternative, that can be used to advantage for matrices |
||
Line 1,551: | Line 3,610: | ||
are used in the declarations, the bounds can be dynamic. |
are used in the declarations, the bounds can be dynamic. |
||
Matrix B is extended by placing matrix C on its diagonal: |
Matrix B is extended by placing matrix C on its diagonal: |
||
<lang> |
<syntaxhighlight lang="text"> |
||
declare a(5,6) fixed; |
declare a(5,6) fixed; |
||
declare b(3,4) fixed defined a(1sub, 2sub); |
declare b(3,4) fixed defined a(1sub, 2sub); |
||
Line 1,566: | Line 3,625: | ||
put skip list ('Composite matrix:'); |
put skip list ('Composite matrix:'); |
||
put skip edit (a) ( skip, (hbound(a,2)) f(5,0) ); |
put skip edit (a) ( skip, (hbound(a,2)) f(5,0) ); |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
|||
Output: |
|||
<lang> |
<syntaxhighlight lang="text"> |
||
Please type elements for a 3 x 4 matrix: |
Please type elements for a 3 x 4 matrix: |
||
Line 1,583: | Line 3,642: | ||
0 0 0 0 15 16 |
0 0 0 0 15 16 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Plain English}}== |
|||
Plain English has these functions for concatenating two sets of things: |
|||
<syntaxhighlight lang="text"> |
|||
To append some things to some other things: |
|||
Put the things' first into a thing. |
|||
If the thing is nil, exit. |
|||
Remove the thing from the things. |
|||
Append the thing to the other things. |
|||
Repeat. |
|||
To prepend some things to some other things: |
|||
Get a thing from the things (backwards). |
|||
If the thing is nil, exit. |
|||
Remove the thing from the things. |
|||
Prepend the thing to the other things. |
|||
Repeat. |
|||
</syntaxhighlight> |
|||
=={{header|Pony}}== |
|||
<syntaxhighlight lang="pony"> |
|||
actor Main |
|||
new create(env:Env)=> |
|||
var a:Array[I32]=Array[I32](4) |
|||
var b:Array[I32]=Array[I32](2) |
|||
a.push(1) |
|||
a.push(2) |
|||
a.push(3) |
|||
a.push(4) |
|||
b.push(5) |
|||
b.push(6) |
|||
a.concat(b.values()) |
|||
for i in a.values() do |
|||
env.out.print(i.string()) |
|||
end |
|||
</syntaxhighlight> |
|||
=={{header|PostScript}}== |
=={{header|PostScript}}== |
||
{{libheader|initlib}} |
{{libheader|initlib}} |
||
< |
<syntaxhighlight lang="postscript"> |
||
[1 2 3 4] [5 6 7 8] concat |
[1 2 3 4] [5 6 7 8] concat |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|PowerShell}}== |
=={{header|PowerShell}}== |
||
< |
<syntaxhighlight lang="powershell">$a = 1,2,3 |
||
$b = 4,5,6 |
$b = 4,5,6 |
||
$c = $a + $b |
$c = $a + $b |
||
Write-Host $c</ |
Write-Host $c</syntaxhighlight> |
||
=={{header|Processing}}== |
|||
<syntaxhighlight lang="processing"> |
|||
int[] a = {1, 2, 3}, b = {4, 5, 6}; |
|||
int[] c = concat(a, b); |
|||
</syntaxhighlight> |
|||
=={{header|Prolog}}== |
=={{header|Prolog}}== |
||
< |
<syntaxhighlight lang="prolog"> |
||
?- append([1,2,3],[4,5,6],R). |
?- append([1,2,3],[4,5,6],R). |
||
R = [1, 2, 3, 4, 5, 6]. |
R = [1, 2, 3, 4, 5, 6]. |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|PureBasic}}== |
=={{header|PureBasic}}== |
||
< |
<syntaxhighlight lang="purebasic">Procedure displayArray(Array a(1), msg.s) |
||
Protected i |
Protected i |
||
Print(msg + " [") |
Print(msg + " [") |
||
Line 1,650: | Line 3,753: | ||
Input() |
Input() |
||
CloseConsole() |
CloseConsole() |
||
EndIf</ |
EndIf</syntaxhighlight> |
||
{{out}} |
|||
Sample output: |
|||
<pre>a: [5, 2, -4, -1, -2] |
<pre>a: [5, 2, -4, -1, -2] |
||
b: [0, -4, -1] |
b: [0, -4, -1] |
||
Line 1,657: | Line 3,760: | ||
=={{header|Python}}== |
=={{header|Python}}== |
||
The <code>[http://docs.python.org/library/stdtypes.html#sequence-types-str-unicode-list-tuple-buffer-xrange +]</code> operator concatenates two lists and returns a new list. |
The <code>[http://docs.python.org/library/stdtypes.html#sequence-types-str-unicode-list-tuple-buffer-xrange +]</code> operator concatenates two lists and returns a new list. |
||
The <code>[http://docs.python.org/library/stdtypes.html#mutable-sequence-types list.extend]</code> method appends elements of another list to the receiver. |
|||
<lang python>arr1 = [1, 2, 3] |
|||
<syntaxhighlight lang="python">arr1 = [1, 2, 3] |
|||
arr2 = [4, 5, 6] |
arr2 = [4, 5, 6] |
||
arr3 = [7, 8, 9] |
arr3 = [7, 8, 9] |
||
Line 1,664: | Line 3,768: | ||
assert arr4 == [1, 2, 3, 4, 5, 6] |
assert arr4 == [1, 2, 3, 4, 5, 6] |
||
arr4.extend(arr3) |
arr4.extend(arr3) |
||
assert arr4 == [1, 2, 3, 4, 5, 6, 7, 8, 9]</ |
assert arr4 == [1, 2, 3, 4, 5, 6, 7, 8, 9]</syntaxhighlight> |
||
Note: list.extend is normally accomplished using the += operator like this: |
Note: list.extend is normally accomplished using the += operator like this: |
||
< |
<syntaxhighlight lang="python">arr5 = [4, 5, 6] |
||
arr6 = [7, 8, 9] |
arr6 = [7, 8, 9] |
||
arr6 += arr5 |
arr6 += arr5 |
||
assert arr6 == [7, 8, 9, 4, 5, 6]</ |
assert arr6 == [7, 8, 9, 4, 5, 6]</syntaxhighlight> |
||
=={{header|Q}}== |
|||
<syntaxhighlight lang="q">list1:1 2 3 |
|||
list2:4 5 6 |
|||
list1,list2</syntaxhighlight> |
|||
=={{header|QBasic}}== |
|||
{{works with|QBasic|1.1}} |
|||
{{works with|QuickBasic|4.5}} |
|||
<syntaxhighlight lang="qbasic">FUNCTION ConcatArrays(a(), b()) |
|||
ta = UBOUND(a) |
|||
tb = UBOUND(b) |
|||
nt = ta + tb |
|||
FOR i = ta + 1 TO nt |
|||
a(i) = b(i - ta) |
|||
NEXT i |
|||
ConcatArrays = nt |
|||
END FUNCTION |
|||
dimen = 5 |
|||
DIM a(dimen) |
|||
DIM b(dimen) |
|||
FOR i = 1 TO dimen |
|||
a(i) = i |
|||
b(i) = i + dimen |
|||
NEXT i |
|||
nt = ConcatArrays(a(), b()) |
|||
FOR i = 1 TO nt |
|||
PRINT a(i); |
|||
IF i < nt THEN PRINT ", "; |
|||
NEXT i |
|||
</syntaxhighlight> |
|||
=={{header|QB64}}== |
|||
<syntaxhighlight lang="qb64"> |
|||
Dim As Integer First, Second |
|||
First = 5: Second = 8 |
|||
Dim As Integer Array1(1 To First), Array2(1 To Second), ArrayResult(1 To First + Second) |
|||
Init Array1(), 2 |
|||
Print "First array" |
|||
ShowArr Array1() |
|||
Sleep 2 |
|||
Print "Second array" |
|||
Init Array2(), 5 |
|||
ShowArr Array2() |
|||
Sleep 2 |
|||
Print "Final array" |
|||
ConcatArray Array1(), Array2(), ArrayResult() |
|||
ShowArr ArrayResult() |
|||
End |
|||
Sub Init (A() As Integer, R As Integer) |
|||
Dim Index As Integer |
|||
For Index = 1 To UBound(a) |
|||
A(Index) = Index * R |
|||
Next |
|||
End Sub |
|||
Sub ShowArr (A() As Integer) |
|||
Dim Index As Integer |
|||
For Index = 1 To UBound(a) |
|||
Print A(Index) |
|||
Next |
|||
End Sub |
|||
Sub ConcatArray (A() As Integer, B() As Integer, R() As Integer) |
|||
Dim Index As Integer |
|||
For Index = 1 To UBound(a) |
|||
R(Index) = A(Index) |
|||
Next |
|||
For Index = (1) To (UBound(b)) |
|||
R(Index + UBound(a)) = B(Index) |
|||
Next |
|||
End Sub |
|||
</syntaxhighlight> |
|||
=={{header|Quackery}}== |
|||
The word <code>join</code> joins two nests. |
|||
Illustrated with a dialogue in the Quackery shell. (REPL) |
|||
<pre>> quackery |
|||
Welcome to Quackery. |
|||
Enter "leave" to leave the shell. |
|||
/O> ' [ [ 1 2 ] [ 3 4 ] [ 5 6 ] ] |
|||
... ' [ [ 7 8 ] [ 9 0 ] ] join echo |
|||
... |
|||
[ [ 1 2 ] [ 3 4 ] [ 5 6 ] [ 7 8 ] [ 9 0 ] ] |
|||
Stack empty. |
|||
/O> leave |
|||
... |
|||
Goodbye. |
|||
</pre> |
|||
=={{header|R}}== |
=={{header|R}}== |
||
<syntaxhighlight lang="r"> |
|||
<lang R> |
|||
a1 <- c(1, 2, 3) |
a1 <- c(1, 2, 3) |
||
a2 <- c(3, 4, 5) |
a2 <- c(3, 4, 5) |
||
a3 <- c(a1, a2) |
a3 <- c(a1, a2) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Racket}}== |
=={{header|Racket}}== |
||
< |
<syntaxhighlight lang="racket"> |
||
(vector-append #(1 2 3 4) #(5 6 7) #(8 9 10)) |
(vector-append #(1 2 3 4) #(5 6 7) #(8 9 10)) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
|||
Output: |
|||
<pre> |
<pre> |
||
'#(1 2 3 4 5 6 7 8 9 10) |
'#(1 2 3 4 5 6 7 8 9 10) |
||
</pre> |
</pre> |
||
=={{header|Raku}}== |
|||
(formerly Perl 6) |
|||
{{works with|Rakudo|2018.06}} |
|||
<syntaxhighlight lang="raku" line>my @array1 = 1, 2, 3; |
|||
my @array2 = 4, 5, 6; |
|||
# If you want to concatenate two array to form a third, |
|||
# either use the slip operator "|", to flatten each array. |
|||
my @array3 = |@array1, |@array2; |
|||
say @array3; |
|||
# or just flatten both arrays in one fell swoop |
|||
@array3 = flat @array1, @array2; |
|||
say @array3; |
|||
# On the other hand, if you just want to add the elements |
|||
# of the second array to the first, use the .append method. |
|||
say @array1.append: @array2;</syntaxhighlight> |
|||
{{Out}} |
|||
<pre>[1 2 3 4 5 6] |
|||
[1 2 3 4 5 6] |
|||
[1 2 3 4 5 6]</pre> |
|||
=={{header|RapidQ}}== |
|||
<syntaxhighlight lang="vb"> |
|||
DEFINT A(1 to 4) = {1, 2, 3, 4} |
|||
DEFINT B(1 to 4) = {10, 20, 30, 40} |
|||
'Append array B to array A |
|||
Redim A(1 to 8) as integer |
|||
MEMCPY(varptr(A(5)), varptr(B(1)), Sizeof(integer)*4) |
|||
</syntaxhighlight> |
|||
=={{header|Rapira}}== |
|||
<syntaxhighlight lang="rapira">arr1 := <* 1, 2, 3 *> |
|||
arr2 := <* 4, 5, 6 *> |
|||
output: arr1 + arr2</syntaxhighlight> |
|||
=={{header|REBOL}}== |
=={{header|REBOL}}== |
||
<syntaxhighlight lang="rebol"> |
|||
<lang REBOL> |
|||
a1: [1 2 3] |
a1: [1 2 3] |
||
a2: [4 5 6] |
a2: [4 5 6] |
||
Line 1,698: | Line 3,955: | ||
append/only a1 a3 ; -> [1 2 3 4 5 6 [7 8 9]] |
append/only a1 a3 ; -> [1 2 3 4 5 6 [7 8 9]] |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header| |
=={{header|Red}}== |
||
<syntaxhighlight lang="red">>> arr1: ["a" "b" "c"] |
|||
<lang Retro>needs array' |
|||
>> arr2: ["d" "e" "f"] |
|||
>> append arr1 arr2 |
|||
== ["a" "b" "c" "d" "e" "f"] |
|||
>> arr3: [1 2 3] |
|||
>> insert arr1 arr3 |
|||
>> arr1 |
|||
== [1 2 3 "a" "b" "c" "d" "e" "f"] |
|||
>> arr4: [22 33 44] |
|||
== [22 33 44] |
|||
>> append/only arr1 arr4 |
|||
== [1 2 3 "a" "b" "c" "d" "e" "f" [22 33 44]]</syntaxhighlight> |
|||
=={{header|ReScript}}== |
|||
^array'new{ 1 2 3 } ^array'new{ 4 5 6 } ^array'append</lang> |
|||
<syntaxhighlight lang="rescript">Js.Array2.concat(["a", "b"], ["c", "d", "e"]) == ["a", "b", "c", "d", "e"]</syntaxhighlight> |
|||
=={{header|Retro}}== |
|||
<syntaxhighlight lang="retro">{ #1 #2 #3 } { #4 #5 #6 } a:append</syntaxhighlight> |
|||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
REXX doesn't have arrays as such, but it has something that looks, feels, and tastes like arrays: |
REXX doesn't have arrays as such, but it has something that looks, feels, and tastes like arrays: |
||
::::* stemmed variables |
|||
<br><br>Simply, a stemmed array is a variable with an appended dot (.) followed by a constant (such as an integer). |
|||
<br>There is no way to preallocate a stemmed variable, REXX just assigns them as they are created (assigned a value). |
|||
Simply, a stemmed array is a variable with an appended dot ('''.''') followed by a symbol (it's normally an integer or an alphanumeric name). |
|||
<br><br> |
|||
As such, there isn't an easy way to keep track of the number of "elements" in a REXX "array". |
|||
There is no way to preallocate a stemmed variable, REXX just assigns them as they are created (assigned a value). <br> |
|||
<br>Consider: |
|||
<lang rexx>a.1 = 10 |
|||
As such, there isn't an easy way to keep track of the number of "elements" in a REXX "array" (unless the programmer maintains a list). <br> |
|||
Consider: |
|||
<syntaxhighlight lang="rexx">a.1 = 10 |
|||
a.2 = 22.7 |
a.2 = 22.7 |
||
a.7 = -12</ |
a.7 = -12</syntaxhighlight> |
||
where now we have three "elements", and they are disjointed (another word for ''sparse''). |
where now we have three "elements", and they are disjointed (another word for ''sparse''). |
||
<br>There are ways to handle this in REXX however. |
<br>There are ways to handle this in REXX however. |
||
Line 1,720: | Line 3,996: | ||
<br>assuming that the stemmed variables are sequential. |
<br>assuming that the stemmed variables are sequential. |
||
<br><br>'''example:''' |
<br><br>'''example:''' |
||
< |
<syntaxhighlight lang="rexx">fact.0=8 |
||
fact.1= 1 |
fact.1= 1 |
||
fact.2= 2 |
fact.2= 2 |
||
Line 1,728: | Line 4,004: | ||
fact.6= 720 |
fact.6= 720 |
||
fact.7= 5040 |
fact.7= 5040 |
||
fact.8=40320</ |
fact.8=40320</syntaxhighlight> |
||
To concat two "arrays" in REXX, the following assumes that the stemmed variables are in order, with no gaps, and none have a "null" value. |
To concat two "arrays" in REXX, the following assumes that the stemmed variables are in order, with no gaps, and none have a "null" value. |
||
< |
<syntaxhighlight lang="rexx">/*REXX program to demonstrates how to perform array concatenation.*/ |
||
p.= /*(below) a short list of primes.*/ |
p.= /*(below) a short list of primes.*/ |
||
Line 1,751: | Line 4,027: | ||
say 'c.'m"="c.m /*show a "merged" C array nums.*/ |
say 'c.'m"="c.m /*show a "merged" C array nums.*/ |
||
end /*m*/ |
end /*m*/ |
||
/*stick a fork in it, we're done.*/</ |
/*stick a fork in it, we're done.*/</syntaxhighlight> |
||
{{out}} |
|||
'''output''' |
|||
<pre> |
|||
<pre style="height:30ex;overflow:scroll"> |
|||
elements= 23 |
elements= 23 |
||
Line 1,780: | Line 4,056: | ||
c.23=55 |
c.23=55 |
||
</pre> |
</pre> |
||
=={{header|Ring}}== |
|||
<syntaxhighlight lang="ring"> |
|||
arr1 = [1, 2, 3] |
|||
arr2 = [4, 5, 6] |
|||
arr3 = [7, 8, 9] |
|||
arr4 = arr1 + arr2 |
|||
see arr4 |
|||
see nl |
|||
arr5 = arr4 + arr3 |
|||
see arr5 |
|||
</syntaxhighlight> |
|||
=={{header|RLaB}}== |
=={{header|RLaB}}== |
||
Line 1,785: | Line 4,073: | ||
In RLaB the matrices can be appended (column-wise) or stacked (row-wise). |
In RLaB the matrices can be appended (column-wise) or stacked (row-wise). |
||
Consider few examples: |
Consider few examples: |
||
<syntaxhighlight lang="rlab"> |
|||
<lang RLaB> |
|||
>> x = [1, 2, 3] |
>> x = [1, 2, 3] |
||
>> y = [4, 5, 6] |
>> y = [4, 5, 6] |
||
Line 1,799: | Line 4,087: | ||
4 5 6 |
4 5 6 |
||
>> |
>> |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|RPL}}== |
|||
In RPL, what is called arrays are actually vectors. Sets of numbers can be stored either in such data structures or in lists, depending on the planned use. Vectors are great for arithmetics, but lists are more versatile. |
|||
{{works with|Halcyon Calc|4.2.7}} |
|||
=== Vector concatenation=== |
|||
≪ SWAP ARRY→ LIST→ DROP → n |
|||
≪ n 1 + ROLL ARRY→ LIST→ DROP |
|||
n + 1 →LIST →ARRY |
|||
≫ ≫ 'CONCAT' STO |
|||
[1 2 3] [4 5] CONCAT |
|||
{{out}} |
|||
<pre> |
|||
1: [1 2 3 4 5] |
|||
</pre> |
|||
A shorter version, without any local variable: |
|||
≪ SWAP ARRY→ 1 GET →LIST |
|||
SWAP ARRY→ 1 GET →LIST |
|||
+ LIST→ { } + →ARRY |
|||
≫ 'CONCAT' STO |
|||
=== List concatenation=== |
|||
No need for a program to do that: |
|||
{1 2 3} {4 5} + |
|||
{{out}} |
|||
<pre> |
|||
1: {1 2 3 4 5} |
|||
</pre> |
|||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
The <code>[http://www.ruby-doc.org/core/classes/Array.html#M002209 Array#+]</code> method concatenates two arrays and returns a new array. The <code>[http://www.ruby-doc.org/core/classes/Array.html#M002166 Array#concat]</code> method appends elements of another array to the receiver. |
The <code>[http://www.ruby-doc.org/core/classes/Array.html#M002209 Array#+]</code> method concatenates two arrays and returns a new array. The <code>[http://www.ruby-doc.org/core/classes/Array.html#M002166 Array#concat]</code> method appends elements of another array to the receiver. |
||
< |
<syntaxhighlight lang="ruby">arr1 = [1, 2, 3] |
||
arr2 = [4, 5, 6] |
arr2 = [4, 5, 6] |
||
arr3 = [7, 8, 9] |
arr3 = [7, 8, 9] |
||
arr4 = arr1 + arr2 # => [1, 2, 3, 4, 5, 6] |
arr4 = arr1 + arr2 # => [1, 2, 3, 4, 5, 6] |
||
arr4.concat(arr3) # => [1, 2, 3, 4, 5, 6, 7, 8, 9]</ |
arr4.concat(arr3) # => [1, 2, 3, 4, 5, 6, 7, 8, 9]</syntaxhighlight> |
||
Or use flatten(1): |
|||
<syntaxhighlight lang="ruby"> |
|||
# concat multiple arrays: |
|||
[arr1,arr2,arr3].flatten(1) |
|||
# ignore nil: |
|||
[arr1,arr2,arr3].compact.flatten(1) |
|||
</syntaxhighlight> |
|||
=={{header|Rust}}== |
|||
<syntaxhighlight lang="rust">fn main() { |
|||
let a_vec = vec![1, 2, 3, 4, 5]; |
|||
let b_vec = vec![6; 5]; |
|||
let c_vec = concatenate_arrays(&a_vec, &b_vec); |
|||
println!("{:?} ~ {:?} => {:?}", a_vec, b_vec, c_vec); |
|||
} |
|||
fn concatenate_arrays<T: Clone>(x: &[T], y: &[T]) -> Vec<T> { |
|||
let mut concat = x.to_vec(); |
|||
concat.extend_from_slice(y); |
|||
concat |
|||
} |
|||
</syntaxhighlight> |
|||
Or, with iterators: |
|||
<syntaxhighlight lang="rust">fn concatenate_arrays<T: Clone>(x: &[T], y: &[T]) -> Vec<T> { |
|||
x.iter().chain(y).cloned().collect() |
|||
} |
|||
</syntaxhighlight> |
|||
=={{header|S-lang}}== |
|||
<syntaxhighlight lang="s-lang">variable a = [1, 2, 3]; |
|||
variable b = [4, 5, 6], c;</syntaxhighlight> |
|||
a+b is perfectly valid in S-Lang, but instead of the problem's desired effect, |
|||
it gives you a new array with each coorresponding element from a and b added. |
|||
But because arrays automatically 'flatten' when defined, concatenation is as |
|||
simple as: |
|||
<syntaxhighlight lang="s-lang">c = [a, b];</syntaxhighlight> |
|||
Use of lists is more traditional; lists don't 'flatten', so we use either |
|||
list_concat() to create a new concatenated array: |
|||
<syntaxhighlight lang="s-lang">a = {1, 2, 3}; |
|||
b = {4, 5, 6}; |
|||
c = list_concat(a, b);</syntaxhighlight> |
|||
or list_join(): |
|||
<syntaxhighlight lang="s-lang">list_join(a, b);</syntaxhighlight> |
|||
which adds the elements of b onto a. |
|||
=={{header|SASL}}== |
|||
In SASL, the concat operator ++ is built-in |
|||
<syntaxhighlight lang="sasl">(1 2 3) ++ (4 5 6)</syntaxhighlight> |
|||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
< |
<syntaxhighlight lang="scala">val arr1 = Array( 1, 2, 3 ) |
||
val arr2 = Array( 4, 5, 6 ) |
val arr2 = Array( 4, 5, 6 ) |
||
val arr3 = Array( 7, 8, 9 ) |
val arr3 = Array( 7, 8, 9 ) |
||
Line 1,817: | Line 4,190: | ||
//or: |
//or: |
||
Array concat ( arr1, arr2, arr3 ) |
Array concat ( arr1, arr2, arr3 ) |
||
// res0: Array[Int] = Array(1, 2, 3, 4, 5, 6, 7, 8, 9)</ |
// res0: Array[Int] = Array(1, 2, 3, 4, 5, 6, 7, 8, 9)</syntaxhighlight> |
||
=={{header|Scheme}}== |
=={{header|Scheme}}== |
||
< |
<syntaxhighlight lang="scheme">; in r5rs, there is append for lists, but we'll need to define vector-append |
||
(define (vector-append . arg) (list->vector (apply append (map vector->list arg)))) |
(define (vector-append . arg) (list->vector (apply append (map vector->list arg)))) |
||
(vector-append #(1 2 3 4) #(5 6 7) #(8 9 10)) |
(vector-append #(1 2 3 4) #(5 6 7) #(8 9 10)) |
||
; #(1 2 3 4 5 6 7 8 9 10)</ |
; #(1 2 3 4 5 6 7 8 9 10)</syntaxhighlight> |
||
''Note : vector-append is also defined in [http://srfi.schemers.org/srfi-43/srfi-43.html SRFI-43].'' |
''Note : vector-append is also defined in [http://srfi.schemers.org/srfi-43/srfi-43.html SRFI-43].'' |
||
=== Concatening two-dimensional arrays === |
|||
{{works with|Gauche Scheme}} |
|||
<syntaxhighlight lang="scheme"> |
|||
(use gauche.array) |
|||
(define (print-matrix m) |
|||
(define row-num #f) |
|||
(array-for-each-index m |
|||
(lambda (row col) |
|||
(when (and row-num (not (= row-num row))) (newline)) |
|||
(format #t "~a " (array-ref m row col)) |
|||
(set! row-num row))) |
|||
(newline)) |
|||
(define a |
|||
#,(<array> (0 3 0 2) |
|||
a b |
|||
c d |
|||
e f)) |
|||
(define b |
|||
#,(<array> (0 3 0 2) |
|||
1 2 |
|||
3 4 |
|||
5 6)) |
|||
(print-matrix (array-concatenate a b)) |
|||
(print-matrix (array-concatenate a b 1)) |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
a b |
|||
c d |
|||
e f |
|||
1 2 |
|||
3 4 |
|||
5 6 |
|||
a b 1 2 |
|||
c d 3 4 |
|||
e f 5 6 |
|||
</pre> |
|||
=={{header|Seed7}}== |
=={{header|Seed7}}== |
||
< |
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i"; |
||
var array integer: a is [] (1, 2, 3, 4); |
var array integer: a is [] (1, 2, 3, 4); |
||
Line 1,844: | Line 4,262: | ||
end for; |
end for; |
||
writeln; |
writeln; |
||
end func;</ |
end func;</syntaxhighlight> |
||
{{out}} |
|||
Output: |
|||
<pre>1 2 3 4 5 6 7 8</pre> |
<pre>1 2 3 4 5 6 7 8</pre> |
||
=={{header|SenseTalk}}== |
|||
<syntaxhighlight lang="sensetalk">put (1, 2, 3) into list1 |
|||
put (4, 5, 6) into list2 |
|||
put list1 &&& list2 into list3 |
|||
put list3</syntaxhighlight> |
|||
=={{header|SETL}}== |
|||
<syntaxhighlight lang="haskell">A := [1, 2, 3]; |
|||
B := [3, 4, 5]; |
|||
print(A + B); -- [1 2 3 3 4 5]</syntaxhighlight> |
|||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
< |
<syntaxhighlight lang="ruby">var arr1 = [1, 2, 3]; |
||
var arr2 = [4, 5, 6]; |
var arr2 = [4, 5, 6]; |
||
var arr3 = (arr1 + arr2); # => [1, 2, 3, 4, 5, 6]</ |
var arr3 = (arr1 + arr2); # => [1, 2, 3, 4, 5, 6]</syntaxhighlight> |
||
=={{header|Simula}}== |
|||
<syntaxhighlight lang="simula">BEGIN ! Concatenate arrays - of REAL, here; |
|||
CLASS REAL_ARRAY(N); INTEGER N; |
|||
BEGIN |
|||
REAL ARRAY DATA(1:N); |
|||
! Return a new REAL_ARRAY containing |
|||
! the values from this REAL_ARRAY |
|||
! followed by the values from other; |
|||
REF(REAL_ARRAY) PROCEDURE CONCAT(other); |
|||
REF(REAL_ARRAY) other; |
|||
BEGIN |
|||
REF(REAL_ARRAY) C; |
|||
INTEGER I; |
|||
C :- NEW REAL_ARRAY(N + other.N); |
|||
FOR I := 1 STEP 1 UNTIL N DO |
|||
C.DATA(I) := DATA(I); |
|||
FOR I := 1 STEP 1 UNTIL other.N DO |
|||
C.DATA(N + I) := other.DATA(I); |
|||
CONCAT :- C; |
|||
END; |
|||
! Fill DATA; |
|||
REF(REAL_ARRAY) PROCEDURE linearFill(start, stride); |
|||
REAL start, stride; |
|||
BEGIN |
|||
linearFillFrom(DATA, 1, N, start, stride); |
|||
linearFill :- this REAL_ARRAY |
|||
END; |
|||
PROCEDURE out(sink); REF(printfile) sink; |
|||
BEGIN |
|||
INTEGER i; |
|||
FOR i := 1 STEP 1 UNTIL N DO |
|||
sink.OUTFIX(DATA(i), 2, 7); |
|||
sink.OUTIMAGE; |
|||
END; |
|||
END REAL_ARRAY; |
|||
! "The problem" is not array as an input parameter: |
|||
! I don't know how to |
|||
! "pass a new ARRAY out of a PROCEDURE"; |
|||
REF(REAL_ARRAY) PROCEDURE concatenate(a, b); |
|||
REAL ARRAY a, b; |
|||
BEGIN |
|||
INTEGER i, a_, N, b_, M; |
|||
REF(REAL_ARRAY) c; |
|||
a_ := LOWERBOUND(a, 1) - 1; |
|||
N := UPPERBOUND(a, 1) - a_; |
|||
b_ := LOWERBOUND(a, 1) - 1; |
|||
M := UPPERBOUND(b, 1) - b_; |
|||
c :- NEW REAL_ARRAY(N + M); |
|||
FOR i := 1 STEP 1 UNTIL N DO |
|||
c.DATA(i) := a(a_+i); |
|||
! for readability, don't |
|||
! reduce one index expression to a variable |
|||
FOR i := 1 STEP 1 UNTIL M DO |
|||
c.DATA(N + i) := b(b_+i); |
|||
concatenate :- c; |
|||
END concatenate REAL ARRAYs; |
|||
! two more convenience PROCEDUREs; |
|||
PROCEDURE linearFillFrom(a, from, inclusive, start, stride); |
|||
REAL ARRAY a; ! passed by reference; |
|||
INTEGER from, inclusive; |
|||
REAL start, stride; |
|||
BEGIN |
|||
INTEGER i; |
|||
FOR i := from STEP 1 UNTIL inclusive DO |
|||
a(i) := start + stride * (i - from) |
|||
END; |
|||
PROCEDURE linearFill(a, start, stride); |
|||
REAL ARRAY a; |
|||
REAL start, stride; |
|||
linearFillFrom(a, LOWERBOUND(a, 1), UPPERBOUND(a, 1), |
|||
start, stride); |
|||
REF(REAL_ARRAY) X; |
|||
REAL ARRAY u(1:3), v(1:4); |
|||
linearFill(u, 3, 7); |
|||
linearFill(v, 0, 5); |
|||
concatenate(u, v).out(SYSOUT); |
|||
X :- NEW REAL_ARRAY(3).linearFill(1, 2); |
|||
X.out(SYSOUT); |
|||
X.CONCAT(NEW REAL_ARRAY(4) |
|||
.linearFill(-1, -3)).out(SYSOUT); |
|||
END.</syntaxhighlight> |
|||
{{out}} |
|||
<pre> 3.00 10.00 17.00 0.00 5.00 10.00 15.00 |
|||
1.00 3.00 5.00 |
|||
1.00 3.00 5.00 -1.00 -4.00 -7.00 -10.00</pre> |
|||
=={{header|Slate}}== |
=={{header|Slate}}== |
||
The binary operation of concatenation is made with the <tt>;</tt> (semi-colon) from the type Sequence. It is also available for appending Sequences to WriteStreams. |
The binary operation of concatenation is made with the <tt>;</tt> (semi-colon) from the type Sequence. It is also available for appending Sequences to WriteStreams. |
||
< |
<syntaxhighlight lang="slate"> |
||
{1. 2. 3. 4. 5} ; {6. 7. 8. 9. 10} |
{1. 2. 3. 4. 5} ; {6. 7. 8. 9. 10} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Slope}}== |
|||
<syntaxhighlight lang="slope">(list-join [1 2 3] [4 5 6])</syntaxhighlight> |
|||
=={{header|SmallBASIC}}== |
|||
<syntaxhighlight lang="SmallBASIC"> |
|||
A = [1,2,3] |
|||
B = [4,5,6] |
|||
for i in B do A << i |
|||
print A |
|||
</syntaxhighlight> |
|||
=={{header|Smalltalk}}== |
=={{header|Smalltalk}}== |
||
Concatenation (appending) is made with the method <tt>,</tt> (comma), present in classes SequenceableCollection, ArrayedCollection and their subclasses (e.g. Array, String, OrderedCollection ...) |
Concatenation (appending) is made with the method <tt>,</tt> (comma), present in classes SequenceableCollection, ArrayedCollection and their subclasses (e.g. Array, String, OrderedCollection ...) |
||
< |
<syntaxhighlight lang="smalltalk">|a b c| |
||
a := #(1 2 3 4 5). |
a := #(1 2 3 4 5). |
||
b := #(6 7 8 9 10). |
b := #(6 7 8 9 10). |
||
c := a,b. |
c := a,b. |
||
c displayNl.</ |
c displayNl.</syntaxhighlight> |
||
=={{header|SNOBOL4}}== |
=={{header|SNOBOL4}}== |
||
Line 1,876: | Line 4,420: | ||
{{works with|CSnobol}} |
{{works with|CSnobol}} |
||
< |
<syntaxhighlight lang="snobol4">* # Concatenate 2 arrays (vectors) |
||
define('cat(a1,a2)i,j') :(cat_end) |
define('cat(a1,a2)i,j') :(cat_end) |
||
cat cat = array(prototype(a1) + prototype(a2)) |
cat cat = array(prototype(a1) + prototype(a2)) |
||
Line 1,895: | Line 4,439: | ||
output = str2 |
output = str2 |
||
output = str3 |
output = str3 |
||
end</ |
end</syntaxhighlight> |
||
{{out}} |
|||
Output: |
|||
<pre>1 2 3 4 5 |
<pre>1 2 3 4 5 |
||
6 7 8 9 10 |
6 7 8 9 10 |
||
1 2 3 4 5 6 7 8 9 10</pre> |
1 2 3 4 5 6 7 8 9 10</pre> |
||
=={{header|SparForte}}== |
|||
As a structured script. |
|||
<syntaxhighlight lang="ada">#!/usr/local/bin/spar |
|||
pragma annotate( summary, "arraycat" ) |
|||
@( description, "Show how to concatenate two arrays in your language." ) |
|||
@( category, "tutorials" ) |
|||
@( author, "Ken O. Burtch" ) |
|||
@( see_also, "http://rosettacode.org/wiki/Array_concatenation" ); |
|||
pragma license( unrestricted ); |
|||
pragma software_model( nonstandard ); |
|||
pragma restriction( no_external_commands ); |
|||
procedure arraycat is |
|||
type arrayOf3 is array(1..3) of integer; |
|||
a1 : constant arrayOf3 := (1, 2, 3); |
|||
a2 : constant arrayOf3 := (4, 5, 6); |
|||
type arrayOf6 is array(1..6) of integer; |
|||
a3 : arrayOf6; |
|||
p : natural := arrays.first(a3); |
|||
begin |
|||
-- In SparForte, & only works on strings and there's no indefinite ranges |
|||
-- or array slicing. We have to do this the hard way, one element at a |
|||
-- time. |
|||
for i in arrays.first(a1)..arrays.last(a1) loop |
|||
a3(p) := a1(i); |
|||
p := @+1; |
|||
end loop; |
|||
for i in arrays.first(a2)..arrays.last(a2) loop |
|||
a3(p) := a2(i); |
|||
p := @+1; |
|||
end loop; |
|||
-- show the array |
|||
for i in arrays.first(a3)..arrays.last(a3) loop |
|||
put( a3(i) ); |
|||
end loop; |
|||
new_line; |
|||
end arraycat;</syntaxhighlight> |
|||
=={{header|Standard ML}}== |
=={{header|Standard ML}}== |
||
<syntaxhighlight lang="standard ml"> |
|||
<lang Standard ML> |
|||
val l1 = [1,2,3,4];; |
val l1 = [1,2,3,4];; |
||
val l2 = [5,6,7,8];; |
val l2 = [5,6,7,8];; |
||
val l3 = l1 @ l2 (* [1,2,3,4,5,6,7,8] *) |
val l3 = l1 @ l2 (* [1,2,3,4,5,6,7,8] *) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Stata}}== |
|||
===Macro language=== |
|||
<syntaxhighlight lang="stata">. matrix a=2,9,4\7,5,3\6,1,8 |
|||
. matrix list a |
|||
a[3,3] |
|||
c1 c2 c3 |
|||
r1 2 9 4 |
|||
r2 7 5 3 |
|||
r3 6 1 8 |
|||
. matrix b=I(3) |
|||
. matrix list b |
|||
symmetric b[3,3] |
|||
c1 c2 c3 |
|||
r1 1 |
|||
r2 0 1 |
|||
r3 0 0 1 |
|||
. matrix c=a,b |
|||
. matrix list c |
|||
c[3,6] |
|||
c1 c2 c3 c1 c2 c3 |
|||
r1 2 9 4 1 0 0 |
|||
r2 7 5 3 0 1 0 |
|||
r3 6 1 8 0 0 1 |
|||
. matrix c=a\b |
|||
. matrix list c |
|||
c[6,3] |
|||
c1 c2 c3 |
|||
r1 2 9 4 |
|||
r2 7 5 3 |
|||
r3 6 1 8 |
|||
r1 1 0 0 |
|||
r2 0 1 0 |
|||
r3 0 0 1</syntaxhighlight> |
|||
=== Mata === |
|||
<syntaxhighlight lang="stata">. mata |
|||
: a=2,9,4\7,5,3\6,1,8 |
|||
: b=I(3) |
|||
: a,b |
|||
1 2 3 4 5 6 |
|||
+-------------------------+ |
|||
1 | 2 9 4 1 0 0 | |
|||
2 | 7 5 3 0 1 0 | |
|||
3 | 6 1 8 0 0 1 | |
|||
+-------------------------+ |
|||
: a\b |
|||
1 2 3 |
|||
+-------------+ |
|||
1 | 2 9 4 | |
|||
2 | 7 5 3 | |
|||
3 | 6 1 8 | |
|||
4 | 1 0 0 | |
|||
5 | 0 1 0 | |
|||
6 | 0 0 1 | |
|||
+-------------+ |
|||
: end</syntaxhighlight> |
|||
=={{header|Swift}}== |
=={{header|Swift}}== |
||
< |
<syntaxhighlight lang="swift">let array1 = [1,2,3] |
||
let array2 = [4,5,6] |
let array2 = [4,5,6] |
||
let array3 = array1 + array2</ |
let array3 = array1 + array2</syntaxhighlight> |
||
=={{header|Symstatic}}== |
|||
<syntaxhighlight lang="symstatic">let concat(a, b) := a + b |
|||
assert(concat([1, 2, 3], [4, 5, 6]) = [1, 2, 3, 4, 5, 6]) |
|||
</syntaxhighlight> |
|||
=={{header|Tailspin}}== |
|||
<syntaxhighlight lang="tailspin"> |
|||
def a: [1, 2, 3]; |
|||
def b: [4, 5, 6]; |
|||
[$a..., $b...] -> !OUT::write |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
[1, 2, 3, 4, 5, 6] |
|||
</pre> |
|||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
< |
<syntaxhighlight lang="tcl">set a {1 2 3} |
||
set b {4 5 6} |
set b {4 5 6} |
||
set ab [concat $a $b]; # 1 2 3 4 5 6</ |
set ab [concat $a $b]; # 1 2 3 4 5 6</syntaxhighlight> |
||
Note that in the Tcl language, “arrays” are hash maps of strings to variables, so the notion of concatenation doesn't really apply. What other languages (usually) call arrays are “lists” in Tcl. |
Note that in the Tcl language, “arrays” are hash maps of strings to variables, so the notion of concatenation doesn't really apply. What other languages (usually) call arrays are “lists” in Tcl. |
||
Line 1,950: | Line 4,616: | ||
=={{header|Trith}}== |
=={{header|Trith}}== |
||
< |
<syntaxhighlight lang="trith">[1 2 3] [4 5 6] concat</syntaxhighlight> |
||
=={{header|Uiua}}== |
|||
{{works with|Uiua|0.11.1}} |
|||
<syntaxhighlight lang="uiua"> |
|||
⊂[1 2 3] [4 5 6] |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
[1 2 3 4 5 6] |
|||
</pre> |
|||
=={{header|UNIX Shell}}== |
=={{header|UNIX Shell}}== |
||
Line 1,958: | Line 4,634: | ||
{{works with|bash}} |
{{works with|bash}} |
||
< |
<syntaxhighlight lang="bash">array1=( 1 2 3 4 5 ) |
||
array2=( 6 7 8 9 10 ) |
array2=( 6 7 8 9 10 ) |
||
botharrays=( ${array1[@]} ${array2[@]} )</ |
botharrays=( ${array1[@]} ${array2[@]} )</syntaxhighlight> |
||
Whitespace-delimited strings work in much the same way: |
Whitespace-delimited strings work in much the same way: |
||
Line 1,966: | Line 4,642: | ||
{{works with|bash}} |
{{works with|bash}} |
||
< |
<syntaxhighlight lang="bash">array1='1 2 3 4 5' |
||
array2='6 7 8 9 10' |
array2='6 7 8 9 10' |
||
Line 1,973: | Line 4,649: | ||
# Concatenated to a string ... |
# Concatenated to a string ... |
||
botharrays_s="$array1 $array2"</ |
botharrays_s="$array1 $array2"</syntaxhighlight> |
||
=={{header|Ursa}}== |
|||
<syntaxhighlight lang="ursa"># create two streams (the ursa equivalent of arrays) |
|||
# a contains the numbers 1-10, b contains 11-20 |
|||
decl int<> a b |
|||
decl int i |
|||
for (set i 1) (< i 11) (inc i) |
|||
append i a |
|||
end for |
|||
for (set i 11) (< i 21) (inc i) |
|||
append i b |
|||
end for |
|||
# append the values in b to a |
|||
append b a |
|||
# output a to the console |
|||
out a endl console</syntaxhighlight> |
|||
=={{header|Vala}}== |
=={{header|Vala}}== |
||
< |
<syntaxhighlight lang="vala">int[] array_concat(int[]a,int[]b){ |
||
int[] c = new int[a.length + b.length]; |
int[] c = new int[a.length + b.length]; |
||
Memory.copy(c, a, a.length * sizeof(int)); |
Memory.copy(c, a, a.length * sizeof(int)); |
||
Line 1,989: | Line 4,683: | ||
stdout.printf("%d\n",i); |
stdout.printf("%d\n",i); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|VBA}}== |
|||
<syntaxhighlight lang="vb"> |
|||
Option Explicit |
|||
Sub MainConcat_Array() |
|||
Dim Aray_1() As Variant, Aray_2() As Variant |
|||
Dim Result() As Variant |
|||
Aray_1 = Array(1, 2, 3, 4, 5, #11/24/2017#, "azerty") |
|||
Aray_2 = Array("A", "B", "C", 18, "End") |
|||
Result = Concat_Array(Aray_1, Aray_2) |
|||
Debug.Print "With Array 1 : " & Join(Aray_1, ", ") |
|||
Debug.Print "And Array 2 : " & Join(Aray_2, ", ") |
|||
Debug.Print "The result is Array 3 : " & Join(Result, ", ") |
|||
End Sub |
|||
Function Concat_Array(A1() As Variant, A2() As Variant) As Variant() |
|||
Dim TmpA1() As Variant, N As Long, i As Long |
|||
N = UBound(A1) + 1 |
|||
TmpA1 = A1 |
|||
ReDim Preserve TmpA1(N + UBound(A2)) |
|||
For i = N To UBound(TmpA1) |
|||
TmpA1(i) = A2(i - N) |
|||
Next |
|||
Concat_Array = TmpA1 |
|||
End Function |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre>With Array 1 : 1, 2, 3, 4, 5, 24/11/2017, azerty |
|||
And Array 2 : A, B, C, 18, End |
|||
The result is Array 3 : 1, 2, 3, 4, 5, 24/11/2017, azerty, A, B, C, 18, End |
|||
</pre> |
|||
=={{header|VBScript}}== |
=={{header|VBScript}}== |
||
< |
<syntaxhighlight lang="vb">Function ArrayConcat(arr1, arr2) |
||
ReDim ret(UBound(arr1) + UBound(arr2) + 1) |
ReDim ret(UBound(arr1) + UBound(arr2) + 1) |
||
For i = 0 To UBound(arr1) |
For i = 0 To UBound(arr1) |
||
Line 2,009: | Line 4,738: | ||
WScript.Echo "arr2 = array(" & Join(arr2,", ") & ")" |
WScript.Echo "arr2 = array(" & Join(arr2,", ") & ")" |
||
arr3 = ArrayConcat(arr1, arr2) |
arr3 = ArrayConcat(arr1, arr2) |
||
WScript.Echo "arr1 + arr2 = array(" & Join(arr3,", ") & ")"</ |
WScript.Echo "arr1 + arr2 = array(" & Join(arr3,", ") & ")"</syntaxhighlight> |
||
Output: |
|||
{{out}} |
|||
<pre> |
<pre> |
||
arr1 = array(10, 20, 30) |
arr1 = array(10, 20, 30) |
||
Line 2,020: | Line 4,748: | ||
=={{header|Visual Basic .NET}}== |
=={{header|Visual Basic .NET}}== |
||
< |
<syntaxhighlight lang="vbnet"> |
||
Dim iArray1() As Integer = {1, 2, 3} |
Dim iArray1() As Integer = {1, 2, 3} |
||
Dim iArray2() As Integer = {4, 5, 6} |
Dim iArray2() As Integer = {4, 5, 6} |
||
Line 2,026: | Line 4,754: | ||
iArray3 = iArray1.Concat(iArray2).ToArray |
iArray3 = iArray1.Concat(iArray2).ToArray |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|V (Vlang)}}== |
|||
V (Vlang) uses a '''<<''' operator for array concatenation. Destination array needs to be mutable. |
|||
<syntaxhighlight lang="go">// V, array concatenation |
|||
// Tectonics: v run array-concatenation.v |
|||
module main |
|||
// starts here |
|||
pub fn main() { |
|||
mut arr1 := [1,2,3,4] |
|||
arr2 := [5,6,7,8] |
|||
arr1 << arr2 |
|||
println(arr1) |
|||
}</syntaxhighlight> |
|||
{{out}}<pre>$ v run array-concatenation.v |
|||
[1, 2, 3, 4, 5, 6, 7, 8]</pre> |
|||
=={{header|Wart}}== |
=={{header|Wart}}== |
||
Line 2,032: | Line 4,779: | ||
Wart doesn't have arrays yet, just lists. |
Wart doesn't have arrays yet, just lists. |
||
< |
<syntaxhighlight lang="wart">a <- '(1 2 3) |
||
b <- '(4 5 6) |
b <- '(4 5 6) |
||
a+b |
a+b |
||
# => (1 2 3 4 5 6)</ |
# => (1 2 3 4 5 6)</syntaxhighlight> |
||
=={{header|Wren}}== |
|||
<syntaxhighlight lang="wren">var arr1 = [1,2,3] |
|||
var arr2 = [4,5,6] |
|||
System.print(arr1 + arr2)</syntaxhighlight> |
|||
{{Out}} |
|||
<pre>[1, 2, 3, 4, 5, 6]</pre> |
|||
=={{header|XPL0}}== |
|||
{{trans|C}} |
|||
A way to concatenate two XPL0 arrays when you know their size (and usually it is so). |
|||
Works on Raspberry Pi. MAlloc works differently in other versions. |
|||
<syntaxhighlight lang "XPL0">func Array_concat(A, AN, B, BN, S); |
|||
int A, AN, B, BN, S; |
|||
int P; |
|||
[ |
|||
P:= MAlloc(S * (AN + BN)); |
|||
CopyMem(P, A, AN*S); |
|||
CopyMem(P + AN*S, B, BN*S); |
|||
return P; |
|||
]; |
|||
\ testing |
|||
int A, B, C, I, SizeOf; |
|||
[ |
|||
A:= [ 1, 2, 3, 4, 5 ]; |
|||
B:= [ 6, 7, 8, 9, 0 ]; |
|||
SizeOf:= @B - @A; |
|||
C:= Array_concat(A, 5, B, 5, SizeOf); |
|||
for I:= 0 to 10-1 do |
|||
[IntOut(0, C(I)); ChOut(0, ^ )]; |
|||
Release(C); |
|||
]</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
1 2 3 4 5 6 7 8 9 0 </pre> |
|||
=={{header|Yabasic}}== |
|||
<syntaxhighlight lang="yabasic">sub arrayConcatenation(a(), b()) |
|||
local ta, tb, nt, i |
|||
ta = arraysize(a(), 1) |
|||
tb = arraysize(b(), 1) |
|||
nt = ta + tb |
|||
redim a(nt) |
|||
for i = ta + 1 to nt |
|||
a(i) = b(i - ta) |
|||
next i |
|||
return nt |
|||
end sub |
|||
//=============================== |
|||
SIZE = 5 |
|||
dim a(SIZE) |
|||
dim b(SIZE) |
|||
for i = 1 to SIZE |
|||
a(i) = i |
|||
b(i) = i + SIZE |
|||
next i |
|||
nt = arrayConcatenation(a(), b()) |
|||
for i = 1 to nt |
|||
print a(i); |
|||
if i < nt print ", "; |
|||
next i |
|||
print</syntaxhighlight> |
|||
=={{header|Yacas}}== |
|||
<syntaxhighlight lang="yacas">Concat({1,2,3}, {4,5,6}) |
|||
Out> {1, 2, 3, 4, 5, 6}</syntaxhighlight> |
|||
=={{header|Yorick}}== |
=={{header|Yorick}}== |
||
< |
<syntaxhighlight lang="yorick">a = [1,2,3]; |
||
b = [4,5,6]; |
b = [4,5,6]; |
||
ab = grow(a, b);</ |
ab = grow(a, b);</syntaxhighlight> |
||
=={{header|Z80 Assembly}}== |
|||
The routine <code>Monitor_Memdump</code> displays a hexdump to the Amstrad CPC's screen. |
|||
Credit to Keith of [https://www.chibiakumas.com ChibiAkumas] for creating it. |
|||
<syntaxhighlight lang="z80"> org $8000 |
|||
ld hl,TestArray1 ; pointer to first array |
|||
ld de,ArrayRam ; pointer to ram area |
|||
ld bc,6 ; size of first array |
|||
ldir |
|||
; DE is already adjusted past the last entry |
|||
; of the first array |
|||
ld hl,TestArray2 ; pointer to second array |
|||
ld bc,4 ; size of second array |
|||
ldir |
|||
call Monitor_MemDump |
|||
db 32 ; hexdump 32 bytes (only the bytes from the arrays will be shown in the output for clarity) |
|||
dw ArrayRam ; start dumping from ArrayRam |
|||
ret ; return to basic |
|||
ArrayRam: |
|||
ds 24,0 ;24 bytes of ram initialized to zero |
|||
org $9000 |
|||
TestArray2: |
|||
byte $23,$45,$67,$89 |
|||
; just to prove that this doesn't rely on the arrays |
|||
; being "already concatenated" I've stored them |
|||
; in the reverse order. |
|||
TestArray1: |
|||
byte $aa,$bb,$cc,$dd,$ee,$ff</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
801D: |
|||
AA BB CC DD EE FF 23 45 67 89 |
|||
</pre> |
|||
=={{header|Zig}}== |
|||
There are no hidden memory allocations in Zig. |
|||
<syntaxhighlight lang="zig"> |
|||
const std = @import("std"); |
|||
pub fn main() !void { |
|||
var gpa = std.heap.GeneralPurposeAllocator(.{}){}; |
|||
defer _ = gpa.deinit(); |
|||
const allocator = gpa.allocator(); |
|||
var array1 = [_]u32{ 1, 2, 3, 4, 5 }; |
|||
var array2 = [_]u32{ 6, 7, 8, 9, 10, 11, 12 }; |
|||
const slice3 = try std.mem.concat(allocator, u32, &[_][]const u32{ &array1, &array2 }); |
|||
defer allocator.free(slice3); |
|||
// Same result, alternative syntax |
|||
const slice4 = try std.mem.concat(allocator, u32, &[_][]const u32{ array1[0..], array2[0..] }); |
|||
defer allocator.free(slice4); |
|||
std.debug.print( |
|||
"Array 1: {any}\nArray 2: {any}\nSlice 3: {any}\nSlice 4: {any}\n", |
|||
.{ array1, array2, slice3, slice4 }, |
|||
); |
|||
} |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Array 1: { 1, 2, 3, 4, 5 } |
|||
Array 2: { 6, 7, 8, 9, 10, 11, 12 } |
|||
Slice 3: { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 } |
|||
Slice 4: { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 } |
|||
</pre> |
|||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
Lists, no built in support for vectors/arrays/matrices |
Lists (both mutable and read only), no built in support for numeric vectors/arrays/matrices |
||
< |
<syntaxhighlight lang="zkl">T(1,2).extend(T(4,5,6)) //-->L(1,2,4,5,6) |
||
T(1,2).extend(4,5,6) //-->L(1,2,4,5,6)</syntaxhighlight> |
|||
=={{header|zonnon}}== |
|||
<syntaxhighlight lang="text"> |
|||
module Main; |
|||
import |
|||
System.Collections.ArrayList as Array, |
|||
System.Console as Console; |
|||
type |
|||
Vector = array {math} * of integer; |
|||
procedure Concat(x,y: Vector): Vector; |
|||
var |
|||
i,k: integer; |
|||
res: Vector; |
|||
begin |
|||
res := new Vector(len(x) + len(y)); |
|||
k := 0; |
|||
for i := 0 to len(x) - 1 do |
|||
res[k] := x[i];inc(k) |
|||
end; |
|||
for i := 0 to len(y) - 1 do |
|||
res[k] := y[i];inc(k) |
|||
end; |
|||
return res |
|||
end Concat; |
|||
procedure Concat2(x,y: Array): Array; |
|||
var |
|||
i: integer; |
|||
res: Array; |
|||
begin |
|||
res := new Array(x.Count + y.Count); |
|||
for i := 0 to x.Count - 1 do |
|||
res.Add(x[i]); |
|||
end; |
|||
for i := 0 to y.Count - 1 do |
|||
res.Add(y[i]); |
|||
end; |
|||
return res |
|||
end Concat2; |
|||
procedure WriteVec(x: Vector); |
|||
var |
|||
i: integer; |
|||
begin |
|||
for i := 0 to len(x) - 1 do; |
|||
write(x[i]:3) |
|||
end; |
|||
writeln; |
|||
end WriteVec; |
|||
procedure WriteAry(x: Array); |
|||
var |
|||
i: integer; |
|||
begin |
|||
for i := 0 to x.Count - 1 do; |
|||
Console.Write("{0,3}",x[i]) |
|||
end; |
|||
writeln; |
|||
end WriteAry; |
|||
var |
|||
a,b: Vector; |
|||
x,y: Array; |
|||
begin |
|||
a := [1,2,3,4]; |
|||
b := [6,7,8,9]; |
|||
WriteVec(Concat(a,b)); |
|||
x := new Array(4); |
|||
y := new Array(4); |
|||
x.Add(2);x.Add(4);x.Add(6);x.Add(8); |
|||
y.Add(3);y.Add(5);y.Add(9);y.Add(11); |
|||
WriteAry(Concat2(x,y)); |
|||
end Main. |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
1 2 3 4 6 7 8 9 |
|||
2 4 6 8 3 5 9 11 |
|||
</pre> |
|||
=={{header|Zsh}}== |
=={{header|Zsh}}== |
||
Concatenating arrays. |
Concatenating arrays. |
||
< |
<syntaxhighlight lang="zsh">a=(1 2 3) |
||
b=(a b c) |
b=(a b c) |
||
c=($a $b)</ |
c=($a $b)</syntaxhighlight> |
||
Pushing a single element into an array. |
Pushing a single element into an array. |
||
< |
<syntaxhighlight lang="zsh">a+=4</syntaxhighlight> |
||
Pushing another array into an array. |
Pushing another array into an array. |
||
< |
<syntaxhighlight lang="zsh">a+=($b)</syntaxhighlight> |
||
=={{header|ZX Spectrum Basic}}== |
|||
{{trans|Liberty BASIC}} |
|||
<syntaxhighlight lang="zxbasic">10 LET x=10 |
|||
20 LET y=20 |
|||
30 DIM a(x) |
|||
40 DIM b(y) |
|||
50 DIM c(x+y) |
|||
60 FOR i=1 TO x |
|||
70 LET c(i)=a(i) |
|||
80 NEXT i |
|||
90 FOR i=1 TO y |
|||
100 LET c(x+i)=b(i) |
|||
110 NEXT i |
|||
120 FOR i=1 TO x+y |
|||
130 PRINT c(i);", "; |
|||
140 NEXT i |
|||
</syntaxhighlight> |
Latest revision as of 11:34, 19 August 2024
You are encouraged to solve this task according to the task description, using any language you may know.
- Task
Show how to concatenate two arrays in your language.
If this is as simple as array1 + array2
, so be it.
11l
V arr1 = [1, 2, 3]
V arr2 = [4, 5, 6]
print(arr1 [+] arr2)
- Output:
[1, 2, 3, 4, 5, 6]
68000 Assembly
In order for this to work, you'll either need to use malloc()
or know a memory location of "free space" at compile time. This example shall use the latter.
ArrayRam equ $00FF2000 ;this label points to 4k of free space.
;concatenate Array1 + Array2
LEA ArrayRam,A0
LEA Array1,A1
MOVE.W #5-1,D1 ;LEN(Array1), measured in words.
JSR memcpy_w
;after this, A0 will point to the destination of the second array.
LEA Array2,A1 ;even though the source arrays are stored back-to-back in memory, we'll assume they're not just for demonstration purposes.
MOVE.W #5-1,D1 ;LEN(Array2), measured in words
JSR memcpy_w
JMP * ;halt the CPU
memcpy_w:
MOVE.W (A1)+,(A0)+
DBRA D1,memcpy_w
rts
Array1:
DC.W 1,2,3,4,5
Array2:
DC.W 6,7,8,9,10
8th
[1,2,3] [4,5,6] a:+ .
- Output:
[1,2,3,4,5,6]
AArch64 Assembly
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program concAreaString.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
.equ NBMAXITEMS, 20 //
/*******************************************/
/* Initialized data */
/*******************************************/
.data
szMessLenArea: .asciz "The length of area 3 is : @ \n"
szCarriageReturn: .asciz "\n"
/* areas strings */
szString1: .asciz "Apples"
szString2: .asciz "Oranges"
szString3: .asciz "Pommes"
szString4: .asciz "Raisins"
szString5: .asciz "Abricots"
/* pointer items area 1*/
tablesPoi1:
pt1_1: .quad szString1
pt1_2: .quad szString2
ptVoid_1: .quad 0
/* pointer items area 2*/
tablesPoi2:
pt2_1: .quad szString3
pt2_2: .quad szString4
pt2_3: .quad szString5
ptVoid_2: .quad 0
/*******************************************/
/* UnInitialized data */
/*******************************************/
.bss
tablesPoi3: .skip 8 * NBMAXITEMS
sZoneConv: .skip 30
/*******************************************/
/* code section */
/*******************************************/
.text
.global main
main: // entry of program
// copy area 1 -> area 3
ldr x1,qAdrtablesPoi1 // begin pointer area 1
ldr x3,qAdrtablesPoi3 // begin pointer area 3
mov x0,0 // counter
1:
ldr x2,[x1,x0,lsl 3] // read string pointer address item x0 (8 bytes by pointer)
cbz x2,2f // is null ?
str x2,[x3,x0,lsl 3] // no store pointer in area 3
add x0,x0,1 // increment counter
b 1b // and loop
2: // copy area 2 -> area 3
ldr x1,qAdrtablesPoi2 // begin pointer area 2
ldr x3,qAdrtablesPoi3 // begin pointer area 3
mov x4,#0 // counter area 2
3: // x0 contains the first void item in area 3
ldr x2,[x1,x4,lsl #3] // read string pointer address item x0 (8 bytes by pointer)
cbz x2,4f // is null ?
str x2,[x3,x0,lsl #3] // no store pointer in area 3
add x0,x0,1 // increment counter
add x4,x4,1 // increment counter
b 3b // and loop
4:
// count items number in area 3
ldr x1,qAdrtablesPoi3 // begin pointer table
mov x0,#0 // counter
5: // begin loop
ldr x2,[x1,x0,lsl #3] // read string pointer address item x0 (8 bytes by pointer)
cmp x2,#0 // is null ?
cinc x0,x0,ne // no increment counter
bne 5b // and loop
ldr x1,qAdrsZoneConv // conversion decimal
bl conversion10S
ldr x0,qAdrszMessLenArea
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at @ character
bl affichageMess
100: // standard end of the program
mov x0,0 // return code
mov x8,EXIT // request to exit program
svc 0 // perform the system call
qAdrtablesPoi1: .quad tablesPoi1
qAdrtablesPoi2: .quad tablesPoi2
qAdrtablesPoi3: .quad tablesPoi3
qAdrszMessLenArea: .quad szMessLenArea
qAdrsZoneConv: .quad sZoneConv
qAdrszCarriageReturn: .quad szCarriageReturn
/****************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
ABAP
The concept of arrays does not exist in ABAP, instead internal tables are used. This works in ABAP version 7.40 and above.
report z_array_concatenation.
data(itab1) = value int4_table( ( 1 ) ( 2 ) ( 3 ) ).
data(itab2) = value int4_table( ( 4 ) ( 5 ) ( 6 ) ).
append lines of itab2 to itab1.
loop at itab1 assigning field-symbol(<line>).
write <line>.
endloop.
- Output:
1 2 3 4 5 6
ACL2
This is for lists, not arrays; ACL2's array support is limited.
(append xs ys)
Action!
BYTE FUNC Concat(INT ARRAY src1,src2,dst BYTE size1,size2)
BYTE i
FOR i=0 TO size1-1
DO
dst(i)=src1(i)
OD
FOR i=0 TO size2-1
DO
dst(size1+i)=src2(i)
OD
RETURN (size1+size2)
PROC PrintArray(INT ARRAY a BYTE size)
BYTE i
Put('[)
FOR i=0 TO size-1
DO
PrintI(a(i))
IF i<size-1 THEN
Put(' )
FI
OD
Put('])
RETURN
PROC Test(INT ARRAY src1,src2 BYTE size1,size2)
INT ARRAY res(20)
BYTE size
size=Concat(src1,src2,res,size1,size2)
PrintArray(src1,size1)
Put('+)
PrintArray(src2,size2)
Put('=)
PrintArray(res,size)
PutE() PutE()
RETURN
PROC Main()
INT ARRAY
a1=[1 2 3 4],
a2=[5 6 7 8 9 10],
;a workaround for a3=[-1 -2 -3 -4 -5]
a3=[65535 65534 65533 65532 65531]
Test(a1,a2,4,6)
Test(a2,a1,6,4)
Test(a3,a2,5,4)
RETURN
- Output:
Screenshot from Atari 8-bit computer
[1 2 3 4]+[5 6 7 8 9 10]=[1 2 3 4 5 6 7 8 9 10] [5 6 7 8 9 10]+[1 2 3 4]=[5 6 7 8 9 10 1 2 3 4] [-1 -2 -3 -4 -5]+[5 6 7 8]=[-1 -2 -3 -4 -5 5 6 7 8]
ActionScript
var array1:Array = new Array(1, 2, 3);
var array2:Array = new Array(4, 5, 6);
var array3:Array = array1.concat(array2); //[1, 2, 3, 4, 5, 6]
Ada
In Ada arrays are concatenated using the operation &. It works with any one dimensioned array:
type T is array (Positive range <>) of Integer;
X : T := (1, 2, 3);
Y : T := X & (4, 5, 6); -- Concatenate X and (4, 5, 6)
Aime
ac(list a, b)
{
list o;
o.copy(a);
b.ucall(l_append, 1, o);
o;
}
main(void)
{
list a, b, c;
a = list(1, 2, 3, 4);
b = list(5, 6, 7, 8);
c = ac(a, b);
c.ucall(o_, 1, " ");
0;
}
- Output:
1 2 3 4 5 6 7 8
ALGOL 68
Includes operators for appending and prefixing an array to an existing flexible array:
MODE ARGTYPE = INT;
MODE ARGLIST = FLEX[0]ARGTYPE;
OP + = (ARGLIST a, b)ARGLIST: (
[LWB a:UPB a - LWB a + 1 + UPB b - LWB b + 1 ]ARGTYPE out;
(
out[LWB a:UPB a]:=a,
out[UPB a+1:]:=b
);
out
);
# Append #
OP +:= = (REF ARGLIST lhs, ARGLIST rhs)ARGLIST: lhs := lhs + rhs;
OP PLUSAB = (REF ARGLIST lhs, ARGLIST rhs)ARGLIST: lhs := lhs + rhs;
# Prefix #
OP +=: = (ARGLIST lhs, REF ARGLIST rhs)ARGLIST: rhs := lhs + rhs;
OP PLUSTO = (ARGLIST lhs, REF ARGLIST rhs)ARGLIST: rhs := lhs + rhs;
ARGLIST a := (1,2),
b := (3,4,5);
print(("a + b",a + b, new line));
VOID(a +:= b);
print(("a +:= b", a, new line));
VOID(a +=: b);
print(("a +=: b", b, new line))
a + b +1 +2 +3 +4 +5 a +:= b +1 +2 +3 +4 +5 a +=: b +1 +2 +3 +4 +5 +3 +4 +5
ALGOL W
Algol W does not allow procedures to return arrays and has no mechanism for procedures to find the bounds of their parameters, so the caller must supply an array to concatenate into and the bounds of the arrays.
begin
integer array a ( 1 :: 5 );
integer array b ( 2 :: 4 );
integer array c ( 1 :: 8 );
% concatenates the arrays a and b into c %
% the lower and upper bounds of each array must be specified in %
% the corresponding *Lb and *Ub parameters %
procedure arrayConcatenate ( integer array a ( * )
; integer value aLb, aUb
; integer array b ( * )
; integer value bLb, bUb
; integer array c ( * )
; integer value cLb, cUb
) ;
begin
integer cPos;
assert( ( cUb - cLb ) + 1 >= ( ( aUb + bUb ) - ( aLb + bLb ) ) - 2 );
cPos := cLb;
for aPos := aLb until aUb do begin
c( cPos ) := a( aPos );
cPos := cPos + 1
end for_aPos ;
for bPos := bLb until bUb do begin
c( cPos ) := b( bPos );
cPos := cPos + 1
end for_bPos
end arrayConcatenate ;
% test arrayConcatenate %
for aPos := 1 until 5 do a( aPos ) := aPos;
for bPos := 2 until 4 do b( bPos ) := - bPos;
arrayConcatenate( a, 1, 5, b, 2, 4, c, 1, 8 );
for cPos := 1 until 8 do writeon( i_w := 1, s_w := 1, c( cPos ) )
end.
- Output:
1 2 3 4 5 -2 -3 -4
Amazing Hopper
#include <hbasic.h>
Begin
a1 = {}
a2 = {}
Take(100,"Hola",0.056,"Mundo!"), and Push All(a1)
Take("Segundo",0,"array",~True,~False), and Push All(a2)
Concat (a1, a2) and Print ( a2, Newl )
End
- Output:
Segundo,0,array,1,0,100,Hola,0.056,Mundo!
AntLang
a:<1; <2; 3>>
b: <"Hello"; 42>
c: a,b
Apex
List<String> listA = new List<String> { 'apple' };
List<String> listB = new List<String> { 'banana' };
listA.addAll(listB);
System.debug(listA); // Prints (apple, banana)
APL
1 2 3 , 4 5 6
1 2 3 4 5 6
AppleScript
set listA to {1, 2, 3}
set listB to {4, 5, 6}
return listA & listB
- Output:
{1, 2, 3, 4, 5, 6}
Or, if we treat the concatenation of two lists as a special case of the more general problem of concatenating N lists, we can write:
on run
concat([["alpha", "beta", "gamma"], ¬
["delta", "epsilon", "zeta"], ¬
["eta", "theta", "iota"]])
end run
-- concat :: [[a]] -> [a]
on concat(xxs)
set lst to {}
repeat with xs in xxs
set lst to lst & xs
end repeat
return lst
end concat
- Output:
{"alpha", "beta", "gamma", "delta", "epsilon", "zeta", "eta", "theta", "iota"}
ARM Assembly
/* ARM assembly Raspberry PI */
/* program concAreaString.s */
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
.equ NBMAXITEMS, 20 @
/* Initialized data */
.data
szMessLenArea: .ascii "The length of area 3 is : "
sZoneconv: .fill 12,1,' '
szCarriageReturn: .asciz "\n"
/* areas strings */
szString1: .asciz "Apples"
szString2: .asciz "Oranges"
szString3: .asciz "Pommes"
szString4: .asciz "Raisins"
szString5: .asciz "Abricots"
/* pointer items area 1*/
tablesPoi1:
pt1_1: .int szString1
pt1_2: .int szString2
ptVoid_1: .int 0
/* pointer items area 2*/
tablesPoi2:
pt2_1: .int szString3
pt2_2: .int szString4
pt2_3: .int szString5
ptVoid_2: .int 0
/* UnInitialized data */
.bss
tablesPoi3: .skip 4 * NBMAXITEMS
/* code section */
.text
.global main
main: /* entry of program */
push {fp,lr} /* saves 2 registers */
@ copy area 1 -> area 3
ldr r1,iAdrtablesPoi1 @ begin pointer area 1
ldr r3,iAdrtablesPoi3 @ begin pointer area 3
mov r0,#0 @ counter
1:
ldr r2,[r1,r0,lsl #2] @ read string pointer address item r0 (4 bytes by pointer)
cmp r2,#0 @ is null ?
strne r2,[r3,r0,lsl #2] @ no store pointer in area 3
addne r0,#1 @ increment counter
bne 1b @ and loop
@ copy area 2 -> area 3
ldr r1,iAdrtablesPoi2 @ begin pointer area 2
ldr r3,iAdrtablesPoi3 @ begin pointer area 3
mov r4,#0 @ counter area 2
2: @ r0 contains the first void item in area 3
ldr r2,[r1,r4,lsl #2] @ read string pointer address item r0 (4 bytes by pointer)
cmp r2,#0 @ is null ?
strne r2,[r3,r0,lsl #2] @ no store pointer in area 3
addne r0,#1 @ increment counter
addne r4,#1 @ increment counter
bne 2b @ and loop
@ count items number in area 3
ldr r1,iAdrtablesPoi3 @ begin pointer table
mov r0,#0 @ counter
3: @ begin loop
ldr r2,[r1,r0,lsl #2] @ read string pointer address item r0 (4 bytes by pointer)
cmp r2,#0 @ is null ?
addne r0,#1 @ no increment counter
bne 3b @ and loop
ldr r1,iAdrsZoneconv @ conversion decimal
bl conversion10S
ldr r0,iAdrszMessLenArea
bl affichageMess
100: /* standard end of the program */
mov r0, #0 @ return code
pop {fp,lr} @restaur 2 registers
mov r7, #EXIT @ request to exit program
swi 0 @ perform the system call
iAdrtablesPoi1: .int tablesPoi1
iAdrtablesPoi2: .int tablesPoi2
iAdrtablesPoi3: .int tablesPoi3
iAdrszMessLenArea: .int szMessLenArea
iAdrsZoneconv: .int sZoneconv
iAdrszCarriageReturn: .int szCarriageReturn
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {fp,lr} /* save registres */
push {r0,r1,r2,r7} /* save others registers */
mov r2,#0 /* counter length */
1: /* loop length calculation */
ldrb r1,[r0,r2] /* read octet start position + index */
cmp r1,#0 /* if 0 its over */
addne r2,r2,#1 /* else add 1 in the length */
bne 1b /* and loop */
/* so here r2 contains the length of the message */
mov r1,r0 /* address message in r1 */
mov r0,#STDOUT /* code to write to the standard output Linux */
mov r7, #WRITE /* code call system "write" */
swi #0 /* call systeme */
pop {r0,r1,r2,r7} /* restaur others registers */
pop {fp,lr} /* restaur des 2 registres */
bx lr /* return */
/***************************************************/
/* conversion register signed décimal */
/***************************************************/
/* r0 contient le registre */
/* r1 contient l adresse de la zone de conversion */
conversion10S:
push {r0-r5,lr} /* save des registres */
mov r2,r1 /* debut zone stockage */
mov r5,#'+' /* par defaut le signe est + */
cmp r0,#0 /* nombre négatif ? */
movlt r5,#'-' /* oui le signe est - */
mvnlt r0,r0 /* et inversion en valeur positive */
addlt r0,#1
mov r4,#10 /* longueur de la zone */
1: /* debut de boucle de conversion */
bl divisionpar10 /* division */
add r1,#48 /* ajout de 48 au reste pour conversion ascii */
strb r1,[r2,r4] /* stockage du byte en début de zone r5 + la position r4 */
sub r4,r4,#1 /* position précedente */
cmp r0,#0
bne 1b /* boucle si quotient different de zéro */
strb r5,[r2,r4] /* stockage du signe à la position courante */
subs r4,r4,#1 /* position précedente */
blt 100f /* si r4 < 0 fin */
/* sinon il faut completer le debut de la zone avec des blancs */
mov r3,#' ' /* caractere espace */
2:
strb r3,[r2,r4] /* stockage du byte */
subs r4,r4,#1 /* position précedente */
bge 2b /* boucle si r4 plus grand ou egal a zero */
100: /* fin standard de la fonction */
pop {r0-r5,lr} /*restaur desregistres */
bx lr
/***************************************************/
/* division par 10 signé */
/* Thanks to http://thinkingeek.com/arm-assembler-raspberry-pi/*
/* and http://www.hackersdelight.org/ */
/***************************************************/
/* r0 contient le dividende */
/* r0 retourne le quotient */
/* r1 retourne le reste */
divisionpar10:
/* r0 contains the argument to be divided by 10 */
push {r2-r4} /* save registers */
mov r4,r0
ldr r3, .Ls_magic_number_10 /* r1 <- magic_number */
smull r1, r2, r3, r0 /* r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0) */
mov r2, r2, ASR #2 /* r2 <- r2 >> 2 */
mov r1, r0, LSR #31 /* r1 <- r0 >> 31 */
add r0, r2, r1 /* r0 <- r2 + r1 */
add r2,r0,r0, lsl #2 /* r2 <- r0 * 5 */
sub r1,r4,r2, lsl #1 /* r1 <- r4 - (r2 * 2) = r4 - (r0 * 10) */
pop {r2-r4}
bx lr /* leave function */
bx lr /* leave function */
.Ls_magic_number_10: .word 0x66666667
Arturo
arr1: [1 2 3]
arr2: ["four" "five" "six"]
print arr1 ++ arr2
- Output:
1 2 3 four five six
ATS
The following may seem frightening. However, it probably compiles down to two calls to __builtin_memcpy. All the complexity is to make sure those calls are done correctly.
(* The Rosetta Code array concatenation task, in ATS2. *)
(* In a way, the task is misleading: in a language such as ATS, one
can always devise a very-easy-to-use array type, put the code for
that in a library, and overload operators. Thus we can have
"array1 + array2" as array concatenation in ATS, complete with
garbage collection when the result no longer is needed.
It depends on what libraries are in one's repertoire.
Nevertheless, it seems fair to demonstrate how to concatenate two
barebones arrays at the nitpicking lowest level, without anything
but the barest contents of the ATS2 prelude. It will make ATS
programming look difficult; but ATS programming *is* difficult,
when you are using it to overcome the programming safety
deficiencies of a language such as C, without losing the runtime
efficiency of C code.
What we want is the kind of routine that would be used *in the
implementation* of "array1 + array2". So let us begin ... *)
#include "share/atspre_staload.hats" (* Loads some needed template
code. *)
fn {t : t@ype}
(* The demonstration will be for arrays of a non-linear type t. Were
the arrays to contain a *linear* type (vt@ype), then either the old
arrays would have to be destroyed or a copy procedure would be
needed for the elements. *)
arrayconcat1 {m, n : nat}
{pa, pb, pc : addr}
(pfa : !(@[t][m]) @ pa,
pfb : !(@[t][n]) @ pb,
pfc : !(@[t?][m + n]) @ pc >> @[t][m + n] @ pc |
pa : ptr pa,
pb : ptr pb,
pc : ptr pc,
m : size_t m,
n : size_t n) : void =
(* The routine takes as arguments three low-level arrays, passed by
value, as pointers with associated views. The first array is of
length m, with elements of type t, and the array must have been
initialized; the second is a similar array of length n. The third
array is uninitialized (thus the "?" character) and must have
length m+n; its type will change to "initialized". *)
{
prval (pfleft, pfright) = array_v_split {t?} {pc} {m + n} {m} pfc
(* We have had to split the view of array c into a left part pfleft,
of length m, and a right part pfright of length n. Arrays a and b
will be copied into the respective parts of c. *)
val _ = array_copy<t> (!pc, !pa, m)
val _ = array_copy<t> (!(ptr_add<t> (pc, m)), !pb, n)
(* Copying an array *safely* is more complex than what we are doing
here, but above the task has been given to the "array_copy"
template in the prelude. The "!" signs appear because array_copy is
call-by-reference but we are passing it pointers. *)
(* pfleft and pfright now refer to *initialized* arrays: one of length
m, starting at address pc; the other of length n, starting at
address pc+(m*sizeof<t>). *)
prval _ = pfc := array_v_unsplit {t} {pc} {m, n} (pfleft, pfright)
(* Before we can exit, the view of array c has to be replaced. It is
replaced by "unsplitting" the (now initialized) left and right
parts of the array. *)
(* We are done. Everything should now work, and the result will be
safe from buffer overruns or underruns, and against accidental
misuse of uninitialized data. *)
}
(* arrayconcat2 is a pass-by-reference interface to arrayconcat1. *)
fn {t : t@ype}
arrayconcat2 {m, n : nat}
(a : &(@[t][m]),
b : &(@[t][n]),
c : &(@[t?][m + n]) >> @[t][m + n],
m : size_t m,
n : size_t n) : void =
arrayconcat1 (view@ a, view@ b, view@ c |
addr@ a, addr@ b, addr@ c, m, n)
(* Overloads to let you say "arrayconcat" for either routine above. *)
overload arrayconcat with arrayconcat1
overload arrayconcat with arrayconcat2
implement
main0 () =
(* A demonstration program. *)
let
(* Some arrays on the stack. Because they are on the stack, they
will not need explicit freeing. *)
var a = @[int][3] (1, 2, 3)
var b = @[int][4] (5, 6, 7, 8)
var c : @[int?][7]
in
(* Compute c as the concatenation of a and b. *)
arrayconcat<int> (a, b, c, i2sz 3, i2sz 4);
(* The following simply prints the result. *)
let
(* Copy c to a linear linked list, because the prelude provides
means to easily print such a list. *)
val lst = array2list (c, i2sz 7)
in
println! (lst); (* Print the list. *)
free lst (* The list is linear and must be freed. *)
end
end
- Output:
$ patscc -O2 -DATS_MEMALLOC_LIBC arrayconcat.dats && ./a.out 1, 2, 3, 5, 6, 7, 8
Footnotes:
- The ATS prelude does in fact translate calls to array_copy into C calls to memcpy. On a GNU system, the memcpy calls will likely become calls to __builtin_memcpy. The prelude's implementation is a practical one, rather than a strict demonstration of ATS methods.
- The "-DATS_MEMALLOC_LIBC" is needed due to the copying of an array to a linear linked list, which has to be both malloc'd and free'd. The arrays themselves are allocated on the stack, in this example.
AutoHotkey
True Arrays
List1 := [1, 2, 3]
List2 := [4, 5, 6]
cList := Arr_concatenate(List1, List2)
MsgBox % Arr_disp(cList) ; [1, 2, 3, 4, 5, 6]
Arr_concatenate(p*) {
res := Object()
For each, obj in p
For each, value in obj
res.Insert(value)
return res
}
Arr_disp(arr) {
for each, value in arr
res .= ", " value
return "[" SubStr(res, 3) "]"
}
Legacy versions
AutoHotkey_Basic does not have real Arrays, but the user can implement them quite easily. For example:
List1 = 1,2,3
List2 = 4,5,6
List2Array(List1 , "Array1_")
List2Array(List2 , "Array2_")
ConcatArrays("Array1_", "Array2_", "MyArray")
MsgBox, % Array2List("MyArray")
;---------------------------------------------------------------------------
ConcatArrays(A1, A2, A3) { ; concatenates the arrays A1 and A2 to A3
;---------------------------------------------------------------------------
local i := 0
%A3%0 := %A1%0 + %A2%0
Loop, % %A1%0
i++, %A3%%i% := %A1%%A_Index%
Loop, % %A2%0
i++, %A3%%i% := %A2%%A_Index%
}
;---------------------------------------------------------------------------
List2Array(List, Array) { ; creates an array from a comma separated list
;---------------------------------------------------------------------------
global
StringSplit, %Array%, List, `,
}
;---------------------------------------------------------------------------
Array2List(Array) { ; returns a comma separated list from an array
;---------------------------------------------------------------------------
Loop, % %Array%0
List .= (A_Index = 1 ? "" : ",") %Array%%A_Index%
Return, List
}
Message box shows:
1,2,3,4,5,6
AutoIt
_ArrayConcatenate is a standard function in Autoit, there´s no need to write it on your own
_ArrayConcatenate($avArray, $avArray2)
Func _ArrayConcatenate(ByRef $avArrayTarget, Const ByRef $avArraySource, $iStart = 0)
If Not IsArray($avArrayTarget) Then Return SetError(1, 0, 0)
If Not IsArray($avArraySource) Then Return SetError(2, 0, 0)
If UBound($avArrayTarget, 0) <> 1 Then
If UBound($avArraySource, 0) <> 1 Then Return SetError(5, 0, 0)
Return SetError(3, 0, 0)
EndIf
If UBound($avArraySource, 0) <> 1 Then Return SetError(4, 0, 0)
Local $iUBoundTarget = UBound($avArrayTarget) - $iStart, $iUBoundSource = UBound($avArraySource)
ReDim $avArrayTarget[$iUBoundTarget + $iUBoundSource]
For $i = $iStart To $iUBoundSource - 1
$avArrayTarget[$iUBoundTarget + $i] = $avArraySource[$i]
Next
Return $iUBoundTarget + $iUBoundSource
EndFunc ;==>_ArrayConcatenate
Avail
<1, 2, 3> ++ <¢a, ¢b, ¢c>
AWK
#!/usr/bin/awk -f
BEGIN {
split("cul-de-sac",a,"-")
split("1-2-3",b,"-")
concat_array(a,b,c)
for (i in c) {
print i,c[i]
}
}
function concat_array(a,b,c, nc) {
for (i in a) {
c[++nc]=a[i]
}
for (i in b) {
c[++nc]=b[i]
}
}
Babel
[1 2 3] [4 5 6] cat ;
- Output:
[val 0x1 0x2 0x3 0x4 0x5 0x6 ]
bash
x=("1 2" "3 4")
y=(5 6)
sum=( "${x[@]}" "${y[@]}" )
for i in "${sum[@]}" ; do echo "$i" ; done
1 2
3 4
5
6
BASIC
Applesoft BASIC
10 LET X = 4:Y = 5
20 DIM A(X - 1),B(Y - 1),C(X + Y - 1)
30 FOR I = 1 TO X:A(I - 1) = I: NEXT
40 FOR I = 1 TO Y:B(I - 1) = I * 10: NEXT
50 FOR I = 1 TO X:C(I - 1) = A(I - 1): NEXT
60 FOR I = 1 TO Y:C(X + I - 1) = B(I - 1): NEXT
70 FOR I = 1 TO X + Y: PRINT MID$ (" ",1,I > 1)C(I - 1);: NEXT
Chipmunk Basic
The GW-BASIC solution works without any changes.
GW-BASIC
100 U1 = 3: U2 = 4
110 DIM A$(3)
120 DATA "The","quick","brown","fox"
130 FOR I = 0 TO U1 : READ A$(I) : NEXT I
140 DIM B$(4)
150 DATA "jumped","over","the","lazy","dog"
160 FOR I = 0 TO U2 : READ B$(I) : NEXT I
170 'SU2 ConcatArrays
180 X = U1 + 1
190 Y = U2 + 1
200 Z = X + Y
210 DIM C$(Z-1)
220 FOR I = 0 TO X-1
230 C$(I) = A$(I)
240 NEXT I
250 FOR I = 0 TO Y-1
260 C$(U1+I+1) = B$(I)
270 NEXT I
280 '
290 FOR I = 0 TO Z-1
300 PRINT C$(I); " ";
310 NEXT I
320 END
Minimal BASIC
10 LET X = 4
20 LET Y = 5
30 DIM A(3)
40 DIM B(4)
50 DIM C(8)
60 FOR I = 1 TO X
70 LET A(I-1) = I
80 NEXT I
90 FOR I = 1 TO Y
100 LET B(I-1) = I*10
110 NEXT I
120 FOR I = 1 TO X
130 LET C(I-1) = A(I-1)
140 NEXT I
150 FOR I = 1 TO Y
160 LET C(X+I-1) = B(I-1)
170 NEXT I
180 FOR I = 1 TO X+Y
190 PRINT C(I-1);
200 NEXT I
210 END
MSX Basic
The GW-BASIC solution works without any changes.
Quite BASIC
100 LET U1 = 3
105 LET U2 = 4
110 ARRAY A$
120 DATA "The","quick","brown","fox"
130 FOR I = 0 TO U1 : READ A$(I) : NEXT I
140 ARRAY B$
150 DATA "jumped","over","the","lazy","dog"
160 FOR I = 0 TO U2 : READ B$(I) : NEXT I
170 rem Sub ConcatArrays
180 LET X = U1 + 1
190 LET Y = U2 + 1
200 LET Z = X + Y
210 ARRAY C
220 FOR I = 0 TO X-1
230 LET C$(I) = A$(I)
240 NEXT I
250 FOR I = 0 TO Y-1
260 LET C$(U1 + I + 1) = B$(I)
270 NEXT I
280 rem
290 FOR I = 0 TO Z-1
300 PRINT C$(I);" ";
310 NEXT I
320 END
BaCon
DECLARE a[] = { 1, 2, 3, 4, 5 }
DECLARE b[] = { 6, 7, 8, 9, 10 }
DECLARE c ARRAY UBOUND(a) + UBOUND(b)
FOR x = 0 TO 4
c[x] = a[x]
c[x+5] = b[x]
NEXT
BBC BASIC
DIM a(3), b(4)
a() = 1, 2, 3, 4
b() = 5, 6, 7, 8, 9
PROCconcat(a(), b(), c())
FOR i% = 0 TO DIM(c(),1)
PRINT c(i%)
NEXT
END
DEF PROCconcat(a(), b(), RETURN c())
LOCAL s%, na%, nb%
s% = ^a(1) - ^a(0) : REM Size of each array element
na% = DIM(a(),1)+1 : REM Number of elements in a()
nb% = DIM(b(),1)+1 : REM Number of elements in b()
DIM c(na%+nb%-1)
SYS "RtlMoveMemory", ^c(0), ^a(0), s%*na%
SYS "RtlMoveMemory", ^c(na%), ^b(0), s%*nb%
ENDPROC
Commodore BASIC
(Based on ZX Spectrum BASIC version)
10 X=4 : Y=5
20 DIM A(X) : DIM B(Y) : DIM C(X+Y)
30 FOR I=1 TO X
40 : A(I) = I
50 NEXT
60 FOR I=1 TO Y
70 : B(I) = I*10
80 NEXT
90 FOR I=1 TO X
100 : C(I) = A(I)
110 NEXT
120 FOR I=1 TO Y
130 : C(X+I) = B(I)
140 NEXT
150 FOR I=1 TO X+Y
160 : PRINT C(I);
170 NEXT
Run BASIC
The Liberty BASIC solution works without any changes.
BASIC256
arraybase 1
global c
dimen = 5
dim a(dimen)
dim b(dimen)
# Array initialization
for i = 1 to dimen
a[i] = i
b[i] = i + dimen
next i
nt = ConcatArrays(a, b)
for i = 1 to nt
print c[i];
if i < nt then print ", ";
next i
end
function ConcatArrays(a, b)
ta = a[?]
tb = b[?]
nt = ta + tb
redim c(nt)
for i = 1 to ta
c[i] = a[i]
next i
for i = 1 to tb
c[i + ta] = b[i]
next i
return nt
end function
- Output:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Binary Lambda Calculus
BLC uses lists instead of arrays. List concatenation is (see also https://github.com/tromp/AIT/blob/master/lists/cat.lam)
00011001000110100000000000010110111100101111001111110111110110
BQN
1‿2‿3 ∾ 4‿5‿6
Bracmat
Bracmat concatenates lists composed with the comma, space, addition and multiplication operators. Furthermore, lists composed with the addition and multiplication operators are canonically sorted and like terms or factors are combined algebraically. Lists composed with the space operator automatically delete any elements with zero-length atoms and no prefixes. All these lists except the comma-separated list support a notion of 'array index', but as the underlying datastructure is a linked list and not an array, accessing, say, the millionth element can be slow. Examples of concatenation (entered on the Bracmat command line):
{?} (a,b,c,d,e),(n,m) {!} a,b,c,d,e,n,m {?} (a,m,y),(b,n,y,z) {!} a,m,y,b,n,y,z {?} (a m y) (b n y z) {!} a m y b n y z {?} (a+m+y)+(b+n+y+z) {!} a+b+m+n+2*y+z {?} (a*m*y)*(b*n*y*z) {!} a*b*m*n*y^2*z
Concatenate three lists and split the concatenated list using a position operator:
{?} (a b c d) (e f g h) (i j k):?A [7 ?Z {!} a b c d e f g h i j k {?} !A {!} a b c d e f g {?} !Z {!} h i j k
Burlesque
blsq ) {1 2 3}{4 5 6}_+
{1 2 3 4 5 6}
C
A way to concatenate two C arrays when you know their size (and usually so it is)
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define ARRAY_CONCAT(TYPE, A, An, B, Bn) \
(TYPE *)array_concat((const void *)(A), (An), (const void *)(B), (Bn), sizeof(TYPE));
void *array_concat(const void *a, size_t an,
const void *b, size_t bn, size_t s)
{
char *p = malloc(s * (an + bn));
memcpy(p, a, an*s);
memcpy(p + an*s, b, bn*s);
return p;
}
// testing
const int a[] = { 1, 2, 3, 4, 5 };
const int b[] = { 6, 7, 8, 9, 0 };
int main(void)
{
unsigned int i;
int *c = ARRAY_CONCAT(int, a, 5, b, 5);
for(i = 0; i < 10; i++)
printf("%d\n", c[i]);
free(c);
return EXIT_SUCCCESS;
}
C#
using System;
namespace RosettaCode
{
class Program
{
static void Main(string[] args)
{
int[] a = { 1, 2, 3 };
int[] b = { 4, 5, 6 };
int[] c = new int[a.Length + b.Length];
a.CopyTo(c, 0);
b.CopyTo(c, a.Length);
foreach(int n in c)
{
Console.WriteLine(n.ToString());
}
}
}
}
Alternatively, using LINQ extension methods:
using System.Linq;
class Program
{
static void Main(string[] args)
{
int[] a = { 1, 2, 3 };
int[] b = { 4, 5, 6 };
int[] c = a.Concat(b).ToArray();
}
}
C++
#include <vector>
#include <iostream>
int main()
{
std::vector<int> a(3), b(4);
a[0] = 11; a[1] = 12; a[2] = 13;
b[0] = 21; b[1] = 22; b[2] = 23; b[3] = 24;
a.insert(a.end(), b.begin(), b.end());
for (int i = 0; i < a.size(); ++i)
std::cout << "a[" << i << "] = " << a[i] << "\n";
}
Similar to above but using initialization schematics.
#include <vector>
#include <iostream>
int main() {
std::vector<int> a {1, 2, 3, 4};
std::vector<int> b {5, 6, 7, 8, 9};
a.insert(a.end(), b.begin(), b.end());
for(int& i: a) std::cout << i << " ";
std::cout << std::endl;
return 0;
}
This is another solution with function level templates and pointers.
#include <iostream>
using namespace std;
template <typename T1, typename T2>
int* concatArrays( T1& array_1, T2& array_2) {
int arrayCount_1 = sizeof(array_1) / sizeof(array_1[0]);
int arrayCount_2 = sizeof(array_2) / sizeof(array_2[0]);
int newArraySize = arrayCount_1 + arrayCount_2;
int *p = new int[newArraySize];
for (int i = 0; i < arrayCount_1; i++) {
p[i] = array_1[i];
}
for (int i = arrayCount_1; i < newArraySize; i++) {
int newIndex = i-arrayCount_2;
if (newArraySize % 2 == 1)
newIndex--;
p[i] = array_2[newIndex];
cout << "i: " << i << endl;
cout << "array_2[i]: " << array_2[newIndex] << endl;
cout << endl;
}
return p;
}
int main() {
int ary[4] = {1, 2, 3, 123};
int anotherAry[3] = {4, 5, 6};
int *r = concatArrays(ary, anotherAry);
cout << *(r + 0) << endl;
cout << *(r + 1) << endl;
cout << *(r + 2) << endl;
cout << *(r + 3) << endl;
cout << *(r + 4) << endl;
cout << *(r + 5) << endl;
cout << *(r + 6) << endl;
delete r;
return 0;
}
Ceylon
shared void arrayConcatenation() {
value a = Array {1, 2, 3};
value b = Array {4, 5, 6};
value c = concatenate(a, b);
print(c);
}
Clojure
(concat [1 2 3] [4 5 6])
The inputs can be any collection, including Java arrays, and returns a lazy sequence of the elements.
A vector is the closest Clojure thing to an array. If a vector is wanted, then use
(into [1 2 3] [4 5 6])
COBOL
IDENTIFICATION DIVISION.
PROGRAM-ID. array-concat.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 table-one.
05 int-field PIC 999 OCCURS 0 TO 5 TIMES DEPENDING ON t1.
01 table-two.
05 int-field PIC 9(4) OCCURS 0 TO 10 TIMES DEPENDING ON t2.
77 tally USAGE IS INDEX.
77 t1 PIC 99.
77 t2 PIC 99.
77 show PIC Z(4) USAGE IS DISPLAY.
PROCEDURE DIVISION.
array-concat-main.
PERFORM initialize-tables
PERFORM concatenate-tables
PERFORM display-result
GOBACK.
initialize-tables.
MOVE 4 TO t1
PERFORM VARYING tally FROM 1 BY 1 UNTIL tally > t1
COMPUTE int-field OF table-one(tally) = tally * 3
END-PERFORM
MOVE 3 TO t2
PERFORM VARYING tally FROM 1 BY 1 UNTIL tally > t2
COMPUTE int-field OF table-two(tally) = tally * 6
END-PERFORM.
concatenate-tables.
PERFORM VARYING tally FROM 1 BY 1 UNTIL tally > t1
ADD 1 TO t2
MOVE int-field OF table-one(tally)
TO int-field OF table-two(t2)
END-PERFORM.
display-result.
PERFORM VARYING tally FROM 1 BY 1 UNTIL tally = t2
MOVE int-field OF table-two(tally) TO show
DISPLAY FUNCTION TRIM(show) ", " WITH NO ADVANCING
END-PERFORM
MOVE int-field OF table-two(tally) TO show
DISPLAY FUNCTION TRIM(show).
END PROGRAM array-concat.
- Output:
$ cobc -xjd array-concatenation.cob --std=cobol2014 # COBOL 2014 needed for FUNCTION TRIM 6, 12, 18, 3, 6, 9, 12
CoffeeScript
# like in JavaScript
a = [1, 2, 3]
b = [4, 5, 6]
c = a.concat b
Common Lisp
concatenate
is a general function for concatenating any type of sequence. It takes the type of sequence to produce, followed by any number of sequences of any type.
(concatenate 'vector #(0 1 2 3) #(4 5 6 7))
=> #(0 1 2 3 4 5 6 7)
Alternate solution
I use Allegro CL 10.1
(setf arr1 (make-array '(3) :initial-contents '(1 2 3)))
(setf arr2 (make-array '(3) :initial-contents '(4 5 6)))
(setf arr3 (make-array '(3) :initial-contents '(7 8 9)))
(setf arr4 (make-array '(6)))
(setf arr5 (make-array '(9)))
(setf arr4 (concatenate `(vector ,(array-element-type arr1)) arr1 arr2))
(format t "~a" "concatenate arr1 and arr2: ")
(write arr4)
(terpri)
(setf arr5 (concatenate `(vector ,(array-element-type arr1)) arr4 arr3))
(format t "~a" "concatenate arr4 and arr3: ")
(write arr5)
(terpri)
Output:
concatenate arr1 and arr2: #(1 2 3 4 5 6) concatenate arr4 and arr3: #(1 2 3 4 5 6 7 8 9)
Component Pascal
BlackBox Component Builder
MODULE ArrayConcat;
IMPORT StdLog;
PROCEDURE Concat(x: ARRAY OF INTEGER; y: ARRAY OF INTEGER; OUT z: ARRAY OF INTEGER);
VAR
i: INTEGER;
BEGIN
ASSERT(LEN(x) + LEN(y) <= LEN(z));
FOR i := 0 TO LEN(x) - 1 DO z[i] := x[i] END;
FOR i := 0 TO LEN(y) - 1 DO z[i + LEN(x)] := y[i] END
END Concat;
PROCEDURE Concat2(x: ARRAY OF INTEGER;y: ARRAY OF INTEGER): POINTER TO ARRAY OF INTEGER;
VAR
z: POINTER TO ARRAY OF INTEGER;
i: INTEGER;
BEGIN
NEW(z,LEN(x) + LEN(y));
FOR i := 0 TO LEN(x) - 1 DO z[i] := x[i] END;
FOR i := 0 TO LEN(y) - 1 DO z[i + LEN(x)] := y[i] END;
RETURN z;
END Concat2;
PROCEDURE ShowArray(x: ARRAY OF INTEGER);
VAR
i: INTEGER;
BEGIN
i := 0;
StdLog.Char('[');
WHILE (i < LEN(x)) DO
StdLog.Int(x[i]);IF i < LEN(x) - 1 THEN StdLog.Char(',') END;
INC(i)
END;
StdLog.Char(']');StdLog.Ln;
END ShowArray;
PROCEDURE Do*;
VAR
x: ARRAY 10 OF INTEGER;
y: ARRAY 15 OF INTEGER;
z: ARRAY 25 OF INTEGER;
w: POINTER TO ARRAY OF INTEGER;
i: INTEGER;
BEGIN
FOR i := 0 TO LEN(x) - 1 DO x[i] := i END;
FOR i := 0 TO LEN(y) - 1 DO y[i] := i END;
Concat(x,y,z);StdLog.String("1> ");ShowArray(z);
NEW(w,LEN(x) + LEN(y));
Concat(x,y,z);StdLog.String("2:> ");ShowArray(z);
StdLog.String("3:> ");ShowArray(Concat2(x,y));
END Do;
END ArrayConcat.
Execute: ^Q ArrayConcat.Do
- Output:
1> [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] 2:> [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] 3:> [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
Crystal
arr1 = [1, 2, 3]
arr2 = ["foo", "bar", "baz"]
arr1 + arr2 #=> [1, 2, 3, "foo", "bar", "baz"]
D
import std.stdio: writeln;
void main() {
int[] a = [1, 2];
int[] b = [4, 5, 6];
writeln(a, " ~ ", b, " = ", a ~ b);
}
- Output:
[1, 2] ~ [4, 5, 6] = [1, 2, 4, 5, 6]
Delphi
2022/07/13
// This example works on stuff as old as Delphi 5 (maybe older)
// Modern Delphi / Object Pascal has both
// • generic types
// • the ability to concatenate arrays with the '+' operator
// So I could just say:
// myarray := [1] + [2, 3];
// But if you do not have access to the latest/greatest, then:
{$apptype console}
type
// Array types must be declared in order to return them from functions
// They can also be used with open array parameters.
TArrayOfString = array of string;
function Concat( a, b : array of string ): TArrayOfString; overload;
{
Every array type needs its own 'Concat' function:
function Concat( a, b : array of integer ): TArrayOfInteger; overload;
function Concat( a, b : array of double ): TArrayOfDouble; overload;
etc
Also, dynamic and open array types ALWAYS start at 0. No need to complicate indexing here.
}
var
n : Integer;
begin
SetLength( result, Length(a)+Length(b) );
for n := 0 to High(a) do result[ n] := a[n];
for n := 0 to High(b) do result[Length(a)+n] := b[n]
end;
// Example time!
function Join( a : array of string; sep : string = ' ' ): string;
var
n : integer;
begin
if Length(a) > 0 then result := a[0];
for n := 1 to High(a) do result := result + sep + a[n]
end;
var
names : TArrayOfString;
begin
// Here we use the open array parameter constructor as a convenience
names := Concat( ['Korra', 'Asami'], ['Bolin', 'Mako'] );
WriteLn( Join(names) );
// Also convenient: open array parameters are assignment-compatible with our array type!
names := Concat( names, ['Varrick', 'Zhu Li'] );
WriteLn( #13#10, Join(names, ', ') );
names := Concat( ['Tenzin'], names );
Writeln( #13#10, Join(names, #13#10 ) );
end.
Output:
Korra Asami Bolin Mako Korra, Asami, Bolin, Mako, Varrick, Zhu Li Tenzin Korra Asami Bolin Mako Varrick Zhu Li
What follows is older content found on this page.
It has running commentary about memory management that isn’t exactly correct.
Delphi handles dynamic array memory very well.
type
TReturnArray = array of integer; //you need to define a type to be able to return it
function ConcatArray(a1,a2:array of integer):TReturnArray;
var
i,r:integer;
begin
{ Low(array) is not necessarily 0 }
SetLength(result,High(a1)-Low(a1)+High(a2)-Low(a2)+2); //BAD idea to set a length you won't release, just to show the idea!
r:=0; //index on the result may be different to indexes on the sources
for i := Low(a1) to High(a1) do begin
result[r] := a1[i];
Inc(r);
end;
for i := Low(a2) to High(a2) do begin
result[r] := a2[i];
Inc(r);
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
a1,a2:array of integer;
r1:array of integer;
i:integer;
begin
SetLength(a1,4);
SetLength(a2,3);
for i := Low(a1) to High(a1) do
a1[i] := i;
for i := Low(a2) to High(a2) do
a2[i] := i;
TReturnArray(r1) := ConcatArray(a1,a2);
for i := Low(r1) to High(r1) do
showMessage(IntToStr(r1[i]));
Finalize(r1); //IMPORTANT!
ShowMessage(IntToStr(High(r1)));
end;
Diego
set_namespace(rosettacode)_me();
add_ary(a)_values(1,2,3);
add_ary(b)_values(4,5,6);
me_msg()_ary[a]_concat[b]
me_msg()_ary[a]_concat()_ary[b]; // alternative
me_msg()_calc([a]+[b]); // alternative
reset_namespace[];
Dyalect
var xs = [1,2,3]
var ys = [4,5,6]
var alls = Array.Concat(xs, ys)
print(alls)
- Output:
[1, 2, 3, 4, 5, 6]
E
? [1,2] + [3,4]
# value: [1, 2, 3, 4]
EasyLang
a[] = [ 1 2 3 ]
b[] = [ 4 5 6 ]
c[] = a[]
for h in b[]
c[] &= h
.
print c[]
EchoLisp
The native operators are append for lists, and vector-append for vectors (1-dim arrays).
;;;; VECTORS
(vector-append (make-vector 6 42) (make-vector 4 666))
→ #( 42 42 42 42 42 42 666 666 666 666)
;;;; LISTS
(append (iota 5) (iota 6))
→ (0 1 2 3 4 0 1 2 3 4 5)
;; NB - append may also be used with sequences (lazy lists)
(lib 'sequences)
(take (append [1 .. 7] [7 6 .. 0]) #:all)
→ (1 2 3 4 5 6 7 6 5 4 3 2 1)
ECL
A := [1, 2, 3, 4];
B := [5, 6, 7, 8];
C := A + B;
Ecstasy
It is as simple as array1 + array2
:
String[] fruits = ["apples", "oranges"];
String[] grains = ["wheat", "corn"];
String[] all = fruits + grains;
Efene
using the ++ operator and the lists.append function
@public
run = fn () {
A = [1, 2, 3, 4]
B = [5, 6, 7, 8]
C = A ++ B
D = lists.append([A, B])
io.format("~p~n", [C])
io.format("~p~n", [D])
}
EGL
program ArrayConcatenation
function main()
a int[] = [ 1, 2, 3 ];
b int[] = [ 4, 5, 6 ];
c int[];
c.appendAll(a);
c.appendAll(b);
for (i int from 1 to c.getSize())
SysLib.writeStdout("Element " :: i :: " = " :: c[i]);
end
end
end
Ela
xs = [1,2,3]
ys = [4,5,6]
xs ++ ys
- Output:
[1,2,3,4,5,6]
Elena
ELENA 5.0 :
import extensions;
public program()
{
var a := new int[]{1,2,3};
var b := new int[]{4,5};
console.printLine(
"(",a.asEnumerable(),") + (",b.asEnumerable(),
") = (",(a + b).asEnumerable(),")").readChar();
}
- Output:
(1,2,3) + (4,5) = (1,2,3,4,5)
Elixir
iex(1)> [1, 2, 3] ++ [4, 5, 6]
[1, 2, 3, 4, 5, 6]
iex(2)> Enum.concat([[1, [2], 3], [4], [5, 6]])
[1, [2], 3, 4, 5, 6]
iex(3)> Enum.concat([1..3, [4,5,6], 7..9])
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Elm
import Element exposing (show, toHtml) -- elm-package install evancz/elm-graphics
import Html.App exposing (beginnerProgram)
import Array exposing (Array, append, initialize)
xs : Array Int
xs =
initialize 3 identity -- [0, 1, 2]
ys : Array Int
ys =
initialize 3 <| (+) 3 -- [3, 4, 5]
main = beginnerProgram { model = ()
, view = \_ -> toHtml (show (append xs ys))
, update = \_ _ -> ()
}
-- Array.fromList [0,1,2,3,4,5]
Emacs Lisp
The vconcat function returns a new array containing all the elements of it's arguments.
(vconcat '[1 2 3] '[4 5] '[6 7 8 9])
=> [1 2 3 4 5 6 7 8 9]
EMal
^|EMal has the concept of list expansion,
|you can expand a list to function arguments
|by prefixing it with the unary plus.
|^
List a = int[1,2,3]
List b = int[4,5,6]
List c = int[+a, +b]
writeLine(c)
- Output:
[1,2,3,4,5,6]
Erlang
In erlang, you can use the ++ operator or lists:append, which is implemented via ++.
On the shell,
1> [1, 2, 3] ++ [4, 5, 6].
[1,2,3,4,5,6]
2> lists:append([1, 2, 3], [4, 5, 6]).
[1,2,3,4,5,6]
3>
ERRE
PROGRAM ARRAY_CONCAT
DIM A[5],B[5],C[10]
!
! for rosettacode.org
!
BEGIN
DATA(1,2,3,4,5)
DATA(6,7,8,9,0)
FOR I=1 TO 5 DO ! read array A[.]
READ(A[I])
END FOR
FOR I=1 TO 5 DO ! read array B[.]
READ(B[I])
END FOR
FOR I=1 TO 10 DO ! append B[.] to A[.]
IF I>5 THEN
C[I]=B[I-5]
ELSE
C[I]=A[I]
END IF
PRINT(C[I];) ! print single C value
END FOR
PRINT
END PROGRAM
Euphoria
sequence s1,s2,s3
s1 = {1,2,3}
s2 = {4,5,6}
s3 = s1 & s2
? s3
- Output:
{1,2,3,4,5,6}
F#
Array concatenation.
let a = [|1; 2; 3|]
let b = [|4; 5; 6;|]
let c = Array.append a b
List concatenation (@ and List.append are equivalent).
let x = [1; 2; 3]
let y = [4; 5; 6]
let z1 = x @ y
let z2 = List.append x y
Factor
append
Example:
( scratchpad ) USE: sequences
( scratchpad ) { 1 2 } { 3 4 } append .
{ 1 2 3 4 }
Fantom
In fansh:
> a := [1,2,3]
> b := [4,5,6]
> a.addAll(b)
> a
[1,2,3,4,5,6]
Note 'addAll' is destructive. Write 'a.dup.addAll(b)' to create a fresh list.
FBSL
Array concatenation:
#APPTYPE CONSOLE
DIM aint[] ={1, 2, 3}, astr[] ={"one", "two", "three"}, asng[] ={!1, !2, !3}
FOREACH DIM e IN ARRAYMERGE(aint, astr, asng)
PRINT e, " ";
NEXT
PAUSE
- Output:
1 2 3 one two three 1.000000 2.000000 3.000000 Press any key to continue...
Forth
: $!+ ( a u a' -- a'+u )
2dup + >r swap move r> ;
: cat ( a2 u2 a1 u1 -- a3 u1+u2 )
align here dup >r $!+ $!+ r> tuck - dup allot ;
\ TEST
create a1 1 , 2 , 3 ,
create a2 4 , 5 ,
a2 2 cells a1 3 cells cat dump
8018425F0: 01 00 00 00 00 00 00 00 - 02 00 00 00 00 00 00 00 ................
801842600: 03 00 00 00 00 00 00 00 - 04 00 00 00 00 00 00 00 ................
801842610: 05 00 00 00 00 00 00 00 - ........
Fortran
program Concat_Arrays
implicit none
! Note: in Fortran 90 you must use the old array delimiters (/ , /)
integer, dimension(3) :: a = [1, 2, 3] ! (/1, 2, 3/)
integer, dimension(3) :: b = [4, 5, 6] ! (/4, 5, 6/)
integer, dimension(:), allocatable :: c, d
allocate(c(size(a)+size(b)))
c(1 : size(a)) = a
c(size(a)+1 : size(a)+size(b)) = b
print*, c
! alternative
d = [a, b] ! (/a, b/)
print*, d
end program Concat_Arrays
Free Pascal
Since FPC (Free Pascal compiler) version 3.2.0., the dynamic array concatenation operator +
is available, provided {$modeSwitch arrayOperators+}
(which is enabled by default in {$mode Delphi}
).
array2 := array0 + array1
Alternatively, one could use concat()
which is independent of above modeswitch and mode. Neither option requires the use of any libraries.:
array2 := concat(array0, array1);
A more complete example:
Program arrayConcat;
{$mode delphi}
type
TDynArr = array of integer;
var
i: integer;
arr1, arr2, arrSum : TDynArr;
begin
arr1 := [1, 2, 3];
arr2 := [4, 5, 6];
arrSum := arr1 + arr2;
for i in arrSum do
write(i, ' ');
writeln;
end.
- Output:
1 2 3 4 5 6
FreeBASIC
' FB 1.05.0 Win64
Sub ConcatArrays(a() As String, b() As String, c() As String)
Dim aSize As Integer = UBound(a) - LBound(a) + 1
Dim bSize As Integer = UBound(b) - LBound(b) + 1
Dim cSize As Integer = aSize + bSize
Redim c(0 To cSize - 1)
Dim i As Integer
For i = 0 To aSize - 1
c(i) = a(LBound(a) + i)
Next
For i = 0 To bSize - 1
c(UBound(a) + i + 1) = b(LBound(b) + i)
Next
End Sub
Dim a(3) As String = {"The", "quick", "brown", "fox"}
Dim b(4) As String = {"jumped", "over", "the", "lazy", "dog"}
Dim c() As String
ConcatArrays(a(), b(), c())
For i As Integer = LBound(c) To UBound(c)
Print c(i); " ";
Next
Print : Print
Print "Press any key to quit the program"
Sleep
- Output:
The quick brown fox jumped over the lazy dog
Frink
a = [1,2]
b = [3,4]
a.pushAll[b]
FunL
arr1 = array( [1, 2, 3] )
arr2 = array( [4, 5, 6] )
arr3 = array( [7, 8, 9] )
println( arr1 + arr2 + arr3 )
- Output:
ArraySeq(1, 2, 3, 4, 5, 6, 7, 8, 9)
Futhark
Array concatenation is done with the built-in function concat
, which can take any number of arguments:
concat as bs cd
FutureBasic
Option 1
void local fn DoIt
CFArrayRef array = @[@"Alpha",@"Bravo",@"Charlie"]
print array
array = fn ArrayByAddingObjectsFromArray( array, @[@"Delta",@"Echo",@"FutureBasic"] )
print array
end fn
window 1
fn DoIt
HandleEvents
Output:
( Alpha, Bravo, Charlie ) ( Alpha, Bravo, Charlie, Delta, Echo, FutureBasic )
Option 2
void local fn ConcatArrays
CFArrayRef array1 = @[@1,@2,@3], array2 = @[@4,@5,@6]
CFArrayRef array3 = concat(array1,array2) // any number of arguments
print array3
end fn
fn DoIt
HandleEvents
- Output:
( 1, 2, 3, 4, 5, 6 )
Gambas
Click this link to run this code
Public Sub Main()
Dim sString1 As String[] = ["The", "quick", "brown", "fox"]
Dim sString2 As String[] = ["jumped", "over", "the", "lazy", "dog"]
sString1.Insert(sString2)
Print sString1.Join(" ")
End
Output:
The quick brown fox jumped over the lazy dog
GAP
# Concatenate arrays
Concatenation([1, 2, 3], [4, 5, 6], [7, 8, 9]);
# [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
# Append to a variable
a := [1, 2, 3];
Append(a, [4, 5, 6);
Append(a, [7, 8, 9]);
a;
# [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
Genie
[indent=4]
/*
Array concatenation, in Genie
Tectonics: valac array-concat.gs
*/
/* Creates a new array */
def int_array_concat(x:array of int, y:array of int):array of int
var a = new Array of int(false, true, 0) /* (zero-terminated, clear, size) */
a.append_vals (x, x.length)
a.append_vals (y, y.length)
z:array of int = (owned) a.data
return z
def int_show_array(a:array of int)
for element in a do stdout.printf("%d ", element)
stdout.printf("\n")
init
x: array of int = {1, 2, 3}
y: array of int = {3, 2, 1, 0, -1}
z: array of int = int_array_concat(x, y)
stdout.printf("x: "); int_show_array(x)
stdout.printf("y: "); int_show_array(y)
stdout.printf("z: "); int_show_array(z)
print "%d elements in new array", z.length
- Output:
prompt$ valac array-concat.gs prompt$ ./array-concat x: 1 2 3 y: 3 2 1 0 -1 z: 1 2 3 3 2 1 0 -1 8 elements in new array
GLSL
This macro concatenates two arrays to form a new array. The first parameter is the type of the array:
#define array_concat(T,a1,a2,returned) \
T[a1.length()+a2.length()] returned; \
{ \
for(int i = 0; i < a1.length(); i++){ \
returned[i] = a1[i]; \
} \
for(int i = 0; i < a2.length(); i++){ \
returned[i+a1.length()] = a2[i]; \
} \
}
The macro can be used like this:
array_concat(float,float[](1.,2.,3.),float[](4.,5.,6.),returned);
int i = returned.length();
Go
package main
import "fmt"
func main() {
// Example 1: Idiomatic in Go is use of the append function.
// Elements must be of identical type.
a := []int{1, 2, 3}
b := []int{7, 12, 60} // these are technically slices, not arrays
c := append(a, b...)
fmt.Println(c)
// Example 2: Polymorphism.
// interface{} is a type too, one that can reference values of any type.
// This allows a sort of polymorphic list.
i := []interface{}{1, 2, 3}
j := []interface{}{"Crosby", "Stills", "Nash", "Young"}
k := append(i, j...) // append will allocate as needed
fmt.Println(k)
// Example 3: Arrays, not slices.
// A word like "array" on RC often means "whatever array means in your
// language." In Go, the common role of "array" is usually filled by
// Go slices, as in examples 1 and 2. If by "array" you really mean
// "Go array," then you have to do a little extra work. The best
// technique is almost always to create slices on the arrays and then
// use the copy function.
l := [...]int{1, 2, 3}
m := [...]int{7, 12, 60} // arrays have constant size set at compile time
var n [len(l) + len(m)]int
copy(n[:], l[:]) // [:] creates a slice that references the entire array
copy(n[len(l):], m[:])
fmt.Println(n)
}
- Output:
[1 2 3 7 12 60] [1 2 3 Crosby Stills Nash Young] [1 2 3 7 12 60]
Array concatenation needs can vary. Here is another set of examples that illustrate different techniques.
package main
import (
"reflect"
"fmt"
)
// Generic version
// Easier to make the generic version accept any number of arguments,
// and loop trough them. Otherwise there will be lots of code duplication.
func ArrayConcat(arrays ...interface{}) interface{} {
if len(arrays) == 0 {
panic("Need at least one arguemnt")
}
var vals = make([]*reflect.SliceValue, len(arrays))
var arrtype *reflect.SliceType
var totalsize int
for i,a := range arrays {
v := reflect.NewValue(a)
switch t := v.Type().(type) {
case *reflect.SliceType:
if arrtype == nil {
arrtype = t
} else if t != arrtype {
panic("Unequal types")
}
vals[i] = v.(*reflect.SliceValue)
totalsize += vals[i].Len()
default: panic("not a slice")
}
}
ret := reflect.MakeSlice(arrtype,totalsize,totalsize)
targ := ret
for _,v := range vals {
reflect.Copy(targ, v)
targ = targ.Slice(v.Len(),targ.Len())
}
return ret.Interface()
}
// Type specific version
func ArrayConcatInts(a, b []int) []int {
ret := make([]int, len(a) + len(b))
copy(ret, a)
copy(ret[len(a):], b)
return ret
}
func main() {
test1_a, test1_b := []int{1,2,3}, []int{4,5,6}
test1_c := ArrayConcatInts(test1_a, test1_b)
fmt.Println(test1_a, " + ", test1_b, " = ", test1_c)
test2_a, test2_b := []string{"a","b","c"}, []string{"d","e","f"}
test2_c := ArrayConcat(test2_a, test2_b).([]string)
fmt.Println(test2_a, " + ", test2_b, " = ", test2_c)
}
- Output:
[1 2 3] + [4 5 6] = [1 2 3 4 5 6] [a b c] + [d e f] = [a b c d e f]
Gosu
var listA = { 1, 2, 3 }
var listB = { 4, 5, 6 }
var listC = listA.concat( listB )
print( listC ) // prints [1, 2, 3, 4, 5, 6]
Groovy
Solution:
def list = [1, 2, 3] + ["Crosby", "Stills", "Nash", "Young"]
Test:
println list
- Output:
[1, 2, 3, Crosby, Stills, Nash, Young]
Haskell
A list is in Haskell one of the most common composite data types (constructed from other types). In the documentation we read for the append operation ++:
(++) :: [a] -> [a] -> [a]
Append two lists, i.e.:
[x1, ..., xm] ++ [y1, ..., yn] == [x1, ..., xm, y1, ..., yn] [x1, ..., xm] ++ [y1, ...] == [x1, ..., xm, y1, ...]
If the first list is not finite, the result is the first list.
This operator could be defined from the scratch using explicit recursion:
[] ++ x = x
(h:t) ++ y = h : (t ++ y)
or folding
x ++ y = foldr (:) y x
HicEst
REAL :: a(7), b(3), c(10)
c = a
DO i = 1, LEN(b)
c(i + LEN(a)) = b(i)
ENDDO
Hy
=> (setv a [1 2 3])
=> a
[1, 2, 3]
=> (+ a [4 5 6]) ; returns the concatenation
[1, 2, 3, 4, 5, 6]
=> a
[1, 2, 3]
=> (.extend a [7 8 9]) ; modifies the list in place
=> a
[1, 2, 3, 7, 8, 9]
=> (+ [1 2] [3 4] [5 6]) ; can accept multiple arguments
[1, 2, 3, 4, 5, 6]
i
main
a $= [1, 2, 3]
b $= [4, 5, 6]
print(a + b)
}
Icon and Unicon
Both languages have list concatenation built in. Lists are fully dynamic arrays which can be truncated or extended at either end.
IDL
Array concatenation can mean different things, depending on the number of dimensions of the arguments and the result. In the simplest case, with 1-dimensional arrays to begin with, there are two obvious ways to concatenate them. If my arrays are these:
> a = [1,2,3]
> b = [4,5,6]
> help,a
A INT = Array[3]
> help,b
B INT = Array[3]
> print,a
1 2 3
> print,b
4 5 6
Then they can be concatenated "at the ends":
> help,[a,b]
<Expression> INT = Array[6]
> print,[a,b]
1 2 3 4 5 6
or "at the sides":
> help,[[a],[b]]
<Expression> INT = Array[3, 2]
> print,[[a],[b]]
1 2 3
4 5 6
Note that this requires that the arrays have the same size at the side at which they are concatenated:
> b = transpose(b)
> help,b
B INT = Array[1, 3]
> print,b
4
5
6
> print,[a,b]
Unable to concatenate variables because the dimensions do not agree: B.
Execution halted at: $MAIN$
> print,[[a],[b]]
Unable to concatenate variables because the dimensions do not agree: B.
Execution halted at: $MAIN$
This can get a lot more complicated as a 3x4x5-element three-dimensional array can be concatenated with a 5x2x3-element array at exactly two "surfaces".
Idris
Idris will disambiguate functions based on type, so both List
(arbitrary length) and Vect
(fixed length) can be concatenated in the same way:
Idris> [1, 2] ++ [4, 5, 6] [1, 2, 3, 4, 5] : List Integer Idris> :module Data.Vect *Data/Vect> (the (Vect 2 Nat) [1, 2]) ++ (the (Vect 3 Nat) [3, 4, 5]) [1, 2, 3, 4, 5] : Vect 5 Nat
Inform 7
let A be {1, 2, 3};
let B be {4, 5, 6};
add B to A;
Insitux
(into [1 2 3] [4 5 6])
(.. vec [1 2 3] [4 5 6])
Ioke
iik> [1,2,3] + [3,2,1]
[1,2,3] + [3,2,1]
+> [1, 2, 3, 3, 2, 1]
J
Solution: ,
Example:
array1 =: 1 2 3
array2 =: 4 5 6
array1 , array2
1 2 3 4 5 6
Of course, in J, array concatenation works (consistently) on arrays of any rank or dimension.
The verb ,
concatenates by treating the argument array with the largest number of dimensions as a list. Other primary verbs concatenate along other axes.
]ab=: 3 3 $ 'aaabbbccc'
aaa
bbb
ccc
]wx=: 3 3 $ 'wxyz'
wxy
zwx
yzw
ab , wx
aaa
bbb
ccc
wxy
zwx
yzw
ab ,. wx
aaawxy
bbbzwx
cccyzw
ab ,: wx
aaa
bbb
ccc
wxy
zwx
yzw
$ ab , wx NB. applies to first (highest) axis
6 3
$ ab ,. wx NB. applies to last (atomic) axis
3 6
$ ab ,: wx NB. applies to new (higher) axis
2 3 3
Jakt
fn main() {
let a = ["Apple", "Banana"]
let b = ["Cherry", "Durian"]
mut c: [String] = []
c.push_values(&a)
c.push_values(&b)
println("{}", c)
}
- Output:
["Apple", "Banana", "Cherry", "Durian"]
Java
In Java, arrays are immutable, so you'll have to create a new array, and copy the contents of the two arrays into it.
Luckily, Java offers the System.arraycopy method, which will save you the effort of creating the for-loops.
int[] concat(int[] arrayA, int[] arrayB) {
int[] array = new int[arrayA.length + arrayB.length];
System.arraycopy(arrayA, 0, array, 0, arrayA.length);
System.arraycopy(arrayB, 0, array, arrayA.length, arrayB.length);
return array;
}
If you wanted to use for-loops, possibly to mutate the data as it's concatenated, you can use the following.
int[] concat(int[] arrayA, int[] arrayB) {
int[] array = new int[arrayA.length + arrayB.length];
for (int index = 0; index < arrayA.length; index++)
array[index] = arrayA[index];
for (int index = 0; index < arrayB.length; index++)
array[index + arrayA.length] = arrayB[index];
return array;
}
A less idiomatic approach would be to use a List, which is a mutable array, similar to a "vector" in other languages.
I have used both arrays and Lists extensively and have not noticed any sort of performance degradation, they appear to work equally as fast.
It's worth noting that the Java Collections Framework, which contains the List class, is built specifically for Objects and not necessarily primitive data-types. Despite this, it's still worth using for primitives, although the conversion to and from arrays is somewhat abstruse.
int[] concat(int[] arrayA, int[] arrayB) {
List<Integer> list = new ArrayList<>();
for (int value : arrayA) list.add(value);
for (int value : arrayB) list.add(value);
int[] array = new int[list.size()];
for (int index = 0; index < list.size(); index++)
array[index] = list.get(index);
return array;
}
JavaScript
The Array.concat()
method returns a new array comprised of this array joined with other array(s) and/or value(s).
var a = [1,2,3],
b = [4,5,6],
c = a.concat(b); //=> [1,2,3,4,5,6]
Or, if we consider the concatenation of two arrays as a particular instance of the more general problem of concatenating 2 or more arrays, we can write a generic function:
See, for a function with an analogous type signature, concat in the Haskell Prelude.
(function () {
'use strict';
// concat :: [[a]] -> [a]
function concat(xs) {
return [].concat.apply([], xs);
}
return concat(
[["alpha", "beta", "gamma"],
["delta", "epsilon", "zeta"],
["eta", "theta", "iota"]]
);
})();
- Output:
["alpha", "beta", "gamma", "delta", "epsilon", "zeta", "eta", "theta", "iota"]
Joy
[1 2 3] [4 5 6] concat.
jq
If a and b are two arrays, then a+b is their concatenation. Similarly for a+b+c.
To concatenate the component arrays of an array, A, the add filter can be used: A|add
jq also supports streams, which are somewhat array-like, so it may be worth mentioning that the concatenation of two or more streams can be accomplished using "," instead of "+".
[1,2] + [3] + [null] # => [1,2,3,null]
[range(1;3), 3, null] # => [1,2,3,null]
Julia
a = [1,2,3]
b = [4,5,6]
ab = [a;b]
# the above bracket notation simply generates a call to vcat
ab = vcat(a,b)
# hcat is short for `horizontal concatenation`
ab = hcat(a,b) #ab -> 3x2 matrix
# the append!(a,b) method is mutating, appending `b` to `a`
append!(a,b) # a now equals [1,2,3,4,5,6]
K
a: 1 2 3
b: 4 5 6
a,b
1 2 3 4 5 6
Concatenations on larger dimensions also use ",", often combined with other operations.
ab:3 3#"abcdefghi"
("abc"
"def"
"ghi")
dd:3 3#"012345678"
("012"
"345"
"678")
ab,dd
("abc"
"def"
"ghi"
"012"
"345"
"678")
+ab,dd / flip (transpose) join
("adg036"
"beh147"
"cfi258")
ab,'dd / eachpair join
("abc012"
"def345"
"ghi678")
+(+ab),dd
("abc036"
"def147"
"ghi258")
Klingphix
include ..\Utilitys.tlhy
( 1.0 "Hello" 3 2 / 4 2.1 power ) ( 5 6 7 8 ) chain print
" " input
- Output:
(1, "Hello", 1.5, 18.379173679952562, 5, 6, 7, 8)
Klong
[1 2 3],[4 5 6] :" join "
[1 2 3 4 5 6]
[1 2],:\[[3 4] [5 6] [7 8]] :" join each-left "
[[1 2 3 4] [1 2 5 6] [1 2 7 8]]
[1 2],:/[[3 4] [5 6] [7 8]] :" join each-right "
[[3 4 1 2] [5 6 1 2] [7 8 1 2]]
Kotlin
fun main() {
val a = intArrayOf(1, 2, 3)
val b = intArrayOf(4, 5, 6)
val c = a + b // [1, 2, 3, 4, 5, 6]
println(c.contentToString())
}
LabVIEW
Use the Build Array function.
This image is a VI Snippet, an executable image of LabVIEW code. The LabVIEW version is shown on the top-right hand corner. You can download it, then drag-and-drop it onto the LabVIEW block diagram from a file browser, and it will appear as runnable, editable code.
Lambdatalk
{def A {A.new 1 2 3 4 5 6}} -> [1,2,3,4,5,6]
{def B {A.new 7 8 9}} -> [7,8,9]
{A.concat {A} {B}} -> [1,2,3,4,5,6,7,8,9]
Lang
&a $= [1, 2, 3]
&b $= [4, 5, 6]
&c $= &a ||| &b
fn.println(&c)
Lang5
[1 2] [3 4] append collapse .
langur
val a = [1, 2, 3]
val b = [7, 8, 9]
val c = a ~ b
writeln c
- Output:
[1, 2, 3, 7, 8, 9]
Lasso
local(arr1 = array(1, 2, 3))
local(arr2 = array(4, 5, 6))
local(arr3 = #arr1->asCopy) // make arr3 a copy of arr2
#arr3->merge(#arr2) // concatenate 2 arrays
Result:
arr1 = array(1, 2, 3)
arr2 = array(4, 5, 6)
arr3 = array(4, 5, 6)
arr3 = array(1, 2, 3, 4, 5, 6)
LDPL
include "std-list.ldpl"
data:
arr1 is number list
arr2 is number list
procedure:
push 1 to arr1
push 2 to arr1
push 3 to arr2
push 4 to arr2
append list arr2 to list arr1
display list arr1
- Output:
[1, 2, 3, 4]
LFE
> (++ '(1 2 3) '(4 5 6))
(1 2 3 4 5 6)
> (: lists append '(1 2 3) '(4 5 6))
(1 2 3 4 5 6)
Liberty BASIC
x=10
y=20
dim array1(x)
dim array2(y)
[concatenate]
dim array3(x + y)
for i = 1 to x
array3(i) = array1(i)
next
for i = 1 to y
array3(i + x) = array2(i)
next
[print]
for i = 1 to x + y
print array3(i)
next
LIL
LIL uses lists instead of arrays. The builtin append command could be used as append a $b. That would add the entire list in variable b as one item to list a. Below quote is used to flatten the lists into a single new list of all items.
##
Array concatenation in LIL
##
set a [list 1 2 3]
set b [list 4 5 6]
set c [quote $a $b]
print $c
print "[index $c 0] [index $c 3]"
- Output:
prompt$ lil arrayConcatenation.lil 1 2 3 4 5 6 1 4
Limbo
implement Command;
include "sys.m";
sys: Sys;
include "draw.m";
include "sh.m";
init(nil: ref Draw->Context, nil: list of string)
{
sys = load Sys Sys->PATH;
a := array[] of {1, 2};
b := array[] of {3, 4, 5};
c := array[len a + len b] of int;
c[:] = a;
c[len a:] = b;
for (i := 0; i < len c; i++)
sys->print("%d\n", c[i]);
}
Lingo
a = [1,2]
b = [3,4,5]
repeat with v in b
a.append(v)
end repeat
put a
-- [1, 2, 3, 4, 5]
Little
void main() {
int a[] = {0, 1, 2, 3, 4};
int b[] = {5, 6, 7, 8, 9};
int c[] = {(expand)a, (expand)b};
puts(c);
}
Logo
COMBINE is used to combine lists or words. SENTENCE is used to combine lists and words into a single list.
to combine-arrays :a1 :a2
output listtoarray sentence arraytolist :a1 arraytolist :a2
end
show combine-arrays {1 2 3} {4 5 6} ; {1 2 3 4 5 6}
Lua
a = {1, 2, 3}
b = {4, 5, 6}
for _, v in pairs(b) do
table.insert(a, v)
end
print(table.concat(a, ", "))
- Output:
1, 2, 3, 4, 5, 6
M2000 Interpreter
a=(1,2,3,4,5)
b=Cons(a, (6,7,8),a)
Print b
1 2 3 4 5 6 7 8 1 2 3 4 5
Adding 2 dimension arrays
Dim Base 0, A(2,2)=1, B(1,2)=6
A()=Cons(A(), B(), A(), B())
\\ Restore the dimensions (without erasing items)
Dim A(Dimension(A(),1)/2, 2)
For I=0 to Dimension(A(),1)-1 {
For j=0 to Dimension(A(),2)-1 {
Print A(i, j),
}
Print
}
- Output:
1 1 1 1 6 6 1 1 1 1 6 6
Adding 2 dimension arrays using OLE clause
Dim OLE Base 0, A(2,2)=1, B(1,2)=6
A()=Cons(A(), B(), A(), B())
\\ Restore the dimensions (without erasing items)
Dim A(Dimension(A(),1)/2, 2)
For I=0 to Dimension(A(),1)-1 {
For j=0 to Dimension(A(),2)-1 {
Print A(i, j),
}
Print
}
- Output:
1 1 1 1 1 1 1 1 6 6 6 6
Maple
There is a built-in procedure for concatenating arrays (and similar objects such as matrices or vectors). Arrays can be concatenated along any given dimension, which is specified as the first argument.
> A := Array( [ 1, 2, 3 ] );
A := [1, 2, 3]
> B := Vector['row']( [ sin( x ), cos( x ), tan( x ) ] );
B := [sin(x), cos(x), tan(x)]
> ArrayTools:-Concatenate( 1, A, B ); # stack vertically
[ 1 2 3 ]
[ ]
[sin(x) cos(x) tan(x)]
> ArrayTools:-Concatenate( 2, A, B ); # stack horizontally
[1, 2, 3, sin(x), cos(x), tan(x)]
> M := << a, b, c ; d, e, f >>; # a matrix
[a b c]
M := [ ]
[d e f]
> ArrayTools:-Concatenate( 1, M, A );
[a b c]
[ ]
[d e f]
[ ]
[1 2 3]
Of course, the order of the arguments is important.
> ArrayTools:-Concatenate( 1, A, M );
[1 2 3]
[ ]
[a b c]
[ ]
[d e f]
Lists, in Maple, might be considered to be a kind of "array" (in the sense that they look like arrays in memory), though they are actually immutable objects. However, they can be concatenated as follows.
> L1 := [ 1, 2, 3 ];
L1 := [1, 2, 3]
> L2 := [ a, b, c ];
L2 := [a, b, c]
> [ op( L1 ), op( L2 ) ];
[1, 2, 3, a, b, c]
> [ L1[], L2[] ]; # equivalent, just different syntax
[1, 2, 3, a, b, c]
Mathcad
Ref: [1] Mathcad Community Topic
Mathcad has a built-in array type that includes a natural 2D matrix-style format.
Mathcad can concatenate arrays in several ways. The easiest way is to use the built-in stack and augment functions.
stack concatenates arrays row-wise. The two (or more) arrays must have the same number of columns, and the resulting array row count is equal to the total number of rows in the stacked arrays.
augment concatenates arrays column-wise. The two (or more) arrays must have the same number of rows, and the resulting array column count is equal to the total number of columns in the augmented arrays.
create a pair of arbitrary array:
a:=matrix(2,2,max) b:=a+3
a=|0 1| b=|3 4|
|1 1| |4 4|
concatentate them vertically:
|0 1|
stack(a,b) = |1 1|
|3 4|
|4 4|
augment(a,b) = |0 1 3 4|
|1 1 3 4|
Mathematica / Wolfram Language
Join[{1,2,3}, {4,5,6}]
-> {1, 2, 3, 4, 5, 6}
MATLAB / Octave
Two arrays are concatenated by placing the two arrays between a pair of square brackets. A space between the two array names will concatenate them horizontally, and a semi-colon between array names will concatenate vertically.
>> a = [1 2 3];
>> b = [4 5 6];
>> c = [a b]
c =
1 2 3 4 5 6
>> c = [a;b]
c =
1 2 3
4 5 6
For concatenation along higher dimensions, use cat():
>> a = randn([3 4 5]);
>> b = randn([3 4 7]);
>> c = cat(3,a,b);
>> size(c)
ans =
3 4 12
Maxima
u: [1, 2, 3, 4]$
v: [5, 6, 7, 8, 9, 10]$
append(u, v);
/* [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] */
/* There are also functions for matrices */
a: matrix([6, 1, 8],
[7, 5, 3],
[2, 9, 4])$
addcol(a, ident(3));
/* matrix([6, 1, 8, 1, 0, 0],
[7, 5, 3, 0, 1, 0],
[2, 9, 4, 0, 0, 1]) */
addrow(a, ident(3));
/* matrix([6, 1, 8],
[7, 5, 3],
[2, 9, 4],
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]) */
Mercury
A `append` B = C
It could be "as simple as array1 + array2", but the 'array' module names the operation 'append' rather than '+'. It's tempting to just say that Mercury supports ad-hoc polymorphism - it can infer that a bare '+' refers to 'float.+' or 'int.+' (or that the 'append' above is array.append, rather than list.append), by the types involved - but it also handles other ambiguities in the same way. For instance, Mercury (like Prolog and Erlang) treats the arity of a function as part of its name, where a(1, 2) and a(1) involve the distinct functions a/2 and a/1. But Mercury also (unlike Prolog and Erlang) supports currying, where a(1) is a function that accepts a/2's second argument. So, is [a(X), a(Y), a(Z)] a list of whatever type a/1 evaluates to, or is it a list of curried a/2?
min
(1 2 3) (4 "apple" 6) concat print
- Output:
(1 2 3 4 "apple" 6)
MiniScript
arrOne = [1, 2, 3]
arrTwo = [4, 5, 6]
print arrOne + arrTwo
Nanoquery
Assuming a and b are array or list objects, they may concatenated using the '+' operator.
a + b
The '*' operator may also be used to create a specific number of copies of a list or array.
% a = list() % append a "a" "b" "c" % println a [a, b, c] % println a * 5 [a, b, c, a, b, c, a, b, c, a, b, c, a, b, c]
Neko
/*
Array concatenation, in Neko
*/
var a1 = $array(1,2,3,4)
var a2 = $array("abc", "def")
/* $array(a1, a2) creates an array of two arrays, $aconcat merges to one */
var ac = $aconcat($array(a1, a2))
$print(ac, "\n")
- Output:
prompt$ nekoc array-concatenation.neko prompt$ neko array-concatenation.n [1,2,3,4,abc,def]
Nemerle
using System.Console;
using Nemerle.Collections;
module ArrayCat
{
Main() : void
{
def arr1 = array[1, 2, 3]; def arr2 = array[4, 5, 6];
def arr12 = arr1.Append(arr2); // <----
foreach (i in arr12) Write($"$i ");
}
}
NetRexx
NetRexx arrays are identical to Java's so all the techniques described in the Java section apply to NetRexx too. This example uses the Collection classes to merge two arrays.
/* NetRexx */
options replace format comments java crossref nobinary
cymru = [ 'Ogof Ffynnon Ddu', 'Ogof Draenen' ]
dlm = '-'.copies(40)
say dlm
loop c_ = 0 to cymru.length - 1
say c_ cymru[c_]
end c_
yorks = [ 'Malham Tarn Pot', 'Greygill Hole' ]
say dlm
loop y_ = 0 to yorks.length - 1
say y_ yorks[y_]
end y_
merge = ArrayList()
merge.addAll(Arrays.asList(cymru))
merge.addAll(Arrays.asList(yorks))
say dlm
merged = merge.toArray()
loop m_ = 0 to merged.length - 1
say m_ merged[m_]
end m_
- Output:
---------------------------------------- 0 Ogof Ffynnon Ddu 1 Ogof Draenen ---------------------------------------- 0 Malham Tarn Pot 1 Greygill Hole ---------------------------------------- 0 Ogof Ffynnon Ddu 1 Ogof Draenen 2 Malham Tarn Pot 3 Greygill Hole
NewLISP
; file: arraycon.lsp
; url: http://rosettacode.org/wiki/Array_concatenation
; author: oofoe 2012-01-28
(println "Append lists: " (append '(3 a 5 3) (sequence 1 9)))
(println "Multi append: "
(append '(this is)
'(a test)
'(of the emergency)
(sequence 3 1)))
(println "Append arrays: "
(append '((x 56) (b 99)) '((z 34) (c 23) (r 88))))
(exit)
- Output:
Append lists: (3 a 5 3 1 2 3 4 5 6 7 8 9) Multi append: (this is a test of the emergency 3 2 1) Append arrays: ((x 56) (b 99) (z 34) (c 23) (r 88))
Nial
Examples tested to work with Q'Nial7
a:= 1 2 3
+-+-+-+
|1|2|3|
+-+-+-+
b:= 4 5 6
+-+-+-+
|4|5|6|
+-+-+-+
Table of lists:
a b
+-------+-------+
|+-+-+-+|+-+-+-+|
||1|2|3|||4|5|6||
|+-+-+-+|+-+-+-+|
+-------+-------+
Simple concatenation of two arrays/lists:
link a b
+-+-+-+-+-+-+
|1|2|3|4|5|6|
+-+-+-+-+-+-+
Convert list of lists to table:
mix a b
+-+-+-+
|1|2|3|
+-+-+-+
|4|5|6|
+-+-+-+
Interchange levels of a list of lists:
pack a b
+-----+-----+-----+
|+-+-+|+-+-+|+-+-+|
||1|4|||2|5|||3|6||
|+-+-+|+-+-+|+-+-+|
+-----+-----+-----+
Nim
Dynamic sized Sequences can simply be concatenated:
var
x = @[1,2,3,4,5,6]
y = @[7,8,9,10,11]
z = x & y
Static sized Arrays:
var
a = [1,2,3,4,5,6]
b = [7,8,9,10,11]
c: array[11, int]
c[0..5] = a
c[6..10] = b
Nu
let a = [1 2 3]
let b = [4 5 6]
By using the ++
operator:
$a ++ $b
By using the spread operator (...
):
[...$a ...$b]
With append
or prepend
:
$a | append $b
$b | prepend $a
With flatten
:
[$a $b] | flatten
- Output:
╭───┬───╮ │ 0 │ 1 │ │ 1 │ 2 │ │ 2 │ 3 │ │ 3 │ 4 │ │ 4 │ 5 │ │ 5 │ 6 │ ╰───┴───╯
Oberon-2
MODULE ArrayConcat;
IMPORT
Out;
TYPE
IntArray = POINTER TO ARRAY OF INTEGER;
VAR
x, y, z: IntArray;
PROCEDURE InitArray(VAR x: IntArray;from: INTEGER);
VAR
i: LONGINT;
BEGIN
FOR i := 0 TO LEN(x^) - 1 DO
x[i] := from;
INC(from)
END
END InitArray;
PROCEDURE Concat(x,y: IntArray; VAR z: IntArray);
VAR
i: LONGINT;
BEGIN
ASSERT(LEN(x^) + LEN(y^) <= LEN(z^));
FOR i := 0 TO LEN(x^) - 1 DO z[i] := x[i] END;
FOR i := 0 TO LEN(y^) - 1 DO z[i + LEN(x^)] := y[i] END
END Concat;
PROCEDURE Show(x: IntArray);
VAR
i: INTEGER;
BEGIN
i := 0;
Out.Char('[');
WHILE (i < LEN(x^)) DO
Out.LongInt(x[i],3);IF i < LEN(x^) - 1 THEN Out.Char(',') END;
INC(i)
END;
Out.Char(']');Out.Ln
END Show;
BEGIN
(* Standard types *)
NEW(x,5);InitArray(x,1);
NEW(y,10);InitArray(y,6);
NEW(z,LEN(x^) + LEN(y^));
Concat(x,y,z);
Show(z)
END ArrayConcat.
- Output:
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
Objeck
bundle Default {
class Arithmetic {
function : Main(args : String[]) ~ Nil {
array1 := [3, 5, 7];
array2 := [2, 4, 6];
array3 := Copy(array1, array2);
each(i : array3) {
array3[i]->PrintLine();
};
}
function : native : Copy(array1 : Int[], array2 : Int[]) ~ Int[] {
max := array1->Size() + array2->Size();
array3 := Int->New[max];
i := 0;
for(i := i; i < array1->Size(); i += 1;) {
array3[i] := array1[i];
};
j := 0;
for(i := i; i < max; i += 1;) {
array3[i] := array2[j];
j += 1;
};
return array3;
}
}
}
Objective-C
with immutable arrays:
NSArray *arr1 = @[@1, @2, @3];
NSArray *arr2 = @[@4, @5, @6];
NSArray *arr3 = [arr1 arrayByAddingObjectsFromArray:arr2];
or adding onto a mutable array:
NSArray *arr1 = @[@1, @2, @3];
NSArray *arr2 = @[@4, @5, @6];
NSMutableArray *arr3 = [NSMutableArray arrayWithArray:arr1];
[arr3 addObjectsFromArray:arr2];
OCaml
It is more natural in OCaml to use lists instead of arrays:
# let list1 = [1; 2; 3];;
val list1 : int list = [1; 2; 3]
# let list2 = [4; 5; 6];;
val list2 : int list = [4; 5; 6]
# let list1and2 = list1 @ list2;;
val list1and2 : int list = [1; 2; 3; 4; 5; 6]
If you want to use arrays:
# let array1 = [|1; 2; 3|];;
val array1 : int array = [|1; 2; 3|]
# let array2 = [|4; 5; 6|];;
val array2 : int array = [|4; 5; 6|]
# let array1and2 = Array.append array1 array2;;
val array1and2 : int array = [|1; 2; 3; 4; 5; 6|]
Odin
package main
import "core:fmt"
import "core:slice"
main :: proc() {
x: [3]int = {1, 2, 3}
y: [3]int = {4, 5, 6}
xy: [len(x) + len(y)]int
copy(xy[:], x[:])
copy(xy[len(x):], y[:])
fmt.println(xy)
}
Using slices
package main
import "core:fmt"
import "core:slice"
main :: proc() {
x: [3]int = {1, 2, 3}
y: [3]int = {4, 5, 6}
xy := slice.concatenate([][]int{x[:], y[:]})
defer delete(xy)
fmt.println(xy)
}
Oforth
import: mapping
[1, 2, 3 ] [ 4, 5, 6, 7 ] +
Onyx
# With two arrays on the stack, cat pops
# them, concatenates them, and pushes the result back
# on the stack. This works with arrays of integers,
# strings, or whatever. For example,
[1 2 3] [4 5 6] cat # result: [1 2 3 4 5 6]
[`abc' `def'] [`ghi' `jkl'] cat # result: [`abc' `def' `ghi' `jkl']
# To concatenate more than two arrays, push the number of arrays
# to concatenate onto the stack and use ncat. For example,
[1 true `a'] [2 false `b'] [`3rd array'] 3 ncat
# leaves [1 true `a' 2 false `b' `3rd array'] on the stack
ooRexx
a = .array~of(1,2,3)
say "Array a has " a~items "items"
b = .array~of(4,5,6)
say "Array b has " b~items "items"
a~appendall(b) -- adds all items from b to a
say "Array a now has " a~items "items"
- Output:
Array a has 3 items Array b has 3 items Array a now has 6 items
Order
Order supports two main aggregate types: tuples and sequences (similar to lists in other languages). Most "interesting" operations are limited to sequences, but both support an append operation, and each can be converted to the other.
#include <order/interpreter.h>
ORDER_PP( 8tuple_append(8tuple(1, 2, 3), 8tuple(4, 5, 6), 8pair(7, 8)) )
// -> (1,2,3,4,5,6,7,8)
ORDER_PP( 8seq_append(8seq(1, 2, 3), 8seq(4, 5, 6), 8seq(7, 8)) )
// -> (1)(2)(3)(4)(5)(6)(7)(8)
OxygenBasic
'CREATE DYNAMIC ARRAY SPACES USING STRINGS
string sa=nuls 5* sizeof float
string sb=sa
'MAP ARRAY VARIABLES ONTO STRINGS
float a at *sa
float b at *sb
'ASSIGN SOME VALUES
a<=10,20,30,40,50
b<=60,70,80,90,00
'ADD ARRAY B TO A BY STRING CONCATENATION
sa+=sb
'TEST
print a[7] 'result 70
Oz
List are concatenated with List.append
(shortcut: Append
). Tuples are concatened with Tuple.append
. Arrays do exist in Oz, but are rarely used.
%% concatenating 2 lists
{Append [a b] [c d]} = [a b c d]
%% concatenating 2 tuples
{Tuple.append t(1 2 3) u(4 5 6)} = u(1 2 3 4 5 6)
PARI/GP
concat(u,v)
Pascal
See Delphi and Free Pascal
PascalABC.NET
##
var a := |1,2,3,4|;
var b := Arr(5..8);
var c := a + b;
c.Println;
- Output:
1 2 3 4 5 6 7 8
Perl
In Perl, arrays placed into list context are flattened:
my @arr1 = (1, 2, 3);
my @arr2 = (4, 5, 6);
my @arr3 = (@arr1, @arr2);
The push
function appends elements onto an existing array:
my @arr1 = (1, 2, 3);
my @arr2 = (4, 5, 6);
push @arr1, @arr2;
print "@arr1\n"; # prints "1 2 3 4 5 6"
Phix
sequence s1 = {1,2,3}, s2 = {4,5,6} ? s1 & s2
- Output:
{1,2,3,4,5,6}
Phixmonti
1.0 "Hello" 3 2 / 4 2.1 power 4 tolist 5 6 7 8 4 tolist chain print
With syntactic sugar
include ..\Utilitys.pmt
( 1.0 "Hello" 3 2 / 4 2.1 power ) ( 5 6 7 8 ) chain print
PHP
$arr1 = array(1, 2, 3);
$arr2 = array(4, 5, 6);
$arr3 = array_merge($arr1, $arr2);
Picat
Picat has support for both lists and arrays and arrays can be much faster. Some list functions works with both lists and arrays, but some doesn't, e.g. append/3. In those cases one have to convert arrays to a list with to_list/1, and back again with to_array/1.
go =>
L1 = {1,2,3,4,5}, % define an array with {}
L2 = {6,7,8,9},
% The built-in array/list concatenation
println(L1 ++ L2),
% Using the built-in append/3 works only on lists
% so the arrays must be converted to lists.
append(L1.to_list,L2.to_list,L3),
println(L3.to_array),
nl.
- Output:
{1,2,3,4,5,6,7,8,9} {1,2,3,4,5,6,7,8,9}
PicoLisp
PicoLisp has no built-in array data type. Lists are used instead.
There are destructive concatenations:
: (setq A (1 2 3) B '(a b c))
-> (a b c)
: (conc A B) # Concatenate lists in 'A' and 'B'
-> (1 2 3 a b c)
: A
-> (1 2 3 a b c) # Side effect: List in 'A' is modified!
and non-destructive concatenations:
: (setq A (1 2 3) B '(a b c))
-> (a b c)
: (append A B) # Append lists in 'A' and 'B'
-> (1 2 3 a b c)
: A
-> (1 2 3)
: B
-> (a b c) # Arguments are not modified
Pike
int main() {
array arr1 = ({1, 2, 3});
array arr2 = ({4, 5, 6});
array arr3 = arr1 + arr2;
}
PL/I
Trivial example requires no computational statement. Note that the arrays are not in static storage:
declare x(12) fixed;
declare b(5) fixed defined x;
declare c(7) fixed defined x(1sub+5);
A more general example using dynamic bounds. Again, no computation statement is required.
declare x(m+n) fixed;
declare b(m) fixed defined x;
declare c(n) fixed defined x(1sub+hbound(b,1));
An alternative, that can be used to advantage for matrices as well as vectors, follows. This example illustrates extending a matrix diagonally. Although fixed array bounds are used in the declarations, the bounds can be dynamic. Matrix B is extended by placing matrix C on its diagonal:
declare a(5,6) fixed;
declare b(3,4) fixed defined a(1sub, 2sub);
declare c(2,2) fixed defined a(1sub+hbound(b,1), 2sub+hbound(b,2));
declare (i, j, k) fixed;
a = 0;
put skip list ('Please type elements for a 3 x 4 matrix:');
get list (b);
put skip list ('Please type elements for a 2 x 2 matrix:');
get list (c);
put skip edit (c) ( skip, (hbound(c,2)) f(5,0) );
put skip list ('Composite matrix:');
put skip edit (a) ( skip, (hbound(a,2)) f(5,0) );
- Output:
Please type elements for a 3 x 4 matrix:
Please type elements for a 2 x 2 matrix:
13 14
15 16
Composite matrix:
1 2 3 4 0 0
5 6 7 8 0 0
9 10 11 12 0 0
0 0 0 0 13 14
0 0 0 0 15 16
Plain English
Plain English has these functions for concatenating two sets of things:
To append some things to some other things:
Put the things' first into a thing.
If the thing is nil, exit.
Remove the thing from the things.
Append the thing to the other things.
Repeat.
To prepend some things to some other things:
Get a thing from the things (backwards).
If the thing is nil, exit.
Remove the thing from the things.
Prepend the thing to the other things.
Repeat.
Pony
actor Main
new create(env:Env)=>
var a:Array[I32]=Array[I32](4)
var b:Array[I32]=Array[I32](2)
a.push(1)
a.push(2)
a.push(3)
a.push(4)
b.push(5)
b.push(6)
a.concat(b.values())
for i in a.values() do
env.out.print(i.string())
end
PostScript
[1 2 3 4] [5 6 7 8] concat
PowerShell
$a = 1,2,3
$b = 4,5,6
$c = $a + $b
Write-Host $c
Processing
int[] a = {1, 2, 3}, b = {4, 5, 6};
int[] c = concat(a, b);
Prolog
?- append([1,2,3],[4,5,6],R).
R = [1, 2, 3, 4, 5, 6].
PureBasic
Procedure displayArray(Array a(1), msg.s)
Protected i
Print(msg + " [")
For i = 0 To ArraySize(a())
Print(Str(a(i)))
If i <> ArraySize(a())
Print(", ")
EndIf
Next
PrintN("]")
EndProcedure
Procedure randomElements(Array a(1), lo, hi)
Protected i
For i = 0 To ArraySize(a())
a(i) = random(hi - lo) + lo
Next
EndProcedure
Procedure arrayConcat(Array a(1), Array b(1), Array c(1))
Protected i, newSize = ArraySize(a()) + ArraySize(b()) + 1
Dim c(newSize)
For i = 0 To ArraySize(a())
c(i) = a(i)
Next
For i = 0 To ArraySize(b())
c(i + ArraySize(a()) + 1) = b(i)
Next
EndProcedure
If OpenConsole()
Dim a(random(3) + 1)
Dim b(random(3) + 1)
Dim c(0) ;array will be resized by arrayConcat()
randomElements(a(), -5, 5)
randomElements(b(), -5, 5)
displayArray(a(), "a:")
displayArray(b(), "b:")
arrayConcat(a(), b(), c())
displayArray(c(), "concat of a[] + b[]:")
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit")
Input()
CloseConsole()
EndIf
- Output:
a: [5, 2, -4, -1, -2] b: [0, -4, -1] concat of a[] + b[]: [5, 2, -4, -1, -2, 0, -4, -1]
Python
The +
operator concatenates two lists and returns a new list.
The list.extend
method appends elements of another list to the receiver.
arr1 = [1, 2, 3]
arr2 = [4, 5, 6]
arr3 = [7, 8, 9]
arr4 = arr1 + arr2
assert arr4 == [1, 2, 3, 4, 5, 6]
arr4.extend(arr3)
assert arr4 == [1, 2, 3, 4, 5, 6, 7, 8, 9]
Note: list.extend is normally accomplished using the += operator like this:
arr5 = [4, 5, 6]
arr6 = [7, 8, 9]
arr6 += arr5
assert arr6 == [7, 8, 9, 4, 5, 6]
Q
list1:1 2 3
list2:4 5 6
list1,list2
QBasic
FUNCTION ConcatArrays(a(), b())
ta = UBOUND(a)
tb = UBOUND(b)
nt = ta + tb
FOR i = ta + 1 TO nt
a(i) = b(i - ta)
NEXT i
ConcatArrays = nt
END FUNCTION
dimen = 5
DIM a(dimen)
DIM b(dimen)
FOR i = 1 TO dimen
a(i) = i
b(i) = i + dimen
NEXT i
nt = ConcatArrays(a(), b())
FOR i = 1 TO nt
PRINT a(i);
IF i < nt THEN PRINT ", ";
NEXT i
QB64
Dim As Integer First, Second
First = 5: Second = 8
Dim As Integer Array1(1 To First), Array2(1 To Second), ArrayResult(1 To First + Second)
Init Array1(), 2
Print "First array"
ShowArr Array1()
Sleep 2
Print "Second array"
Init Array2(), 5
ShowArr Array2()
Sleep 2
Print "Final array"
ConcatArray Array1(), Array2(), ArrayResult()
ShowArr ArrayResult()
End
Sub Init (A() As Integer, R As Integer)
Dim Index As Integer
For Index = 1 To UBound(a)
A(Index) = Index * R
Next
End Sub
Sub ShowArr (A() As Integer)
Dim Index As Integer
For Index = 1 To UBound(a)
Print A(Index)
Next
End Sub
Sub ConcatArray (A() As Integer, B() As Integer, R() As Integer)
Dim Index As Integer
For Index = 1 To UBound(a)
R(Index) = A(Index)
Next
For Index = (1) To (UBound(b))
R(Index + UBound(a)) = B(Index)
Next
End Sub
Quackery
The word join
joins two nests.
Illustrated with a dialogue in the Quackery shell. (REPL)
> quackery Welcome to Quackery. Enter "leave" to leave the shell. /O> ' [ [ 1 2 ] [ 3 4 ] [ 5 6 ] ] ... ' [ [ 7 8 ] [ 9 0 ] ] join echo ... [ [ 1 2 ] [ 3 4 ] [ 5 6 ] [ 7 8 ] [ 9 0 ] ] Stack empty. /O> leave ... Goodbye.
R
a1 <- c(1, 2, 3)
a2 <- c(3, 4, 5)
a3 <- c(a1, a2)
Racket
(vector-append #(1 2 3 4) #(5 6 7) #(8 9 10))
- Output:
'#(1 2 3 4 5 6 7 8 9 10)
Raku
(formerly Perl 6)
my @array1 = 1, 2, 3;
my @array2 = 4, 5, 6;
# If you want to concatenate two array to form a third,
# either use the slip operator "|", to flatten each array.
my @array3 = |@array1, |@array2;
say @array3;
# or just flatten both arrays in one fell swoop
@array3 = flat @array1, @array2;
say @array3;
# On the other hand, if you just want to add the elements
# of the second array to the first, use the .append method.
say @array1.append: @array2;
- Output:
[1 2 3 4 5 6] [1 2 3 4 5 6] [1 2 3 4 5 6]
RapidQ
DEFINT A(1 to 4) = {1, 2, 3, 4}
DEFINT B(1 to 4) = {10, 20, 30, 40}
'Append array B to array A
Redim A(1 to 8) as integer
MEMCPY(varptr(A(5)), varptr(B(1)), Sizeof(integer)*4)
Rapira
arr1 := <* 1, 2, 3 *>
arr2 := <* 4, 5, 6 *>
output: arr1 + arr2
REBOL
a1: [1 2 3]
a2: [4 5 6]
a3: [7 8 9]
append a1 a2 ; -> [1 2 3 4 5 6]
append/only a1 a3 ; -> [1 2 3 4 5 6 [7 8 9]]
Red
>> arr1: ["a" "b" "c"]
>> arr2: ["d" "e" "f"]
>> append arr1 arr2
== ["a" "b" "c" "d" "e" "f"]
>> arr3: [1 2 3]
>> insert arr1 arr3
>> arr1
== [1 2 3 "a" "b" "c" "d" "e" "f"]
>> arr4: [22 33 44]
== [22 33 44]
>> append/only arr1 arr4
== [1 2 3 "a" "b" "c" "d" "e" "f" [22 33 44]]
ReScript
Js.Array2.concat(["a", "b"], ["c", "d", "e"]) == ["a", "b", "c", "d", "e"]
Retro
{ #1 #2 #3 } { #4 #5 #6 } a:append
REXX
REXX doesn't have arrays as such, but it has something that looks, feels, and tastes like arrays:
- stemmed variables
Simply, a stemmed array is a variable with an appended dot (.) followed by a symbol (it's normally an integer or an alphanumeric name).
There is no way to preallocate a stemmed variable, REXX just assigns them as they are created (assigned a value).
As such, there isn't an easy way to keep track of the number of "elements" in a REXX "array" (unless the programmer maintains a list).
Consider:
a.1 = 10
a.2 = 22.7
a.7 = -12
where now we have three "elements", and they are disjointed (another word for sparse).
There are ways to handle this in REXX however.
When assigning stemmed arrays, it is common to assign "element" zero to the number of values,
assuming that the stemmed variables are sequential.
example:
fact.0=8
fact.1= 1
fact.2= 2
fact.3= 6
fact.4= 24
fact.5= 120
fact.6= 720
fact.7= 5040
fact.8=40320
To concat two "arrays" in REXX, the following assumes that the stemmed variables are in order, with no gaps, and none have a "null" value.
/*REXX program to demonstrates how to perform array concatenation.*/
p.= /*(below) a short list of primes.*/
p.1=2; p.2=3; p.3=5; p.4=7; p.5=11; p.6=13
p.7=17; p.8=19; p.9=23; p.10=27; p.11=31; p.12=37
f.= /*(below) a list of Fibonacci #s.*/
f.0=0;f.1=1;f.2=1;f.3=2;f.4=3;f.5=5;f.6=8;f.7=13;f.8=21;f.9=34;f.10=55
do j=1 while p.j\==''
c.j=p.j /*assign C array with some primes*/
end /*j*/
n=j-1
do k=0 while f.k\==''; n=n+1
c.n=f.k /*assign C array with fib numbers*/
end /*k*/
say 'elements=' n
say
do m=1 for n
say 'c.'m"="c.m /*show a "merged" C array nums.*/
end /*m*/
/*stick a fork in it, we're done.*/
- Output:
elements= 23 c.1=2 c.2=3 c.3=5 c.4=7 c.5=11 c.6=13 c.7=17 c.8=19 c.9=23 c.10=27 c.11=31 c.12=37 c.13=0 c.14=1 c.15=1 c.16=2 c.17=3 c.18=5 c.19=8 c.20=13 c.21=21 c.22=34 c.23=55
Ring
arr1 = [1, 2, 3]
arr2 = [4, 5, 6]
arr3 = [7, 8, 9]
arr4 = arr1 + arr2
see arr4
see nl
arr5 = arr4 + arr3
see arr5
RLaB
In RLaB the matrices can be appended (column-wise) or stacked (row-wise). Consider few examples:
>> x = [1, 2, 3]
>> y = [4, 5, 6]
// appending matrix 'y' on the right from matrix 'x' is possible if the two matrices have
// the same number of rows:
>> z1 = [x, y]
matrix columns 1 thru 6
1 2 3 4 5 6
// stacking matrix 'y' below the matrix 'x' is possible if the two matrices have
// the same number of columns:
>> z2 = [x; y]
1 2 3
4 5 6
>>
RPL
In RPL, what is called arrays are actually vectors. Sets of numbers can be stored either in such data structures or in lists, depending on the planned use. Vectors are great for arithmetics, but lists are more versatile.
Vector concatenation
≪ SWAP ARRY→ LIST→ DROP → n ≪ n 1 + ROLL ARRY→ LIST→ DROP n + 1 →LIST →ARRY ≫ ≫ 'CONCAT' STO
[1 2 3] [4 5] CONCAT
- Output:
1: [1 2 3 4 5]
A shorter version, without any local variable:
≪ SWAP ARRY→ 1 GET →LIST SWAP ARRY→ 1 GET →LIST + LIST→ { } + →ARRY ≫ 'CONCAT' STO
List concatenation
No need for a program to do that:
{1 2 3} {4 5} +
- Output:
1: {1 2 3 4 5}
Ruby
The Array#+
method concatenates two arrays and returns a new array. The Array#concat
method appends elements of another array to the receiver.
arr1 = [1, 2, 3]
arr2 = [4, 5, 6]
arr3 = [7, 8, 9]
arr4 = arr1 + arr2 # => [1, 2, 3, 4, 5, 6]
arr4.concat(arr3) # => [1, 2, 3, 4, 5, 6, 7, 8, 9]
Or use flatten(1):
# concat multiple arrays:
[arr1,arr2,arr3].flatten(1)
# ignore nil:
[arr1,arr2,arr3].compact.flatten(1)
Rust
fn main() {
let a_vec = vec![1, 2, 3, 4, 5];
let b_vec = vec![6; 5];
let c_vec = concatenate_arrays(&a_vec, &b_vec);
println!("{:?} ~ {:?} => {:?}", a_vec, b_vec, c_vec);
}
fn concatenate_arrays<T: Clone>(x: &[T], y: &[T]) -> Vec<T> {
let mut concat = x.to_vec();
concat.extend_from_slice(y);
concat
}
Or, with iterators:
fn concatenate_arrays<T: Clone>(x: &[T], y: &[T]) -> Vec<T> {
x.iter().chain(y).cloned().collect()
}
S-lang
variable a = [1, 2, 3];
variable b = [4, 5, 6], c;
a+b is perfectly valid in S-Lang, but instead of the problem's desired effect, it gives you a new array with each coorresponding element from a and b added. But because arrays automatically 'flatten' when defined, concatenation is as simple as:
c = [a, b];
Use of lists is more traditional; lists don't 'flatten', so we use either list_concat() to create a new concatenated array:
a = {1, 2, 3};
b = {4, 5, 6};
c = list_concat(a, b);
or list_join():
list_join(a, b);
which adds the elements of b onto a.
SASL
In SASL, the concat operator ++ is built-in
(1 2 3) ++ (4 5 6)
Scala
val arr1 = Array( 1, 2, 3 )
val arr2 = Array( 4, 5, 6 )
val arr3 = Array( 7, 8, 9 )
arr1 ++ arr2 ++ arr3
//or:
Array concat ( arr1, arr2, arr3 )
// res0: Array[Int] = Array(1, 2, 3, 4, 5, 6, 7, 8, 9)
Scheme
; in r5rs, there is append for lists, but we'll need to define vector-append
(define (vector-append . arg) (list->vector (apply append (map vector->list arg))))
(vector-append #(1 2 3 4) #(5 6 7) #(8 9 10))
; #(1 2 3 4 5 6 7 8 9 10)
Note : vector-append is also defined in SRFI-43.
Concatening two-dimensional arrays
(use gauche.array)
(define (print-matrix m)
(define row-num #f)
(array-for-each-index m
(lambda (row col)
(when (and row-num (not (= row-num row))) (newline))
(format #t "~a " (array-ref m row col))
(set! row-num row)))
(newline))
(define a
#,(<array> (0 3 0 2)
a b
c d
e f))
(define b
#,(<array> (0 3 0 2)
1 2
3 4
5 6))
(print-matrix (array-concatenate a b))
(print-matrix (array-concatenate a b 1))
- Output:
a b c d e f 1 2 3 4 5 6 a b 1 2 c d 3 4 e f 5 6
Seed7
$ include "seed7_05.s7i";
var array integer: a is [] (1, 2, 3, 4);
var array integer: b is [] (5, 6, 7, 8);
var array integer: c is [] (9, 10);
const proc: main is func
local
var integer: number is 0;
begin
c := a & b;
for number range c do
write(number <& " ");
end for;
writeln;
end func;
- Output:
1 2 3 4 5 6 7 8
SenseTalk
put (1, 2, 3) into list1
put (4, 5, 6) into list2
put list1 &&& list2 into list3
put list3
SETL
A := [1, 2, 3];
B := [3, 4, 5];
print(A + B); -- [1 2 3 3 4 5]
Sidef
var arr1 = [1, 2, 3];
var arr2 = [4, 5, 6];
var arr3 = (arr1 + arr2); # => [1, 2, 3, 4, 5, 6]
Simula
BEGIN ! Concatenate arrays - of REAL, here;
CLASS REAL_ARRAY(N); INTEGER N;
BEGIN
REAL ARRAY DATA(1:N);
! Return a new REAL_ARRAY containing
! the values from this REAL_ARRAY
! followed by the values from other;
REF(REAL_ARRAY) PROCEDURE CONCAT(other);
REF(REAL_ARRAY) other;
BEGIN
REF(REAL_ARRAY) C;
INTEGER I;
C :- NEW REAL_ARRAY(N + other.N);
FOR I := 1 STEP 1 UNTIL N DO
C.DATA(I) := DATA(I);
FOR I := 1 STEP 1 UNTIL other.N DO
C.DATA(N + I) := other.DATA(I);
CONCAT :- C;
END;
! Fill DATA;
REF(REAL_ARRAY) PROCEDURE linearFill(start, stride);
REAL start, stride;
BEGIN
linearFillFrom(DATA, 1, N, start, stride);
linearFill :- this REAL_ARRAY
END;
PROCEDURE out(sink); REF(printfile) sink;
BEGIN
INTEGER i;
FOR i := 1 STEP 1 UNTIL N DO
sink.OUTFIX(DATA(i), 2, 7);
sink.OUTIMAGE;
END;
END REAL_ARRAY;
! "The problem" is not array as an input parameter:
! I don't know how to
! "pass a new ARRAY out of a PROCEDURE";
REF(REAL_ARRAY) PROCEDURE concatenate(a, b);
REAL ARRAY a, b;
BEGIN
INTEGER i, a_, N, b_, M;
REF(REAL_ARRAY) c;
a_ := LOWERBOUND(a, 1) - 1;
N := UPPERBOUND(a, 1) - a_;
b_ := LOWERBOUND(a, 1) - 1;
M := UPPERBOUND(b, 1) - b_;
c :- NEW REAL_ARRAY(N + M);
FOR i := 1 STEP 1 UNTIL N DO
c.DATA(i) := a(a_+i);
! for readability, don't
! reduce one index expression to a variable
FOR i := 1 STEP 1 UNTIL M DO
c.DATA(N + i) := b(b_+i);
concatenate :- c;
END concatenate REAL ARRAYs;
! two more convenience PROCEDUREs;
PROCEDURE linearFillFrom(a, from, inclusive, start, stride);
REAL ARRAY a; ! passed by reference;
INTEGER from, inclusive;
REAL start, stride;
BEGIN
INTEGER i;
FOR i := from STEP 1 UNTIL inclusive DO
a(i) := start + stride * (i - from)
END;
PROCEDURE linearFill(a, start, stride);
REAL ARRAY a;
REAL start, stride;
linearFillFrom(a, LOWERBOUND(a, 1), UPPERBOUND(a, 1),
start, stride);
REF(REAL_ARRAY) X;
REAL ARRAY u(1:3), v(1:4);
linearFill(u, 3, 7);
linearFill(v, 0, 5);
concatenate(u, v).out(SYSOUT);
X :- NEW REAL_ARRAY(3).linearFill(1, 2);
X.out(SYSOUT);
X.CONCAT(NEW REAL_ARRAY(4)
.linearFill(-1, -3)).out(SYSOUT);
END.
- Output:
3.00 10.00 17.00 0.00 5.00 10.00 15.00 1.00 3.00 5.00 1.00 3.00 5.00 -1.00 -4.00 -7.00 -10.00
Slate
The binary operation of concatenation is made with the ; (semi-colon) from the type Sequence. It is also available for appending Sequences to WriteStreams.
{1. 2. 3. 4. 5} ; {6. 7. 8. 9. 10}
Slope
(list-join [1 2 3] [4 5 6])
SmallBASIC
A = [1,2,3]
B = [4,5,6]
for i in B do A << i
print A
Smalltalk
Concatenation (appending) is made with the method , (comma), present in classes SequenceableCollection, ArrayedCollection and their subclasses (e.g. Array, String, OrderedCollection ...)
|a b c|
a := #(1 2 3 4 5).
b := #(6 7 8 9 10).
c := a,b.
c displayNl.
SNOBOL4
* # Concatenate 2 arrays (vectors)
define('cat(a1,a2)i,j') :(cat_end)
cat cat = array(prototype(a1) + prototype(a2))
cat1 i = i + 1; cat<i> = a1<i> :s(cat1)
cat2 j = j + 1; cat<i - 1 + j> = a2<j> :s(cat2)f(return)
cat_end
* # Fill arrays
str1 = '1 2 3 4 5'; arr1 = array(5)
loop i = i + 1; str1 len(p) span('0123456789') . arr1<i> @p :s(loop)
str2 = '6 7 8 9 10'; arr2 = array(5)
loop2 j = j + 1; str2 len(q) span('0123456789') . arr2<j> @q :s(loop2)
* # Test and display
arr3 = cat(arr1,arr2)
loop3 k = k + 1; str3 = str3 arr3<k> ' ' :s(loop3)
output = str1
output = str2
output = str3
end
- Output:
1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10
SparForte
As a structured script.
#!/usr/local/bin/spar
pragma annotate( summary, "arraycat" )
@( description, "Show how to concatenate two arrays in your language." )
@( category, "tutorials" )
@( author, "Ken O. Burtch" )
@( see_also, "http://rosettacode.org/wiki/Array_concatenation" );
pragma license( unrestricted );
pragma software_model( nonstandard );
pragma restriction( no_external_commands );
procedure arraycat is
type arrayOf3 is array(1..3) of integer;
a1 : constant arrayOf3 := (1, 2, 3);
a2 : constant arrayOf3 := (4, 5, 6);
type arrayOf6 is array(1..6) of integer;
a3 : arrayOf6;
p : natural := arrays.first(a3);
begin
-- In SparForte, & only works on strings and there's no indefinite ranges
-- or array slicing. We have to do this the hard way, one element at a
-- time.
for i in arrays.first(a1)..arrays.last(a1) loop
a3(p) := a1(i);
p := @+1;
end loop;
for i in arrays.first(a2)..arrays.last(a2) loop
a3(p) := a2(i);
p := @+1;
end loop;
-- show the array
for i in arrays.first(a3)..arrays.last(a3) loop
put( a3(i) );
end loop;
new_line;
end arraycat;
Standard ML
val l1 = [1,2,3,4];;
val l2 = [5,6,7,8];;
val l3 = l1 @ l2 (* [1,2,3,4,5,6,7,8] *)
Stata
Macro language
. matrix a=2,9,4\7,5,3\6,1,8
. matrix list a
a[3,3]
c1 c2 c3
r1 2 9 4
r2 7 5 3
r3 6 1 8
. matrix b=I(3)
. matrix list b
symmetric b[3,3]
c1 c2 c3
r1 1
r2 0 1
r3 0 0 1
. matrix c=a,b
. matrix list c
c[3,6]
c1 c2 c3 c1 c2 c3
r1 2 9 4 1 0 0
r2 7 5 3 0 1 0
r3 6 1 8 0 0 1
. matrix c=a\b
. matrix list c
c[6,3]
c1 c2 c3
r1 2 9 4
r2 7 5 3
r3 6 1 8
r1 1 0 0
r2 0 1 0
r3 0 0 1
Mata
. mata
: a=2,9,4\7,5,3\6,1,8
: b=I(3)
: a,b
1 2 3 4 5 6
+-------------------------+
1 | 2 9 4 1 0 0 |
2 | 7 5 3 0 1 0 |
3 | 6 1 8 0 0 1 |
+-------------------------+
: a\b
1 2 3
+-------------+
1 | 2 9 4 |
2 | 7 5 3 |
3 | 6 1 8 |
4 | 1 0 0 |
5 | 0 1 0 |
6 | 0 0 1 |
+-------------+
: end
Swift
let array1 = [1,2,3]
let array2 = [4,5,6]
let array3 = array1 + array2
Symstatic
let concat(a, b) := a + b
assert(concat([1, 2, 3], [4, 5, 6]) = [1, 2, 3, 4, 5, 6])
Tailspin
def a: [1, 2, 3];
def b: [4, 5, 6];
[$a..., $b...] -> !OUT::write
- Output:
[1, 2, 3, 4, 5, 6]
Tcl
set a {1 2 3}
set b {4 5 6}
set ab [concat $a $b]; # 1 2 3 4 5 6
Note that in the Tcl language, “arrays” are hash maps of strings to variables, so the notion of concatenation doesn't really apply. What other languages (usually) call arrays are “lists” in Tcl.
TI-89 BASIC
If a and b are lists, augment(a, b)
concatenates them in the usual fashion. If a and b are matrices, then augment(a, b)
produces a matrix whose columns are the columns of a followed by the columns of b, i.e. an augmented matrix.
■ augment({1,2}, {3,4}) {1,2,3,4} ■ augment([[1][2]], [[3][4]]) [[1,3][2,4]]
That last example as displayed in pretty-printing mode:
Concatenation in the other direction may of course be done by transposition:
■ augment([[x][y]], [[z][w]]) [[x][y][z][w]]
Trith
[1 2 3] [4 5 6] concat
Uiua
⊂[1 2 3] [4 5 6]
- Output:
[1 2 3 4 5 6]
UNIX Shell
Using proper built-in Bash arrays:
array1=( 1 2 3 4 5 )
array2=( 6 7 8 9 10 )
botharrays=( ${array1[@]} ${array2[@]} )
Whitespace-delimited strings work in much the same way:
array1='1 2 3 4 5'
array2='6 7 8 9 10'
# Concatenated to a Bash array ...
botharrays_a=( $array1 $array2 )
# Concatenated to a string ...
botharrays_s="$array1 $array2"
Ursa
# create two streams (the ursa equivalent of arrays)
# a contains the numbers 1-10, b contains 11-20
decl int<> a b
decl int i
for (set i 1) (< i 11) (inc i)
append i a
end for
for (set i 11) (< i 21) (inc i)
append i b
end for
# append the values in b to a
append b a
# output a to the console
out a endl console
Vala
int[] array_concat(int[]a,int[]b){
int[] c = new int[a.length + b.length];
Memory.copy(c, a, a.length * sizeof(int));
Memory.copy(&c[a.length], b, b.length * sizeof(int));
return c;
}
void main(){
int[] a = {1,2,3,4,5};
int[] b = {6,7,8};
int[] c = array_concat(a,b);
foreach(int i in c){
stdout.printf("%d\n",i);
}
}
VBA
Option Explicit
Sub MainConcat_Array()
Dim Aray_1() As Variant, Aray_2() As Variant
Dim Result() As Variant
Aray_1 = Array(1, 2, 3, 4, 5, #11/24/2017#, "azerty")
Aray_2 = Array("A", "B", "C", 18, "End")
Result = Concat_Array(Aray_1, Aray_2)
Debug.Print "With Array 1 : " & Join(Aray_1, ", ")
Debug.Print "And Array 2 : " & Join(Aray_2, ", ")
Debug.Print "The result is Array 3 : " & Join(Result, ", ")
End Sub
Function Concat_Array(A1() As Variant, A2() As Variant) As Variant()
Dim TmpA1() As Variant, N As Long, i As Long
N = UBound(A1) + 1
TmpA1 = A1
ReDim Preserve TmpA1(N + UBound(A2))
For i = N To UBound(TmpA1)
TmpA1(i) = A2(i - N)
Next
Concat_Array = TmpA1
End Function
- Output:
With Array 1 : 1, 2, 3, 4, 5, 24/11/2017, azerty And Array 2 : A, B, C, 18, End The result is Array 3 : 1, 2, 3, 4, 5, 24/11/2017, azerty, A, B, C, 18, End
VBScript
Function ArrayConcat(arr1, arr2)
ReDim ret(UBound(arr1) + UBound(arr2) + 1)
For i = 0 To UBound(arr1)
ret(i) = arr1(i)
Next
offset = Ubound(arr1) + 1
For i = 0 To UBound(arr2)
ret(i + offset) = arr2(i)
Next
ArrayConcat = ret
End Function
arr1 = array(10,20,30)
arr2 = array(40,50,60)
WScript.Echo "arr1 = array(" & Join(arr1,", ") & ")"
WScript.Echo "arr2 = array(" & Join(arr2,", ") & ")"
arr3 = ArrayConcat(arr1, arr2)
WScript.Echo "arr1 + arr2 = array(" & Join(arr3,", ") & ")"
- Output:
arr1 = array(10, 20, 30) arr2 = array(40, 50, 60) arr1 + arr2 = array(10, 20, 30, 40, 50, 60)
Visual Basic .NET
Dim iArray1() As Integer = {1, 2, 3}
Dim iArray2() As Integer = {4, 5, 6}
Dim iArray3() As Integer = Nothing
iArray3 = iArray1.Concat(iArray2).ToArray
V (Vlang)
V (Vlang) uses a << operator for array concatenation. Destination array needs to be mutable.
// V, array concatenation
// Tectonics: v run array-concatenation.v
module main
// starts here
pub fn main() {
mut arr1 := [1,2,3,4]
arr2 := [5,6,7,8]
arr1 << arr2
println(arr1)
}
- Output:
$ v run array-concatenation.v [1, 2, 3, 4, 5, 6, 7, 8]
Wart
Wart doesn't have arrays yet, just lists.
a <- '(1 2 3)
b <- '(4 5 6)
a+b
# => (1 2 3 4 5 6)
Wren
var arr1 = [1,2,3]
var arr2 = [4,5,6]
System.print(arr1 + arr2)
- Output:
[1, 2, 3, 4, 5, 6]
XPL0
A way to concatenate two XPL0 arrays when you know their size (and usually it is so). Works on Raspberry Pi. MAlloc works differently in other versions.
func Array_concat(A, AN, B, BN, S);
int A, AN, B, BN, S;
int P;
[
P:= MAlloc(S * (AN + BN));
CopyMem(P, A, AN*S);
CopyMem(P + AN*S, B, BN*S);
return P;
];
\ testing
int A, B, C, I, SizeOf;
[
A:= [ 1, 2, 3, 4, 5 ];
B:= [ 6, 7, 8, 9, 0 ];
SizeOf:= @B - @A;
C:= Array_concat(A, 5, B, 5, SizeOf);
for I:= 0 to 10-1 do
[IntOut(0, C(I)); ChOut(0, ^ )];
Release(C);
]
- Output:
1 2 3 4 5 6 7 8 9 0
Yabasic
sub arrayConcatenation(a(), b())
local ta, tb, nt, i
ta = arraysize(a(), 1)
tb = arraysize(b(), 1)
nt = ta + tb
redim a(nt)
for i = ta + 1 to nt
a(i) = b(i - ta)
next i
return nt
end sub
//===============================
SIZE = 5
dim a(SIZE)
dim b(SIZE)
for i = 1 to SIZE
a(i) = i
b(i) = i + SIZE
next i
nt = arrayConcatenation(a(), b())
for i = 1 to nt
print a(i);
if i < nt print ", ";
next i
print
Yacas
Concat({1,2,3}, {4,5,6})
Out> {1, 2, 3, 4, 5, 6}
Yorick
a = [1,2,3];
b = [4,5,6];
ab = grow(a, b);
Z80 Assembly
The routine Monitor_Memdump
displays a hexdump to the Amstrad CPC's screen.
Credit to Keith of ChibiAkumas for creating it.
org $8000
ld hl,TestArray1 ; pointer to first array
ld de,ArrayRam ; pointer to ram area
ld bc,6 ; size of first array
ldir
; DE is already adjusted past the last entry
; of the first array
ld hl,TestArray2 ; pointer to second array
ld bc,4 ; size of second array
ldir
call Monitor_MemDump
db 32 ; hexdump 32 bytes (only the bytes from the arrays will be shown in the output for clarity)
dw ArrayRam ; start dumping from ArrayRam
ret ; return to basic
ArrayRam:
ds 24,0 ;24 bytes of ram initialized to zero
org $9000
TestArray2:
byte $23,$45,$67,$89
; just to prove that this doesn't rely on the arrays
; being "already concatenated" I've stored them
; in the reverse order.
TestArray1:
byte $aa,$bb,$cc,$dd,$ee,$ff
- Output:
801D: AA BB CC DD EE FF 23 45 67 89
Zig
There are no hidden memory allocations in Zig.
const std = @import("std");
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
var array1 = [_]u32{ 1, 2, 3, 4, 5 };
var array2 = [_]u32{ 6, 7, 8, 9, 10, 11, 12 };
const slice3 = try std.mem.concat(allocator, u32, &[_][]const u32{ &array1, &array2 });
defer allocator.free(slice3);
// Same result, alternative syntax
const slice4 = try std.mem.concat(allocator, u32, &[_][]const u32{ array1[0..], array2[0..] });
defer allocator.free(slice4);
std.debug.print(
"Array 1: {any}\nArray 2: {any}\nSlice 3: {any}\nSlice 4: {any}\n",
.{ array1, array2, slice3, slice4 },
);
}
- Output:
Array 1: { 1, 2, 3, 4, 5 } Array 2: { 6, 7, 8, 9, 10, 11, 12 } Slice 3: { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 } Slice 4: { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }
zkl
Lists (both mutable and read only), no built in support for numeric vectors/arrays/matrices
T(1,2).extend(T(4,5,6)) //-->L(1,2,4,5,6)
T(1,2).extend(4,5,6) //-->L(1,2,4,5,6)
zonnon
module Main;
import
System.Collections.ArrayList as Array,
System.Console as Console;
type
Vector = array {math} * of integer;
procedure Concat(x,y: Vector): Vector;
var
i,k: integer;
res: Vector;
begin
res := new Vector(len(x) + len(y));
k := 0;
for i := 0 to len(x) - 1 do
res[k] := x[i];inc(k)
end;
for i := 0 to len(y) - 1 do
res[k] := y[i];inc(k)
end;
return res
end Concat;
procedure Concat2(x,y: Array): Array;
var
i: integer;
res: Array;
begin
res := new Array(x.Count + y.Count);
for i := 0 to x.Count - 1 do
res.Add(x[i]);
end;
for i := 0 to y.Count - 1 do
res.Add(y[i]);
end;
return res
end Concat2;
procedure WriteVec(x: Vector);
var
i: integer;
begin
for i := 0 to len(x) - 1 do;
write(x[i]:3)
end;
writeln;
end WriteVec;
procedure WriteAry(x: Array);
var
i: integer;
begin
for i := 0 to x.Count - 1 do;
Console.Write("{0,3}",x[i])
end;
writeln;
end WriteAry;
var
a,b: Vector;
x,y: Array;
begin
a := [1,2,3,4];
b := [6,7,8,9];
WriteVec(Concat(a,b));
x := new Array(4);
y := new Array(4);
x.Add(2);x.Add(4);x.Add(6);x.Add(8);
y.Add(3);y.Add(5);y.Add(9);y.Add(11);
WriteAry(Concat2(x,y));
end Main.
- Output:
1 2 3 4 6 7 8 9 2 4 6 8 3 5 9 11
Zsh
Concatenating arrays.
a=(1 2 3)
b=(a b c)
c=($a $b)
Pushing a single element into an array.
a+=4
Pushing another array into an array.
a+=($b)
ZX Spectrum Basic
10 LET x=10
20 LET y=20
30 DIM a(x)
40 DIM b(y)
50 DIM c(x+y)
60 FOR i=1 TO x
70 LET c(i)=a(i)
80 NEXT i
90 FOR i=1 TO y
100 LET c(x+i)=b(i)
110 NEXT i
120 FOR i=1 TO x+y
130 PRINT c(i);", ";
140 NEXT i
- Simple
- Programming Tasks
- Data Structures
- 11l
- 68000 Assembly
- 8th
- AArch64 Assembly
- ABAP
- ACL2
- Action!
- ActionScript
- Ada
- Aime
- ALGOL 68
- ALGOL W
- Amazing Hopper
- AntLang
- Apex
- APL
- AppleScript
- ARM Assembly
- Arturo
- ATS
- AutoHotkey
- AutoIt
- Avail
- AWK
- Babel
- Bash
- BASIC
- Applesoft BASIC
- Chipmunk Basic
- GW-BASIC
- Minimal BASIC
- MSX Basic
- Quite BASIC
- BaCon
- BBC BASIC
- Commodore BASIC
- Run BASIC
- BASIC256
- Binary Lambda Calculus
- BQN
- Bracmat
- Burlesque
- C
- C sharp
- C++
- Ceylon
- Clojure
- COBOL
- CoffeeScript
- Common Lisp
- Component Pascal
- Crystal
- D
- Delphi
- Diego
- Dyalect
- E
- EasyLang
- EchoLisp
- ECL
- Ecstasy
- Efene
- EGL
- Ela
- Elena
- Elixir
- Elm
- Emacs Lisp
- EMal
- Erlang
- ERRE
- Euphoria
- F Sharp
- Factor
- Fantom
- FBSL
- Forth
- Fortran
- Free Pascal
- FreeBASIC
- Frink
- FunL
- Futhark
- FutureBasic
- Gambas
- GAP
- Genie
- GLSL
- Go
- Gosu
- Groovy
- Haskell
- HicEst
- Hy
- I
- Icon
- Unicon
- IDL
- Idris
- Inform 7
- Insitux
- Ioke
- J
- Jakt
- Java
- JavaScript
- Joy
- Jq
- Julia
- K
- Klingphix
- Klong
- Kotlin
- LabVIEW
- Lambdatalk
- Lang
- Lang5
- Langur
- Lasso
- LDPL
- Ldpl-std
- LFE
- Liberty BASIC
- LIL
- Limbo
- Lingo
- Little
- Logo
- Lua
- M2000 Interpreter
- Maple
- Mathcad
- Mathematica
- Wolfram Language
- MATLAB
- Octave
- Maxima
- Mercury
- Min
- MiniScript
- Nanoquery
- Neko
- Nemerle
- NetRexx
- NewLISP
- Nial
- Nim
- Nu
- Oberon-2
- Objeck
- Objective-C
- OCaml
- Odin
- Oforth
- Onyx
- OoRexx
- Order
- OxygenBasic
- Oz
- PARI/GP
- Pascal
- PascalABC.NET
- Perl
- Phix
- Phix/basics
- Phixmonti
- PHP
- Picat
- PicoLisp
- Pike
- PL/I
- Plain English
- Pony
- PostScript
- Initlib
- PowerShell
- Processing
- Prolog
- PureBasic
- Python
- Q
- QBasic
- QB64
- Quackery
- R
- Racket
- Raku
- RapidQ
- Rapira
- REBOL
- Red
- ReScript
- Retro
- REXX
- Ring
- RLaB
- RPL
- Ruby
- Rust
- S-lang
- SASL
- Scala
- Scheme
- Seed7
- SenseTalk
- SETL
- Sidef
- Simula
- Slate
- Slope
- SmallBASIC
- Smalltalk
- SNOBOL4
- SparForte
- Standard ML
- Stata
- Swift
- Symstatic
- Tailspin
- Tcl
- TI-89 BASIC
- Trith
- Uiua
- UNIX Shell
- Ursa
- Vala
- VBA
- VBScript
- Visual Basic .NET
- V (Vlang)
- Wart
- Wren
- XPL0
- Yabasic
- Yacas
- Yorick
- Z80 Assembly
- Zig
- Zkl
- Zonnon
- Zsh
- ZX Spectrum Basic
- Pages with too many expensive parser function calls