Taskintro
Concatenate two lists
Also called join two lists, join two arrays, array concatenation, merge two lists, extend a list, combine two lists, append a list to a list.
Make a new list with the items of one list followed by the items of another, or add the second list to the end of the first in place.
- Evidence
- Code in 10 languages
Task
Make a new list with the items of a followed by the items of b. The function concat(a, b) returns the new list, and a and b do not change. For example, concat([1, 2], [3, 4]) is [1, 2, 3, 4], and concat([], [5]) is [5].
Each item is a 32-bit signed integer. The task also shows the in-place form, which adds the items of b to the end of a.
Solutions
| Language | A new list | In place, at the end of a |
|---|---|---|
| Python | a + b |
a.extend(b) or a += b |
| JavaScript, TypeScript | [...a, ...b] or a.concat(b) |
a.push(...b) |
| Java | new ArrayList<>(a), then addAll(b) |
a.addAll(b) |
| C# | [.. a, .. b] or a.Concat(b).ToList() |
a.AddRange(b) |
| Go | slices.Concat(a, b) |
a = append(a, b...) |
| Rust | [a, b].concat() |
a.extend_from_slice(&b) |
| C | malloc and two memcpy calls |
realloc and one memcpy |
| C++ | copy a, then insert(c.end(), b.begin(), b.end()) |
a.insert(a.end(), b.begin(), b.end()) |
| Bash | c=("${a[@]}" "${b[@]}") |
a+=("${b[@]}") |
- Python.
a + bmakes a new list.s += t"extends s with the contents of t"1, so it changes the list in place. - JavaScript.
concat"does not change the existing arrays, but instead returns a new array"2. Spread syntax in an array literal does the same. - Java.
addAllchanges the list it is called on, so the solution copiesainto a newArrayListfirst. - C#.
Concat"is implemented by using deferred execution"3.ToListorToArraymakes the new list at once. - Go.
slices.Concat"returns a new slice concatenating the passed in slices"4.appendcan write into the array ofa(see the pitfalls). - Rust.
extend_from_slicecopies the items ofb.appendmoves them and leavesbempty5. - C.
memcpy"Copies count characters"6, so the count is in bytes:n * sizeof *a. - C++.
insertwith a range copies the items ofbbefore the positiona.end(). - Bash. In double quotes, "${name[@]} expands each element of name to a separate word"7, so each item stays one item.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl.
both-empty,left-emptyandright-empty: an empty list adds nothing.slices.Concatin Go givesnilwhen "the concatenation is empty"4, andnilhas length 0.duplicates: the result keeps equal items from both lists. A concatenation is not a set union.order: the result keeps the order ofaand then the order ofb. It does not sort.limit: the items can be the largest and the smallest 32-bit signed integers.
Pitfalls
- Python += changes the list for every name.
a += bextends the list in place, so another name for the same list sees the change.a = a + bmakes a new list and bindsato it. "Concatenating immutable sequences always results in a new object"8, so a loop that builds a tuple or a string with+copies all of it each time:
a = [1, 2]
alias = a
a += [3]
print(alias)
b = [1, 2]
alias = b
b = b + [3]
print(alias, b)
[1, 2, 3]
[1, 2] [1, 2, 3]
- JavaScript a + b makes a string. The
+operator "first coerces both operands to primitives"9, and "If one side is a string, the other operand is also converted to a string and they are concatenated"9. An array becomes the text of its items with commas:
const a = [1, 2];
const b = [3, 4];
console.log(a + b);
console.log(typeof (a + b));
console.log(a.concat(b), [...a, ...b]);
1,23,4
string
[ 1, 2, 3, 4 ] [ 1, 2, 3, 4 ]
- Java List.of cannot grow. "Calling any mutator method on the List will always cause UnsupportedOperationException to be thrown"10. So
addAllon a list fromList.offails. Copy it into anArrayListfirst:
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> a = List.of(1, 2);
List<Integer> b = List.of(3, 4);
try {
a.addAll(b);
} catch (UnsupportedOperationException e) {
System.out.println("UnsupportedOperationException");
}
List<Integer> c = new ArrayList<>(a);
c.addAll(b);
System.out.println(a + " " + c);
}
}
UnsupportedOperationException
[1, 2] [1, 2, 3, 4]
- C# Concat reads the lists later. "The query represented by this method is not executed until the object is enumerated"3. In the example, the item 9 is added to
aafter the call, and it shows in the lazy result before the items ofb.ToListkeeps the items of the moment:
var a = new List<int> { 1, 2 };
var b = new List<int> { 3 };
var lazy = a.Concat(b);
var now = a.Concat(b).ToList();
a.Add(9);
Console.WriteLine(string.Join(",", lazy));
Console.WriteLine(string.Join(",", now));
1,2,9,3
1,2,3
- Go append can write into a shared array. "If the capacity of s is not large enough to fit the additional values, append allocates a new, sufficiently large underlying array"11. "Otherwise, append re-uses the underlying array"11. In the example,
ahas room for 4 items, so bothappendcalls write to the same array, and the second one changesx.slices.Concatalways makes a new slice:
package main
import (
"fmt"
"slices"
)
func main() {
a := make([]int, 2, 4)
x := append(a, 1)
y := append(a, 2)
fmt.Println(x, y)
p := slices.Concat(a, []int{1})
q := slices.Concat(a, []int{2})
fmt.Println(p, q)
}
[0 0 2] [0 0 2]
[0 0 1] [0 0 2]
- Rust append empties the other vector.
append"Moves all the elements of other into self, leaving other empty"5. Useextend_from_sliceorconcatwhen the code needsbafter the call:
fn main() {
let mut a = vec![1, 2];
let mut b = vec![3, 4];
a.append(&mut b);
println!("{a:?} {b:?}");
let mut c = vec![1, 2];
let d = vec![3, 4];
c.extend_from_slice(&d);
println!("{c:?} {d:?} {:?}", [c.as_slice(), d.as_slice()].concat());
}
[1, 2, 3, 4] []
[1, 2, 3, 4] [3, 4] [1, 2, 3, 4, 3, 4]
- C memcpy counts bytes, not items.
memcpy"Copies count characters"6. A count of 3 copies 3 bytes, which is less than one 4-byteint. The example usescalloc, so the items that the short copy misses are 0. The output is from a little-endian machine with 4-byteint:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
int a[] = {1, 2, 3};
int *wrong = calloc(3, sizeof *wrong);
int *right = calloc(3, sizeof *right);
if (wrong == NULL || right == NULL) {
return 1;
}
memcpy(wrong, a, 3);
memcpy(right, a, 3 * sizeof *a);
printf("%d %d %d\n", wrong[0], wrong[1], wrong[2]);
printf("%d %d %d\n", right[0], right[1], right[2]);
free(wrong);
free(right);
return 0;
}
1 0 0
1 2 3
- C++ insert of a vector into itself is undefined. For the range form of
insert, "If first and last are iterators into *this, the behavior is undefined"12. Soa.insert(a.end(), a.begin(), a.end())is a bug. Copy the vector first:
#include <iostream>
#include <vector>
int main() {
std::vector<int> a{1, 2};
const std::vector<int> copy = a;
a.insert(a.end(), copy.begin(), copy.end());
for (int x : a) {
std::cout << x << " ";
}
std::cout << "size=" << a.size() << "\n";
}
1 2 1 2 size=4
- Bash without quotes splits the items. Without double quotes, an item with a space becomes two items. In the example, the unquoted form gives 4 items, and the quoted form keeps the 3 items:
a=("New York" Paris)
b=(Rome)
c=(${a[@]} ${b[@]})
d=("${a[@]}" "${b[@]}")
echo "${#c[@]} ${#d[@]}"
printf '%s\n' "${d[@]}"
4 3
New York
Paris
Rome
Related tasks
- Append to a list: add one item at the end or at a position.
- Create an array: make an array of a given length.
- Zip two lists: pair the items of two lists.
- Flatten a nested list: join the lists inside a list into one list.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/concatenate-two-lists/.
def concat(a: list[int], b: list[int]) -> list[int]:
"""Return a new list with the items of a, then the items of b."""
# + makes a new list. a += b would change a in place.
return a + b
test_concat.py 25 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/concatenate-two-lists/.
import pytest
from concat import concat
CASES = {
"two-pairs": ([1, 2], [3, 4], [1, 2, 3, 4]),
"uneven": ([5], [6, 7, 8], [5, 6, 7, 8]),
"both-empty": ([], [], []),
"left-empty": ([], [1, 2], [1, 2]),
"right-empty": ([1, 2], [], [1, 2]),
"duplicates": ([1, 1], [1], [1, 1, 1]),
"order": ([3, 1], [2], [3, 1, 2]),
"limit": ([2147483647], [-2147483648], [2147483647, -2147483648]),
}
@pytest.mark.parametrize("name", CASES)
def test_concat(name):
a, b, want = CASES[name]
a0, b0 = list(a), list(b)
assert concat(a, b) == want
assert (a, b) == (a0, b0)
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/concatenate-two-lists/.
#include "concat.hpp"
#include <span>
#include <vector>
std::vector<int> concat(std::span<const int> a, std::span<const int> b) {
std::vector<int> c;
c.reserve(a.size() + b.size());
// insert copies a range. The ranges are not part of c, so the call is safe.
c.insert(c.end(), a.begin(), a.end());
c.insert(c.end(), b.begin(), b.end());
return c;
}
concat.hpp 10 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/concatenate-two-lists/.
#pragma once
#include <span>
#include <vector>
// concat returns a new vector with the items of a, then the items of b.
std::vector<int> concat(std::span<const int> a, std::span<const int> b);
test_concat.cpp 34 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/concatenate-two-lists/.
#include "concat.hpp"
#include <climits>
#include <iostream>
#include <string_view>
#include <vector>
static int failures = 0;
static void check(std::string_view name, const std::vector<int> &a, const std::vector<int> &b, const std::vector<int> &want) {
if (concat(a, b) != want) {
std::cerr << "case " << name << " failed\n";
failures++;
}
}
int main() {
check("two-pairs", std::vector<int>{1, 2}, std::vector<int>{3, 4}, std::vector<int>{1, 2, 3, 4});
check("uneven", std::vector<int>{5}, std::vector<int>{6, 7, 8}, std::vector<int>{5, 6, 7, 8});
check("both-empty", std::vector<int>{}, std::vector<int>{}, std::vector<int>{});
check("left-empty", std::vector<int>{}, std::vector<int>{1, 2}, std::vector<int>{1, 2});
check("right-empty", std::vector<int>{1, 2}, std::vector<int>{}, std::vector<int>{1, 2});
check("duplicates", std::vector<int>{1, 1}, std::vector<int>{1}, std::vector<int>{1, 1, 1});
check("order", std::vector<int>{3, 1}, std::vector<int>{2}, std::vector<int>{3, 1, 2});
check("limit", std::vector<int>{INT_MAX}, std::vector<int>{INT_MIN}, std::vector<int>{INT_MAX, INT_MIN});
if (failures > 0) {
return 1;
}
std::cout << "all cases pass\n";
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/concatenate-two-lists/.
final class Concat {
private Concat() {}
/** Returns a new array with the items of a, then the items of b. */
static int[] concat(int[] a, int[] b) {
// An array cannot grow, so make one of the full length and copy twice.
// For a List, copy a into a new ArrayList and call addAll(b).
int[] c = new int[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
return c;
}
}
ConcatTest.java 33 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/concatenate-two-lists/.
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class ConcatTest {
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("two-pairs", new int[] {1, 2}, new int[] {3, 4}, new int[] {1, 2, 3, 4}),
Arguments.of("uneven", new int[] {5}, new int[] {6, 7, 8}, new int[] {5, 6, 7, 8}),
Arguments.of("both-empty", new int[] {}, new int[] {}, new int[] {}),
Arguments.of("left-empty", new int[] {}, new int[] {1, 2}, new int[] {1, 2}),
Arguments.of("right-empty", new int[] {1, 2}, new int[] {}, new int[] {1, 2}),
Arguments.of("duplicates", new int[] {1, 1}, new int[] {1}, new int[] {1, 1, 1}),
Arguments.of("order", new int[] {3, 1}, new int[] {2}, new int[] {3, 1, 2}),
Arguments.of("limit", new int[] {2147483647}, new int[] {Integer.MIN_VALUE}, new int[] {2147483647, Integer.MIN_VALUE}));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void concat(String name, int[] a, int[] b, int[] want) {
int[] a0 = a.clone();
int[] b0 = b.clone();
assertArrayEquals(want, Concat.concat(a, b));
assertArrayEquals(a0, a);
assertArrayEquals(b0, b);
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/concatenate-two-lists/.
#include "concat.h"
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
int *concat(const int *a, size_t n, const int *b, size_t m) {
if (n > SIZE_MAX / sizeof(int) - m) {
return NULL;
}
size_t k = n + m;
// malloc(0) may return NULL, so ask for at least one item.
int *c = malloc((k > 0 ? k : 1) * sizeof *c);
if (c == NULL) {
return NULL;
}
// memcpy counts bytes, so multiply the counts by the item size.
if (n > 0) {
memcpy(c, a, n * sizeof *a);
}
if (m > 0) {
memcpy(c + n, b, m * sizeof *b);
}
return c;
}
concat.h 13 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/concatenate-two-lists/.
#ifndef CONCAT_H
#define CONCAT_H
#include <stddef.h>
// concat returns a new array with the n items of a, then the m items of b.
// The caller must free it. It returns NULL when the allocation fails.
int *concat(const int *a, size_t n, const int *b, size_t m);
#endif
test_concat.c 47 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/concatenate-two-lists/.
#include "concat.h"
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int failures = 0;
#define L(...) {__VA_ARGS__}
static void check(const char *name, const int *a, size_t n, const int *b, size_t m, const int *want) {
int *c = concat(a, n, b, m);
if (c == NULL || (n + m > 0 && memcmp(c, want, (n + m) * sizeof *c) != 0)) {
fprintf(stderr, "case %s failed\n", name);
failures++;
}
free(c);
}
// C has no empty array, so an empty list is the array {0} with a count of 0.
#define CHECK(name, n, a, m, b, want) \
do { \
const int x[] = a; \
const int y[] = b; \
const int w[] = want; \
check(name, x, n, y, m, w); \
} while (0)
int main(void) {
CHECK("two-pairs", 2, L(1, 2), 2, L(3, 4), L(1, 2, 3, 4));
CHECK("uneven", 1, L(5), 3, L(6, 7, 8), L(5, 6, 7, 8));
CHECK("both-empty", 0, L(0), 0, L(0), L(0));
CHECK("left-empty", 0, L(0), 2, L(1, 2), L(1, 2));
CHECK("right-empty", 2, L(1, 2), 0, L(0), L(1, 2));
CHECK("duplicates", 2, L(1, 1), 1, L(1), L(1, 1, 1));
CHECK("order", 2, L(3, 1), 1, L(2), L(3, 1, 2));
CHECK("limit", 1, L(INT_MAX), 1, L(INT_MIN), L(INT_MAX, INT_MIN));
if (failures > 0) {
return 1;
}
printf("all cases pass\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/concatenate-two-lists/.
public static class ConcatLists
{
// The collection expression copies the items now. a.Concat(b) would read
// the arrays later, when the result is enumerated.
public static int[] Of(int[] a, int[] b) => [.. a, .. b];
}
ConcatListsTests.cs 31 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/concatenate-two-lists/.
using Xunit;
public sealed class ConcatListsTests
{
public static TheoryData<string, int[], int[], int[]> Cases => new()
{
{ "two-pairs", new int[] { 1, 2 }, new int[] { 3, 4 }, new int[] { 1, 2, 3, 4 } },
{ "uneven", new int[] { 5 }, new int[] { 6, 7, 8 }, new int[] { 5, 6, 7, 8 } },
{ "both-empty", new int[0], new int[0], new int[0] },
{ "left-empty", new int[0], new int[] { 1, 2 }, new int[] { 1, 2 } },
{ "right-empty", new int[] { 1, 2 }, new int[0], new int[] { 1, 2 } },
{ "duplicates", new int[] { 1, 1 }, new int[] { 1 }, new int[] { 1, 1, 1 } },
{ "order", new int[] { 3, 1 }, new int[] { 2 }, new int[] { 3, 1, 2 } },
{ "limit", new int[] { 2147483647 }, new int[] { int.MinValue }, new int[] { 2147483647, int.MinValue } },
};
[Theory]
[MemberData(nameof(Cases))]
public void Check(string name, int[] a, int[] b, int[] want)
{
Assert.NotNull(name);
var a0 = (int[])a.Clone();
var b0 = (int[])b.Clone();
Assert.Equal(want, ConcatLists.Of(a, b));
Assert.Equal(a0, a);
Assert.Equal(b0, b);
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/concatenate-two-lists/.
/**
* @param {number[]} a
* @param {number[]} b
* @returns {number[]}
*/
export function concat(a, b) {
// Spread syntax copies the items into a new array. a + b would make a string.
return [...a, ...b];
}
concat.test.js 27 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/concatenate-two-lists/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { concat } from "./concat.js";
const cases = [
["two-pairs", [1, 2], [3, 4], [1, 2, 3, 4]],
["uneven", [5], [6, 7, 8], [5, 6, 7, 8]],
["both-empty", [], [], []],
["left-empty", [], [1, 2], [1, 2]],
["right-empty", [1, 2], [], [1, 2]],
["duplicates", [1, 1], [1], [1, 1, 1]],
["order", [3, 1], [2], [3, 1, 2]],
["limit", [2147483647], [-2147483648], [2147483647, -2147483648]],
];
for (const [name, a, b, want] of cases) {
test(name, () => {
const a0 = [...a];
const b0 = [...b];
assert.deepEqual(concat(a, b), want);
assert.deepEqual([a, b], [a0, b0]);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/concatenate-two-lists/.
export function concat(a: readonly number[], b: readonly number[]): number[] {
// concat returns a new array and does not change a or b.
return a.concat(b);
}
concat.test.ts 27 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/concatenate-two-lists/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { concat } from "./concat.ts";
const cases: [string, number[], number[], number[]][] = [
["two-pairs", [1, 2], [3, 4], [1, 2, 3, 4]],
["uneven", [5], [6, 7, 8], [5, 6, 7, 8]],
["both-empty", [], [], []],
["left-empty", [], [1, 2], [1, 2]],
["right-empty", [1, 2], [], [1, 2]],
["duplicates", [1, 1], [1], [1, 1, 1]],
["order", [3, 1], [2], [3, 1, 2]],
["limit", [2147483647], [-2147483648], [2147483647, -2147483648]],
];
for (const [name, a, b, want] of cases) {
test(name, () => {
const a0 = [...a];
const b0 = [...b];
assert.deepEqual(concat(a, b), want);
assert.deepEqual([a, b], [a0, b0]);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/concatenate-two-lists/.
// Package concatlists joins two slices into a new slice.
package concatlists
import "slices"
// Concat returns a new slice with the items of a, then the items of b. It
// never writes to the array of a, which append(a, b...) can do.
func Concat(a, b []int) []int {
return slices.Concat(a, b)
}
concat_test.go 43 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/concatenate-two-lists/.
package concatlists
import (
"slices"
"testing"
)
var cases = []struct {
name string
a, b []int
want []int
}{
{"two-pairs", []int{1, 2}, []int{3, 4}, []int{1, 2, 3, 4}},
{"uneven", []int{5}, []int{6, 7, 8}, []int{5, 6, 7, 8}},
{"both-empty", []int{}, []int{}, []int{}},
{"left-empty", []int{}, []int{1, 2}, []int{1, 2}},
{"right-empty", []int{1, 2}, []int{}, []int{1, 2}},
{"duplicates", []int{1, 1}, []int{1}, []int{1, 1, 1}},
{"order", []int{3, 1}, []int{2}, []int{3, 1, 2}},
{"limit", []int{2147483647}, []int{-2147483648}, []int{2147483647, -2147483648}},
}
func TestConcat(t *testing.T) {
for _, c := range cases {
a0, b0 := slices.Clone(c.a), slices.Clone(c.b)
if got := Concat(c.a, c.b); !slices.Equal(got, c.want) {
t.Errorf("%s: got %v, want %v", c.name, got, c.want)
}
if !slices.Equal(c.a, a0) || !slices.Equal(c.b, b0) {
t.Errorf("%s: an input changed", c.name)
}
}
// The result must not share the array of a, even when a has room.
a := make([]int, 1, 4)
x := Concat(a, []int{1})
y := Concat(a, []int{2})
if x[1] != 1 || y[1] != 2 {
t.Errorf("shared array: got %v and %v", x, y)
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/concatenate-two-lists/.
/// Returns a new vector with the items of a, then the items of b.
pub fn concat(a: &[i32], b: &[i32]) -> Vec<i32> {
// concat on an array of slices copies the items into a new vector.
[a, b].concat()
}
tests/concat_test.rs 21 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/concatenate-two-lists/.
use algo_concatenate_two_lists::concat;
#[test]
fn cases() {
let cases: &[(&str, &[i32], &[i32], &[i32])] = &[
("two-pairs", &[1, 2], &[3, 4], &[1, 2, 3, 4]),
("uneven", &[5], &[6, 7, 8], &[5, 6, 7, 8]),
("both-empty", &[], &[], &[]),
("left-empty", &[], &[1, 2], &[1, 2]),
("right-empty", &[1, 2], &[], &[1, 2]),
("duplicates", &[1, 1], &[1], &[1, 1, 1]),
("order", &[3, 1], &[2], &[3, 1, 2]),
("limit", &[2147483647], &[i32::MIN], &[2147483647, i32::MIN]),
];
for &(name, a, b, want) in cases {
assert_eq!(concat(a, b), want, "{name}");
}
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/concatenate-two-lists/.
# concat NAME_A NAME_B
# Prints the items of the array NAME_A, then the items of the array NAME_B,
# one on each line. The names are passed, because a function cannot take an
# array as one argument.
concat() {
local -n _concat_a=$1 _concat_b=$2
# The quotes keep each item one word.
local -a _concat_c=("${_concat_a[@]}" "${_concat_b[@]}")
if ((${#_concat_c[@]} > 0)); then printf '%s\n' "${_concat_c[@]}"; fi
}
test_concat.bats 35 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/concatenate-two-lists/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/concat.sh"
}
lines() { # lines ITEM...: prints each item on a line, and nothing for no items
if (($# > 0)); then printf '%s\n' "$@"; fi
}
check() { # check "A ITEMS" "B ITEMS" -- WANT...
local -a left right
read -r -a left <<<"$1"
read -r -a right <<<"$2"
shift 3
local got want
# The x keeps the trailing newlines, which $(...) removes.
got=$(concat left right; printf x)
want=$(lines "$@"; printf x)
[ "$got" = "$want" ] || { printf 'got: %q\nwant: %q\n' "$got" "$want"; return 1; }
}
@test "two-pairs" { check "1 2" "3 4" -- 1 2 3 4; }
@test "uneven" { check "5" "6 7 8" -- 5 6 7 8; }
@test "both-empty" { check "" "" --; }
@test "left-empty" { check "" "1 2" -- 1 2; }
@test "right-empty" { check "1 2" "" -- 1 2; }
@test "duplicates" { check "1 1" "1" -- 1 1 1; }
@test "order" { check "3 1" "2" -- 3 1 2; }
@test "limit" { check "2147483647" "-2147483648" -- 2147483647 -2147483648; }
@test "spaces" { local -a x=("New York" Paris) y=(Rome); got=$(concat x y; printf x); [ "$got" = $'New York\nParis\nRome\nx' ]; }
References
- The Python Standard Library, Built-in Types, Mutable Sequence Types
- MDN Web Docs, Array.prototype.concat(), Description
- .NET API reference, Enumerable.Concat method, Remarks
- Go standard library, package slices, func Concat
- Rust standard library, struct Vec, append
- cppreference.com, memcpy, Description
- Bash Reference Manual, 6.7 Arrays
- The Python Standard Library, Built-in Types, Common Sequence Operations, note 6
- MDN Web Docs, Addition (+), Description
- Java SE 25 API, Interface List, Unmodifiable Lists
- The Go Programming Language Specification, Appending to and copying slices
- cppreference.com, std::vector::insert, Description
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag 726HFA Edit this page History Report an error Markdown