Array concatenation

From Rosetta Code
Task
Array concatenation
You are encouraged to solve this task according to the task description, using any language you may know.

Show how to concatenate two arrays in your language.

If this is as simple as array1 + array2, so be it.

ACL2[edit]

This is for lists, not arrays; ACL2's array support is limited.

(append xs ys)

ActionScript[edit]

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[edit]

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)

ALGOL 68[edit]

Works with: ALGOL 68 version Standard - no extensions to language used
Works with: ALGOL 68G version Any - tested with release 1.18.0-9h.tiny

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

APL[edit]

 
1 2 3 , 4 5 6
1 2 3 4 5 6
 

AppleScript[edit]

 
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:

Translation of: JavaScript
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"}

AutoHotkey[edit]

True Arrays[edit]

Works with: AutoHotkey_L
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[edit]

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[edit]

_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
 

AWK[edit]

#!/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) {
for (i in a) {
c[++nc]=a[i]
}
for (i in b) {
c[++nc]=b[i]
}
}

Babel[edit]

[1 2 3] [4 5 6] cat ;
Output:
[val 0x1 0x2 0x3 0x4 0x5 0x6 ]

bash[edit]

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

BBC BASIC[edit]

      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

Bracmat[edit]

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[edit]

 
blsq ) {1 2 3}{4 5 6}_+
{1 2 3 4 5 6}
 

C[edit]

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++[edit]

#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";
}
Works with: C++11

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;
}

C#[edit]

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:

Works with: C# version 3
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();
}
}

Ceylon[edit]

shared void arrayConcatenation() {
value a = Array {1, 2, 3};
value b = Array {4, 5, 6};
value c = concatenate(a, b);
print(c);
}

Clojure[edit]

(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])

CoffeeScript[edit]

 
# like in JavaScript
a = [1, 2, 3]
b = [4, 5, 6]
c = a.concat b
 

Common Lisp[edit]

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)

Component Pascal[edit]

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]

D[edit]

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[edit]

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;

E[edit]

? [1,2] + [3,4]
# value: [1, 2, 3, 4]

EchoLisp[edit]

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[edit]

 
A := [1, 2, 3, 4];
B := [5, 6, 7, 8];
 
C := A + B;

Efene[edit]

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[edit]

Works with: EDT
 
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[edit]

xs = [1,2,3]
ys = [4,5,6]
xs ++ ys
Output:
[1,2,3,4,5,6]

Elena[edit]

#define system.
#define extensions.
 
#symbol program =
[
#var a := (1,2,3).
#var b := (4,5).
 
console writeLine:"(":a:") + (":b:") = (":(a + b):")".
].

Elixir[edit]

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[edit]

import Array exposing (Array, append, initialize)
import Graphics.Element exposing (Element, show)
 
 
xs : Array Int
xs =
initialize 3 identity -- [0, 1, 2]
 
 
ys : Array Int
ys =
initialize 3 <| (+) 3 -- [3, 4, 5]
 
 
main : Element
main =
show <| append xs ys
-- Array.fromList [0,1,2,3,4,5]

Emacs Lisp[edit]

See Scheme

Erlang[edit]

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[edit]

 
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[edit]

sequence s1,s2,s3
s1 = {1,2,3}
s2 = {4,5,6}
s3 = s1 & s2
? s3
Output:
{1,2,3,4,5,6}

F#[edit]

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

FBSL[edit]

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...

Factor[edit]

append

Example:

( scratchpad ) USE: sequences
( scratchpad ) { 1 2 } { 3 4 } append .
{ 1 2 3 4 }

Fantom[edit]

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.

Forth[edit]

: $!+   ( 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[edit]

Works with: Fortran version 90 and later
program Concat_Arrays
implicit none
 
integer, dimension(3) :: a = [ 1, 2, 3 ]
integer, dimension(3) :: b = [ 4, 5, 6 ]
integer, dimension(:), allocatable :: c
 
allocate(c(size(a)+size(b)))
c(1:size(a)) = a
c(size(a)+1:size(a)+size(b)) = b
 
write(*,*) c
 
end program Concat_Arrays
Works with: Fortran version 2003 and later
program Concat_Arrays
implicit none
 
integer, dimension(3) :: a = [ 1, 2, 3 ]
integer, dimension(3) :: b = [ 4, 5, 6 ]
integer, dimension(:), allocatable :: c
 
c = [a, b]
 
write(*,*) c
 
end program Concat_Arrays

Frink[edit]

 
a = [1,2]
b = [3,4]
a.pushAll[b]
 

FunL[edit]

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)

