Taskintro
Flatten a nested list
Also called flatten a list of lists, concatenate lists, join lists, flat, flatMap, SelectMany.
Join a list of lists of integers into one list, one level deep, with the items in order.
- Evidence
- Code in 10 languages
Task
Join a list of lists of integers into one list, one level deep. The function flatten(lists) returns the items of the first inner list, then the items of the second inner list, and so on. For example, flatten([[1, 2], [3], [4, 5, 6]]) is [1, 2, 3, 4, 5, 6].
The items are 32-bit signed integers. The outer list and each inner list can be empty. An item is not a list, so the function flattens one level only.
Solutions
| Language | Join the inner lists |
|---|---|
| Python | list(chain.from_iterable(lists)) |
| JavaScript, TypeScript | lists.flat() |
| Java | Arrays.stream(lists).flatMapToInt(Arrays::stream).toArray() |
| C# | lists.SelectMany(xs => xs).ToArray() |
| Go | slices.Concat(lists...) |
| Rust | lists.concat() |
| C | a check of the total length, then memcpy of each list |
| C++ | reserve of the total length, then insert of each list |
| Bash | read -r -a of each argument, then printf of all the items |
- One level.
chain.from_iterableis an "Alternate constructor for chain(). Gets chained inputs from a single iterable argument that is evaluated lazily."1flattakes a depth, which "Defaults to 1."2SelectMany"Projects each element of a sequence to an IEnumerable and flattens the resulting sequences into one sequence."3concat"Flattens a slice of T into a single value Self::Output."4 - A new list. Each solution makes a new list, so a change to the result does not change the input. For Go, "Concat returns a new slice concatenating the passed in slices."5 The Go test also checks this.
- C. The caller gives the array
outand its capacity. The function returns -1 when the items do not fit, and then it writes nothing. - Bash. An array cannot have arrays in it. Thus each argument is one inner list, with the items separated by spaces. The function prints one item on each line.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl.
empty: no inner lists give an empty list. For Go, "If the concatenation is empty, the result is nil."5empty-inner:[[], [1], []]gives[1].all-empty:[[], []]gives an empty list.singleandone-list: one inner list gives a copy of it.negativeandextremes: negative items, -2147483648 and 2147483647 stay in their order.
Pitfalls
- Python the order of the for clauses. The items of a comprehension come from "considering each of the for or if clauses a block, nesting from left to right"6. Thus the outer loop comes first:
[x for xs in lists for x in xs]. With the other order,xsis not defined yet. Also,chain.from_iterableflattens one level only, so[2]stays a list:
from itertools import chain
lists = [[1, 2], [3], [4, 5]]
print([x for xs in lists for x in xs])
try:
print([x for x in xs for xs in lists])
except NameError as e:
print(type(e).__name__, e)
print(list(chain.from_iterable(lists)))
print(list(chain.from_iterable([[1, [2]], [3]])))
[1, 2, 3, 4, 5]
NameError name 'xs' is not defined
[1, 2, 3, 4, 5]
[1, [2], 3]
- JavaScript flat flattens one level. The depth is "The depth level specifying how deep a nested array structure should be flattened. Defaults to 1."2 In the example,
[2, [3]]stays a list afterflat().flat(Infinity)flattens all the levels:
const nested = [[1, [2, [3]]], [4]];
console.log(JSON.stringify(nested.flat()));
console.log(JSON.stringify(nested.flat(Infinity)));
[1,[2,[3]],4]
[1,2,3,4]
- Java map gives a stream of streams.
map(List::stream)gives one item for each inner list, so the count is 2.flatMap"Returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream"7:
import java.util.List;
public class Main {
public static void main(String[] args) {
List<List<Integer>> lists = List.of(List.of(1, 2), List.of(3));
System.out.println(lists.stream().map(List::stream).count());
System.out.println(lists.stream().flatMap(List::stream).toList());
}
}
2
[1, 2, 3]
- C# Select does not flatten.
Select(xs => xs)gives one array for each inner array, so the count is 2.SelectMany"flattens the resulting sequences into one sequence."3
using System;
using System.Linq;
int[][] lists = { new[] { 1, 2 }, new[] { 3 } };
Console.WriteLine(lists.Select(xs => xs).Count());
Console.WriteLine(string.Join(" ", lists.SelectMany(xs => xs)));
2
1 2 3
- Go append to the first list can change it. "If the capacity of s is not large enough to fit the additional values, append allocates a new, sufficiently large underlying array"8. "Otherwise, append re-uses the underlying array."8 In the example,
ahas a capacity of 10, sooutshares its array, andout[0] = 99changesa.slices.Concat"returns a new slice"5:
package main
import (
"fmt"
"slices"
)
func main() {
a := make([]int, 2, 10)
b := []int{3}
out := append(a, b...)
out[0] = 99
fmt.Println(a, out)
a = make([]int, 2, 10)
out = slices.Concat(a, b)
out[0] = 99
fmt.Println(a, out)
}
[99 0] [99 0 3]
[0 0] [99 0 3]
- Rust flatten of iter gives references.
flatten"Creates an iterator that flattens nested structure."9 Butlists.iter()gives references, so the items are&i32.copied"Creates an iterator which copies all of its elements."9concatgives aVec<i32>:
fn main() {
let lists = vec![vec![1, 2], vec![3]];
let refs: Vec<&i32> = lists.iter().flatten().collect();
println!("{refs:?}");
let copies: Vec<i32> = lists.iter().flatten().copied().collect();
println!("{copies:?} {:?}", lists.concat());
}
[1, 2, 3]
[1, 2, 3] [1, 2, 3]
- C the sum of the lengths can wrap around. "Unsigned integer arithmetic is always performed modulo 2n where n is the number of bits in that particular integer."10 In the example,
SIZE_MAX + 2is 1, so a buffer of that size is too small. Compare each length with the room that is left, as the solution does:
#include <stdint.h>
#include <stdio.h>
int main(void) {
size_t a = SIZE_MAX;
size_t b = 2;
// The sum wraps around to 1.
printf("%zu\n", a + b);
// This test does not wrap around: 1 means that a + b does not fit.
printf("%d\n", b > SIZE_MAX - a);
return 0;
}
1
1
- C++ views::join reads the lists in the loop.
views::join"represents view consisting of the sequence obtained from flattening a view of ranges."11 In the example, the change tolists[0][0]after the join shows in the loop. The solution copies the items into a new vector:
#include <iostream>
#include <ranges>
#include <vector>
int main() {
std::vector<std::vector<int>> lists{{1, 2}, {3}};
auto joined = lists | std::views::join;
lists[0][0] = 9;
for (int x : joined) {
std::cout << x << '\n';
}
}
9
2
3
- Bash arrays cannot nest. "Bash provides one-dimensional indexed and associative array variables."12 Thus an item of
listsis a string. Withread -a, "The words are assigned to sequential indices of the array variable aname, starting at 0."12
lists=("1 2" "3")
echo "${#lists[@]} ${lists[0]}"
read -r -a first <<< "${lists[0]}"
echo "${#first[@]} ${first[1]}"
2 1 2
2 2
Related tasks
- Iterate in chunks: split a list into lists of a fixed size, the reverse of this task.
- Group items by a key: split a list into lists by a key.
- Zip two lists: pair the items of two lists.
- Compute the Cartesian product: a nested loop over two lists.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/flatten-a-nested-list/.
from itertools import chain
def flatten(lists: list[list[int]]) -> list[int]:
"""Return the items of the inner lists, one level deep, in order."""
return list(chain.from_iterable(lists))
test_flatten.py 24 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/flatten-a-nested-list/.
import pytest
from flatten import flatten
CASES = {
"three": ([[1, 2], [3], [4, 5, 6]], [1, 2, 3, 4, 5, 6]),
"two": ([[7], [8, 9]], [7, 8, 9]),
"empty": ([], []),
"empty-inner": ([[], [1], []], [1]),
"all-empty": ([[], []], []),
"single": ([[5]], [5]),
"one-list": ([[1, 2, 3]], [1, 2, 3]),
"negative": ([[-1, -2], [3]], [-1, -2, 3]),
"extremes": ([[-2147483648], [2147483647, 0]], [-2147483648, 2147483647, 0]),
}
@pytest.mark.parametrize("name", CASES)
def test_flatten(name):
lists, want = CASES[name]
assert flatten(lists) == want
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/flatten-a-nested-list/.
#include "flatten.hpp"
#include <cstddef>
std::vector<std::int32_t> flatten(const std::vector<std::vector<std::int32_t>> &lists) {
std::size_t total = 0;
for (const auto &xs : lists) {
total += xs.size();
}
std::vector<std::int32_t> out;
out.reserve(total);
for (const auto &xs : lists) {
out.insert(out.end(), xs.begin(), xs.end());
}
return out;
}
flatten.hpp 10 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/flatten-a-nested-list/.
#pragma once
#include <cstdint>
#include <vector>
// flatten returns the items of the inner vectors, one level deep, in order.
std::vector<std::int32_t> flatten(const std::vector<std::vector<std::int32_t>> &lists);
test_flatten.cpp 38 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/flatten-a-nested-list/.
#include "flatten.hpp"
#include <cstdint>
#include <iostream>
#include <string_view>
#include <vector>
static int failures = 0;
using List = std::vector<std::int32_t>;
using Lists = std::vector<List>;
static void check(std::string_view name, const Lists &lists, const List &want) {
if (flatten(lists) != want) {
std::cerr << "case " << name << " failed\n";
failures++;
}
}
int main() {
check("three", Lists{{1, 2}, {3}, {4, 5, 6}}, List{1, 2, 3, 4, 5, 6});
check("two", Lists{{7}, {8, 9}}, List{7, 8, 9});
check("empty", Lists{}, List{});
check("empty-inner", Lists{{}, {1}, {}}, List{1});
check("all-empty", Lists{{}, {}}, List{});
check("single", Lists{{5}}, List{5});
check("one-list", Lists{{1, 2, 3}}, List{1, 2, 3});
check("negative", Lists{{-1, -2}, {3}}, List{-1, -2, 3});
check("extremes", Lists{{INT32_MIN}, {2147483647, 0}}, List{INT32_MIN, 2147483647, 0});
if (failures > 0) {
return 1;
}
std::cout << "all cases pass\n";
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/flatten-a-nested-list/.
import java.util.Arrays;
final class Flatten {
private Flatten() {}
/** Returns the items of the inner arrays, one level deep, in order. */
static int[] flatten(int[][] lists) {
return Arrays.stream(lists).flatMapToInt(Arrays::stream).toArray();
}
}
FlattenTest.java 30 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/flatten-a-nested-list/.
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 FlattenTest {
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("three", new int[][] {new int[] {1, 2}, new int[] {3}, new int[] {4, 5, 6}}, new int[] {1, 2, 3, 4, 5, 6}),
Arguments.of("two", new int[][] {new int[] {7}, new int[] {8, 9}}, new int[] {7, 8, 9}),
Arguments.of("empty", new int[][] {}, new int[] {}),
Arguments.of("empty-inner", new int[][] {new int[] {}, new int[] {1}, new int[] {}}, new int[] {1}),
Arguments.of("all-empty", new int[][] {new int[] {}, new int[] {}}, new int[] {}),
Arguments.of("single", new int[][] {new int[] {5}}, new int[] {5}),
Arguments.of("one-list", new int[][] {new int[] {1, 2, 3}}, new int[] {1, 2, 3}),
Arguments.of("negative", new int[][] {new int[] {-1, -2}, new int[] {3}}, new int[] {-1, -2, 3}),
Arguments.of("extremes", new int[][] {new int[] {Integer.MIN_VALUE}, new int[] {2147483647, 0}}, new int[] {Integer.MIN_VALUE, 2147483647, 0}));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void flatten(String name, int[][] lists, int[] want) {
assertArrayEquals(want, Flatten.flatten(lists), name);
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/flatten-a-nested-list/.
#include "flatten.h"
#include <string.h>
int flatten(const struct int_list *lists, size_t n, int32_t *out, size_t cap, size_t *len) {
size_t total = 0;
for (size_t i = 0; i < n; i++) {
// total + lists[i].len could wrap around, so compare with cap - total.
if (lists[i].len > cap - total) {
return -1;
}
total += lists[i].len;
}
size_t at = 0;
for (size_t i = 0; i < n; i++) {
if (lists[i].len > 0) {
memcpy(out + at, lists[i].items, lists[i].len * sizeof *out);
at += lists[i].len;
}
}
*len = total;
return 0;
}
flatten.h 21 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/flatten-a-nested-list/.
#ifndef FLATTEN_H
#define FLATTEN_H
#include <stddef.h>
#include <stdint.h>
// An int_list is len items at items. items can be NULL when len is 0.
struct int_list {
const int32_t *items;
size_t len;
};
// flatten writes the items of the n lists to out, in order, and stores the
// number of items in *len. It returns 0, or -1 when out has room for fewer
// than all the items. Then it writes nothing.
int flatten(const struct int_list *lists, size_t n, int32_t *out, size_t cap, size_t *len);
#endif
test_flatten.c 64 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/flatten-a-nested-list/.
#include "flatten.h"
#include <stdint.h>
#include <stdio.h>
static int failures = 0;
#define L(...) {__VA_ARGS__}
// An empty list of lists has {NULL, 0} in it, because C has no empty array.
// N and M give the real lengths.
#define CHECK(name, n, given, m, flat) \
do { \
const struct int_list g[] = given; \
const int32_t want[] = flat; \
const size_t want_n = m; \
int32_t out[sizeof want / sizeof want[0]]; \
size_t len = 0; \
int ok = flatten(g, n, out, want_n, &len) == 0 && len == want_n; \
for (size_t i = 0; ok && i < want_n; i++) { \
ok = out[i] == want[i]; \
} \
if (!ok) { \
fprintf(stderr, "case %s failed\n", name); \
failures++; \
} \
} while (0)
int main(void) {
CHECK("three", 3, L({(const int32_t[]){1, 2}, 2}, {(const int32_t[]){3}, 1}, {(const int32_t[]){4, 5, 6}, 3}), 6, L(1, 2, 3, 4, 5, 6));
CHECK("two", 2, L({(const int32_t[]){7}, 1}, {(const int32_t[]){8, 9}, 2}), 3, L(7, 8, 9));
CHECK("empty", 0, L({NULL, 0}), 0, L(0));
CHECK("empty-inner", 3, L({NULL, 0}, {(const int32_t[]){1}, 1}, {NULL, 0}), 1, L(1));
CHECK("all-empty", 2, L({NULL, 0}, {NULL, 0}), 0, L(0));
CHECK("single", 1, L({(const int32_t[]){5}, 1}), 1, L(5));
CHECK("one-list", 1, L({(const int32_t[]){1, 2, 3}, 3}), 3, L(1, 2, 3));
CHECK("negative", 2, L({(const int32_t[]){-1, -2}, 2}, {(const int32_t[]){3}, 1}), 3, L(-1, -2, 3));
CHECK("extremes", 2, L({(const int32_t[]){INT32_MIN}, 1}, {(const int32_t[]){2147483647, 0}, 2}), 3, L(INT32_MIN, 2147483647, 0));
// out has room for 2 items, and there are 3.
const struct int_list three[] = {{(const int32_t[]){1, 2}, 2}, {(const int32_t[]){3}, 1}};
int32_t small[2] = {0, 0};
size_t len = 0;
if (flatten(three, 2, small, 2, &len) != -1 || small[0] != 0) {
fprintf(stderr, "case small failed\n");
failures++;
}
// The sum of the lengths wraps around, so flatten must give -1.
const struct int_list huge[] = {{NULL, SIZE_MAX}, {NULL, 2}};
if (flatten(huge, 2, small, 2, &len) != -1) {
fprintf(stderr, "case wrap failed\n");
failures++;
}
if (failures > 0) {
return 1;
}
printf("all cases pass\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/flatten-a-nested-list/.
using System.Linq;
public static class Flatten
{
// Join returns the items of the inner arrays, one level deep, in order.
public static int[] Join(int[][] lists)
{
return lists.SelectMany(xs => xs).ToArray();
}
}
FlattenTests.cs 28 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/flatten-a-nested-list/.
using Xunit;
public sealed class FlattenTests
{
public static TheoryData<string, int[][], int[]> Cases => new()
{
{ "three", new int[][] { new int[] { 1, 2 }, new int[] { 3 }, new int[] { 4, 5, 6 } }, new int[] { 1, 2, 3, 4, 5, 6 } },
{ "two", new int[][] { new int[] { 7 }, new int[] { 8, 9 } }, new int[] { 7, 8, 9 } },
{ "empty", new int[0][], new int[0] },
{ "empty-inner", new int[][] { new int[0], new int[] { 1 }, new int[0] }, new int[] { 1 } },
{ "all-empty", new int[][] { new int[0], new int[0] }, new int[0] },
{ "single", new int[][] { new int[] { 5 } }, new int[] { 5 } },
{ "one-list", new int[][] { new int[] { 1, 2, 3 } }, new int[] { 1, 2, 3 } },
{ "negative", new int[][] { new int[] { -1, -2 }, new int[] { 3 } }, new int[] { -1, -2, 3 } },
{ "extremes", new int[][] { new int[] { int.MinValue }, new int[] { 2147483647, 0 } }, new int[] { int.MinValue, 2147483647, 0 } },
};
[Theory]
[MemberData(nameof(Cases))]
public void Check(string name, int[][] lists, int[] want)
{
Assert.NotNull(name);
Assert.Equal(want, Flatten.Join(lists));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/flatten-a-nested-list/.
/**
* @param {number[][]} lists
* @returns {number[]}
*/
export function flatten(lists) {
// flat() with no argument flattens one level.
return lists.flat();
}
flatten.test.js 25 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/flatten-a-nested-list/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { flatten } from "./flatten.js";
const cases = [
["three", [[1, 2], [3], [4, 5, 6]], [1, 2, 3, 4, 5, 6]],
["two", [[7], [8, 9]], [7, 8, 9]],
["empty", [], []],
["empty-inner", [[], [1], []], [1]],
["all-empty", [[], []], []],
["single", [[5]], [5]],
["one-list", [[1, 2, 3]], [1, 2, 3]],
["negative", [[-1, -2], [3]], [-1, -2, 3]],
["extremes", [[-2147483648], [2147483647, 0]], [-2147483648, 2147483647, 0]],
];
for (const [name, lists, want] of cases) {
test(name, () => {
assert.deepEqual(flatten(lists), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/flatten-a-nested-list/.
export function flatten(lists: readonly (readonly number[])[]): number[] {
// flat() with no argument flattens one level.
return lists.flat();
}
flatten.test.ts 25 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/flatten-a-nested-list/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { flatten } from "./flatten.ts";
const cases: [string, number[][], number[]][] = [
["three", [[1, 2], [3], [4, 5, 6]], [1, 2, 3, 4, 5, 6]],
["two", [[7], [8, 9]], [7, 8, 9]],
["empty", [], []],
["empty-inner", [[], [1], []], [1]],
["all-empty", [[], []], []],
["single", [[5]], [5]],
["one-list", [[1, 2, 3]], [1, 2, 3]],
["negative", [[-1, -2], [3]], [-1, -2, 3]],
["extremes", [[-2147483648], [2147483647, 0]], [-2147483648, 2147483647, 0]],
];
for (const [name, lists, want] of cases) {
test(name, () => {
assert.deepEqual(flatten(lists), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/flatten-a-nested-list/.
// Package flatten joins a list of lists into one list.
package flatten
import "slices"
// Flatten returns a new slice with the items of the inner slices, in order.
func Flatten(lists [][]int32) []int32 {
return slices.Concat(lists...)
}
flatten_test.go 43 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/flatten-a-nested-list/.
package flatten
import (
"math"
"slices"
"testing"
)
var cases = []struct {
name string
lists [][]int32
want []int32
}{
{"three", [][]int32{[]int32{1, 2}, []int32{3}, []int32{4, 5, 6}}, []int32{1, 2, 3, 4, 5, 6}},
{"two", [][]int32{[]int32{7}, []int32{8, 9}}, []int32{7, 8, 9}},
{"empty", [][]int32{}, []int32{}},
{"empty-inner", [][]int32{[]int32{}, []int32{1}, []int32{}}, []int32{1}},
{"all-empty", [][]int32{[]int32{}, []int32{}}, []int32{}},
{"single", [][]int32{[]int32{5}}, []int32{5}},
{"one-list", [][]int32{[]int32{1, 2, 3}}, []int32{1, 2, 3}},
{"negative", [][]int32{[]int32{-1, -2}, []int32{3}}, []int32{-1, -2, 3}},
{"extremes", [][]int32{[]int32{math.MinInt32}, []int32{2147483647, 0}}, []int32{math.MinInt32, 2147483647, 0}},
}
func TestFlatten(t *testing.T) {
for _, c := range cases {
if got := Flatten(c.lists); !slices.Equal(got, c.want) {
t.Errorf("%s: got %v, want %v", c.name, got, c.want)
}
}
}
func TestFlattenCopies(t *testing.T) {
a := make([]int32, 2, 10)
got := Flatten([][]int32{a, {3}})
got[0] = 99
if a[0] != 0 {
t.Errorf("a change to the result changed the input: %v", a)
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/flatten-a-nested-list/.
/// Returns a new vector with the items of the inner vectors, in order.
pub fn flatten(lists: &[Vec<i32>]) -> Vec<i32> {
lists.concat()
}
tests/flatten_test.rs 22 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/flatten-a-nested-list/.
use algo_flatten_a_nested_list::flatten;
#[test]
fn cases() {
let cases: Vec<(&str, Vec<Vec<i32>>, Vec<i32>)> = vec![
("three", vec![vec![1, 2], vec![3], vec![4, 5, 6]], vec![1, 2, 3, 4, 5, 6]),
("two", vec![vec![7], vec![8, 9]], vec![7, 8, 9]),
("empty", Vec::<Vec<i32>>::new(), Vec::<i32>::new()),
("empty-inner", vec![Vec::<i32>::new(), vec![1], Vec::<i32>::new()], vec![1]),
("all-empty", vec![Vec::<i32>::new(), Vec::<i32>::new()], Vec::<i32>::new()),
("single", vec![vec![5]], vec![5]),
("one-list", vec![vec![1, 2, 3]], vec![1, 2, 3]),
("negative", vec![vec![-1, -2], vec![3]], vec![-1, -2, 3]),
("extremes", vec![vec![i32::MIN], vec![2147483647, 0]], vec![i32::MIN, 2147483647, 0]),
];
for (name, lists, want) in cases {
assert_eq!(flatten(&lists), want, "{name}");
}
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/flatten-a-nested-list/.
# flatten LIST...
# Each argument is one inner list, with the items separated by spaces. Prints
# the items of all the lists, one on each line, in order.
flatten() {
local list
local -a items out=()
for list in "$@"; do
read -r -a items <<< "$list"
out+=("${items[@]}")
done
if ((${#out[@]} > 0)); then
printf '%s\n' "${out[@]}"
fi
}
test_flatten.bats 29 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/flatten-a-nested-list/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/flatten.sh"
}
check() { # check WANT LIST...
local want got
# %b turns each \n in WANT into a newline. The x keeps the trailing
# newlines, which $(...) removes.
want=$(printf '%b' "$1"; printf x)
shift
got=$(flatten "$@"; printf x)
[ "$got" = "$want" ] || { printf 'got: %q\nwant: %q\n' "$got" "$want"; return 1; }
}
@test "three" { check "1\n2\n3\n4\n5\n6\n" "1 2" "3" "4 5 6"; }
@test "two" { check "7\n8\n9\n" "7" "8 9"; }
@test "empty" { check ""; }
@test "empty-inner" { check "1\n" "" "1" ""; }
@test "all-empty" { check "" "" ""; }
@test "single" { check "5\n" "5"; }
@test "one-list" { check "1\n2\n3\n" "1 2 3"; }
@test "negative" { check "-1\n-2\n3\n" "-1 -2" "3"; }
@test "extremes" { check "-2147483648\n2147483647\n0\n" "-2147483648" "2147483647 0"; }
References
- The Python Standard Library, itertools, chain.from_iterable()
- MDN Web Docs, Array.prototype.flat(), Parameters
- .NET API reference, Enumerable.SelectMany method, Definition
- Rust standard library, primitive type slice, concat
- Go standard library, package slices, func Concat
- The Python Language Reference, Expressions, 6.2.4 Displays for lists, sets and dictionaries
- Java SE 25 API, Interface Stream, flatMap(Function)
- The Go Programming Language Specification, Appending to and copying slices
- Rust standard library, trait Iterator, flatten; copied
- cppreference.com, Arithmetic operators (C), Overflows
- cppreference.com, std::ranges::join_view, Description
- Bash Reference Manual, 6.7 Arrays; 4.2 Bash Builtin Commands (read)
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 HTH996 Edit this page History Report an error Markdown