Array concatenation

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.

8th

 [1,2,3] [4,5,6] a:+ .
Output:
[1,2,3,4,5,6]


ABAP

The concept of arrays does not exist in ABAP, instead internal tables are used. This works in ABAP version 7.40 abd 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)

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]

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

listac(list a, list b){    list o;     o.copy(a);    b.ucall(l_append, 1, o);     o;} integermain(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, " ");     return 0;}
Output:
 1 2 3 4 5 6 7 8

ALGOL 68

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


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


AntLang

a:<1; <2; 3>>b: <"Hello"; 42>c: a,b

APL

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

Apex

List<String> listA = new List<String> { 'apple' };List<String> listB = new List<String> { 'banana' };listA.addAll(listB);System.debug(listA); // Prints (apple, banana)

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:

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 lstend concat
Output:
{"alpha", "beta", "gamma", "delta", "epsilon", "zeta", "eta", "theta", "iota"}

AutoHotkey

True Arrays

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

AutoHotkey_Basic does not have real Arrays, but the user can implement them quite easily. For example:

List1 = 1,2,3List2 = 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 +$iUBoundSourceEndFunc   ;==>_ArrayConcatenate 

AWK

#!/usr/bin/awk -fBEGIN {    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

[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" ; done1  23  456

BASIC

BaCon

' Array concatenationOPTION BASE 1 CONST asize = 2CONST bsize = 3DECLARE a[asize] TYPE NUMBERDECLARE b[bsize] TYPE NUMBER ' BaCon has no array concatenation builtin, it will need to be done by handLOCAL c TYPE NUMBER ARRAY asize + bsizeFOR i = 1 TO asize    c[i] = a[i]NEXT FOR i = 1 TO bsize    c[asize + i] = b[i]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=520 DIM A(X) : DIM B(Y) : DIM C(X+Y)30 FOR I=1 TO X40 : A(I) = I50 NEXT60 FOR I=1 TO Y70 : B(I) = I*1080 NEXT90 FOR I=1 TO X100 : C(I) = A(I)110 NEXT120 FOR I=1 TO Y130 : C(X+I) = B(I)140 NEXT150 FOR I=1 TO X+Y160 : PRINT C(I);170 NEXT

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;} // testingconst 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++

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

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

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:

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

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.        environment division.       configuration section.       repository.           function all intrinsic.        data division.       working-storage section.       01 table-one.          05 int-field pic 999 occurs 0 to 5 depending on t1.       01 table-two.          05 int-field pic 9(4) occurs 0 to 10 depending on t2.        77 t1           pic 99.       77 t2           pic 99.        77 show         pic z(4).        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 trim(show) ", " with no advancing           end-perform           move int-field of table-two(tally) to show           display trim(show)       .        end program array-concat.
Output:

Fortran

Works with: Fortran version 90 and later
program Concat_Arraysimplicit 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  write(*,*) c   ! alternative  d = [a, b] ! (/a, b/)  write(*,*) d   deallocate(c)  deallocate(d) end program Concat_Arrays

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 StringConcatArrays(a(), b(), c())For i As Integer = LBound(c) To UBound(c)  Print c(i); " ";NextPrint : PrintPrint "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 

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

Output:

The quick brown fox jumped over the lazy dog


GAP

# Concatenate arraysConcatenation([1, 2, 3], [4, 5, 6], [7, 8, 9]);# [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ] # Append to a variablea := [1, 2, 3];Append(a, [4, 5, 6);Append(a, [7, 8, 9]);a;# [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

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

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

REAL :: a(7), b(3), c(10) c = aDO 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

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

 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

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

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

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

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?

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

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

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

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

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

PowerShell

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

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)  NextEndProcedure  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 + arr2assert 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 += arr5assert arr6 == [7, 8, 9, 4, 5, 6]

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)


RapidQ

 DEFINT A(1 to 4) = {1, 2, 3, 4}DEFINT B(1 to 4) = {10, 20, 30, 40} 'Append array B to array ARedim A(1 to 8) as integerMEMCPY(varptr(A(5)), varptr(B(1)), Sizeof(integer)*4) 

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

Retro

needs array' ^array'new{ 1 2 3 }  ^array'new{ 4 5 6 }  ^array'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 =  10a.2 =  22.7a.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=8fact.1=    1fact.2=    2fact.3=    6fact.4=   24fact.5=  120fact.6=  720fact.7= 5040fact.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=13p.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=' nsay             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 + arr2see arr4see nlarr5 = 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>> 

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

Works with: Gauche 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)) 
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


ZX Spectrum Basic

Translation of: Liberty BASIC
10 LET x=1020 LET y=2030 DIM a(x)40 DIM b(y)50 DIM c(x+y)60 FOR i=1 TO x70 LET c(i)=a(i)80 NEXT i90 FOR i=1 TO y100 LET c(x+i)=b(i)110 NEXT i120 FOR i=1 TO x+y130 PRINT c(i);", ";140 NEXT i `