GAP[edit]

# 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 ]

Go[edit]

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[edit]

 
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[edit]

Solution:

def list = [1, 2, 3] + ["Crosby", "Stills", "Nash", "Young"]

Test:

println list
Output:
[1, 2, 3, Crosby, Stills, Nash, Young]

Haskell[edit]

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.

HicEst[edit]

REAL :: a(7), b(3), c(10)
 
c = a
DO i = 1, LEN(b)
c(i + LEN(a)) = b(i)
ENDDO

Icon and Unicon[edit]

Both languages have list concatenation built in. Lists are fully dynamic arrays which can be truncated or extended at either end.

 
procedure main()
L1 := [1, 2, 3, 4]
L2 := [11, 12, 13, 14]
L3 := L1 ||| L2
 
sep := ""
every writes(sep, !L3) do
sep := ", "
write()
end
 

IDL[edit]

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".

Inform 7[edit]

let A be {1, 2, 3};
let B be {4, 5, 6};
add B to A;

Ioke[edit]

iik> [1,2,3] + [3,2,1]
[1,2,3] + [3,2,1]
+> [1, 2, 3, 3, 2, 1]

J[edit]

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

Java[edit]

From [1]:

public static Object[] objArrayConcat(Object[] o1, Object[] o2)
{
Object[] ret = new Object[o1.length + o2.length];
 
System.arraycopy(o1, 0, ret, 0, o1.length);
System.arraycopy(o2, 0, ret, o1.length, o2.length);
 
return ret;
}

Or with Collections simply call addAll:

Collection list1, list2, list1And2;
//...list1 and list2 are instantiated...
list1And2 = new ArrayList(list1); //or any other Collection you want
list1And2.addAll(list2);

JavaScript[edit]

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:

Translation of: Haskell

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"]

jq[edit]

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 flatten filter is available in recent versions of jq. If your jq does not have flatten, then the task can be accomplished by:

   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 "+".
[1,2] + [3] + [null] # => [1,2,3,null]
 
[range(1;3), 3, null] # => [1,2,3,null]
 

Julia[edit]

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[edit]

 
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")

Kotlin[edit]

There is no operator or standard library function for concatenating Array types. One option is to convert to Collections, concatenate, and convert back:

val a : Array<T> = // initialise a
val b : Array<T> = // initialise b
val c = (a.toList() + b.toList()).copyToArray()

Alternatively, we can write our own concatenation function:

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]})

When working directly with Collections, we can simply use the + operator:

val a : Collection<T> // initialise a
val b : Collection<T> = // initialise b
val c : Collection = a + b

LabVIEW[edit]

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.
LabVIEW Array concatenation.png

Lang5[edit]

[1 2] [3 4] append collapse .


Lasso[edit]

 
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)

LFE[edit]

 
> (++ '(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[edit]

    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

Little[edit]

void main() {
int a[] = {0, 1, 2, 3, 4};
int b[] = {5, 6, 7, 8, 9};
int c[] = {(expand)a, (expand)b};
puts(c);
}

[edit]

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[edit]

a = {1,2,3}
b = {4,5,6}
table.foreach(b,function(i,v)table.insert(a,v)end)
for i,v in next,a do io.write (v..' ') end

Maple[edit]

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]
 

Mathematica / Wolfram Language[edit]

Join[{1,2,3}, {4,5,6}]
 
-> {1, 2, 3, 4, 5, 6}

MATLAB / Octave[edit]

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]
 
a =
 
1 2 3
 
>> b = [4 5 6]
 
b =
 
4 5 6
 
>> concat = [a b]
 
concat =
 
1 2 3 4 5 6
 
>> concat = [a;b]
 
concat =
 
1 2 3
4 5 6

For multi-dimensional arrays, there is also the function cat():

>> c = randn([3,4,5]);
>> d = randn([3,4,7]);
>> e = cat(3,c,d);
>> size(e)
ans =
 
3 4 12
 
 

Maxima[edit]

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[edit]

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?

Nemerle[edit]

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[edit]

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[edit]

; 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))

Nim[edit]

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

Oberon-2[edit]

 
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[edit]

 
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[edit]

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[edit]

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|]

Oforth[edit]

[1, 2, 3 ] [ 4, 5, 6, 7 ] + 

Onyx[edit]

# 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[edit]

 
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 "

Order[edit]

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[edit]

 
'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[edit]

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[edit]

concat(u,v)

Pascal[edit]

See Delphi

Perl[edit]

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"

Perl 6[edit]

Works with: rakudo version 2015-10-01
# the prefix:<|> operator (called "slip") can be used to interpolate arrays into a list:
sub cat-arrays(@a, @b) {
|@a, |@b
}
 
my @a1 = (1,2,3);
my @a2 = (2,3,4);
cat-arrays(@a1,@a2).join(", ").say;
Output:
1, 2, 3, 2, 3, 4

Phix[edit]

sequence s1 = {1,2,3}, s2 = {4,5,6}
? s1 & s2
Output:
 {1,2,3,4,5,6}

PHP[edit]

$arr1 = array(1, 2, 3);
$arr2 = array(4, 5, 6);
$arr3 = array_merge($arr1, $arr2);

PicoLisp[edit]

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

PL/I[edit]

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
 
 

PostScript[edit]

Library: initlib
 
[1 2 3 4] [5 6 7 8] concat
 

PowerShell[edit]

$a = 1,2,3
$b = 4,5,6
 
$c = $a + $b
Write-Host $c

Prolog[edit]

 
?- append([1,2,3],[4,5,6],R).
R = [1, 2, 3, 4, 5, 6].
 

PureBasic[edit]

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[edit]

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]

R[edit]

 
a1 <- c(1, 2, 3)
a2 <- c(3, 4, 5)
a3 <- c(a1, a2)
 

Racket[edit]

 
(vector-append #(1 2 3 4) #(5 6 7) #(8 9 10))
 
Output:
'#(1 2 3 4 5 6 7 8 9 10)

RapidQ[edit]

 
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)
 

REBOL[edit]

 
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]]
 

Retro[edit]

needs array'
 
^array'new{ 1 2 3 } ^array'new{ 4 5 6 } ^array'append

REXX[edit]

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[edit]

 
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[edit]

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
>>
 

Ruby[edit]

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[edit]

fn main() {
let a_vec: Vec<i32> = vec![1, 2, 3, 4, 5];
let b_vec: Vec<i32> = vec![6; 5];
 
let c_vec = concatenate_arrays::<i32>(a_vec.as_slice(), b_vec.as_slice());
 
println!("{:?} ~ {:?} => {:?}", a_vec, b_vec, c_vec);
}
 
fn concatenate_arrays<T: Clone>(x: &[T], y: &[T]) -> Vec<T> {
let mut concat: Vec<T> = vec![x[0].clone(); x.len()];
 
concat.clone_from_slice(x);
concat.extend_from_slice(y);
 
concat
}
 

Scala[edit]

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[edit]

; 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.

Seed7[edit]

$ 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

SETL[edit]

A := [1, 2, 3];
B := [3, 4, 5];
print(A + B); -- [1 2 3 3 4 5]

Sidef[edit]

var arr1 = [1, 2, 3];
var arr2 = [4, 5, 6];
var arr3 = (arr1 + arr2); # => [1, 2, 3, 4, 5, 6]

Slate[edit]

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}
 

Smalltalk[edit]

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[edit]

Works with: Macro Spitbol
Works with: Snobol4+
Works with: CSnobol
*       # 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

Standard ML[edit]

 
val l1 = [1,2,3,4];;
val l2 = [5,6,7,8];;
val l3 = l1 @ l2 (* [1,2,3,4,5,6,7,8] *)
 

Swift[edit]

let array1 = [1,2,3]
let array2 = [4,5,6]
let array3 = array1 + array2

Tcl[edit]

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[edit]

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[edit]

[1 2 3] [4 5 6] concat

UNIX Shell[edit]

Using proper built-in Bash arrays:

Works with: bash
array1=( 1 2 3 4 5 )
array2=( 6 7 8 9 10 )
botharrays=( ${array1[@]} ${array2[@]} )

Whitespace-delimited strings work in much the same way:

Works with: bash
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"

Vala[edit]

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);
}
}

VBScript[edit]

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[edit]

 
Dim iArray1() As Integer = {1, 2, 3}
Dim iArray2() As Integer = {4, 5, 6}
Dim iArray3() As Integer = Nothing
 
iArray3 = iArray1.Concat(iArray2).ToArray
 

Wart[edit]

Wart doesn't have arrays yet, just lists.

a <- '(1 2 3)
b <- '(4 5 6)
a+b
# => (1 2 3 4 5 6)

Yacas[edit]

Concat({1,2,3}, {4,5,6})
 
Out> {1, 2, 3, 4, 5, 6}

Yorick[edit]

a = [1,2,3];
b = [4,5,6];
ab = grow(a, b);

zkl[edit]

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)

Zsh[edit]

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)