Programming Search⌘K

Taskintro

Take the first n items

Also called take n items, first n elements, head of a list, limit a sequence, take from an infinite sequence, prefix of a list.

Copy the first n items of a list, where a shorter list gives all its items, and take the first n items of an infinite lazy sequence.

Task

Take the first n items of a list of integers. The function take(items, n) returns them as a new list, in input order. If the list has fewer than n items, the result is the whole list, and n = 0 gives an empty list. For example, take([1, 2, 3, 4, 5], 3) is [1, 2, 3] and take([1, 2], 5) is [1, 2].

The second function, take_naturals(start, n), takes the first n items of the infinite sequence start, start + 1, start + 2, and so on. A program cannot make this sequence as a list, because the list has no end. Each solution makes the sequence lazily, so that it gives one value each time the program asks for one, and then takes n values from it. For example, take_naturals(10, 3) is [10, 11, 12].

Solutions

Language take take_naturals
Python items[:n] list(islice(count(start), n))
JavaScript items.slice(0, n) a generator with take(n) and toArray()
TypeScript items.slice(0, n) a generator and a for loop with break
Java Arrays.copyOf(items, Math.min(n, items.length)) IntStream.iterate(start, i -> i + 1).limit(n)
C# items.Take(n).ToArray() a yield return method with Take(n)
Go slices.Clone(items[:min(n, len(items))]) an iter.Seq[int] and a range loop with break
Rust items.iter().take(n).copied().collect() (start..).take(n).collect()
C memcpy of the smaller of n and the length a struct that holds the next value
C++ `items std::views::take(n)`
Bash "${@:1:n}" a loop without end, piped to head -n "$n"
  • The infinite sequence. Python count makes "an iterator that returns evenly spaced values beginning with start"1, and islice reads only n values from it. JavaScript take "returns a new iterator helper object that yields the given number of elements in this iterator and then terminates."2 Java limit gives "the elements of this stream, truncated to be no longer than maxSize in length"3. Rust says that "take() is often used with an infinite iterator, to make it finite"4. The C++ take view represents a "view of the elements from an underlying sequence, starting at the beginning and ending at a given bound."5
  • Go. An iter.Seq is a function that calls yield for each value. The function "stops either when the sequence is finished or when yield returns false, indicating to stop the iteration early."6 A break in the range loop makes yield return false.
  • C#. Take "Returns a specified number of contiguous elements from the start of a sequence."7 The iterator method with yield return runs only up to the value that Take asks for.
  • C. C has no lazy sequence in its library. The struct naturals holds only the next value, and the function naturals_next returns it and adds 1. The caller asks for n values and no more.
  • Bash. head -n prints "the first num lines"8 and then exits. The loop of naturals then writes to a closed pipe, so it stops. A function that prints the items one on each line is the Bash form of a list.
  • A copy. Each take returns a new list. A change to the result does not change the input, and the tests check this.

Edge cases

The cases are in cases/basic.jsonl, cases/edge.jsonl and cases/infinite.jsonl.

  • zero: n = 0 gives an empty list, also from the infinite sequence (none).
  • empty: an empty list gives an empty list for each n.
  • more-than-length: take([1, 2], 5) is [1, 2]. The function does not fail and does not add values.
  • equal-length: take([4, 5, 6], 3) is the whole list.
  • negative and extremes: negative items, -2147483648 and 2147483647 come through unchanged.
  • large-start: take_naturals(999998, 2) is [999998, 999999]. The contract keeps start + n at 1000000 or less, so no value overflows a 32-bit integer.

Pitfalls

  • Python a second take from the same iterator gives other items. islice reads items from the iterator, and they are then gone. "If the input is an iterator, then fully consuming the islice advances the input iterator by max(start, stop) steps regardless of the step value."1 A slice of a list does not change the list:
from itertools import count, islice

numbers = count(1)
print(list(islice(numbers, 3)))
print(list(islice(numbers, 3)))

items = [1, 2, 3, 4, 5, 6]
print(items[:3], items[:3])
Output
[1, 2, 3]
[4, 5, 6]
[1, 2, 3] [1, 2, 3]
  • JavaScript a negative n takes from the end. For the end of slice, MDN says: "Negative index counts back from the end of the array"9. A count that a program computes, and that goes below 0 by mistake, gives a wrong list and no error. Check that n is at least 0:
const items = [1, 2, 3, 4, 5];
console.log(items.slice(0, 2));
console.log(items.slice(0, -2));
Output
[ 1, 2 ]
[ 1, 2, 3 ]
  • Java copyOf pads a short array. Arrays.copyOf copies "the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length."10 With n larger than the length, the result has zeros at the end. Use the smaller of n and the length:
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] items = {1, 2};
        System.out.println(Arrays.toString(Arrays.copyOf(items, 5)));
        System.out.println(Arrays.toString(Arrays.copyOf(items, Math.min(5, items.length))));
    }
}
Output
[1, 2, 0, 0, 0]
[1, 2]
  • C# Take is deferred. "This method is implemented by using deferred execution."7 The query reads the list when the program enumerates it, not when the program calls Take. A change to the list between the two changes the result. Call ToArray or ToList to take the items at once:
var items = new List<int> { 1, 2, 3 };
var deferred = items.Take(2);
var now = items.Take(2).ToArray();
items.Insert(0, 99);
Console.WriteLine(string.Join(", ", deferred));
Console.WriteLine(string.Join(", ", now));
Output
99, 1
1, 2
  • Bash head and pipefail. When head exits, the command before it in the pipeline gets a write error or a signal, and it exits with a status that is not zero. "If pipefail is enabled, the pipeline’s return status is the value of the last (rightmost) command to exit with a non-zero status"11. A script with set -o pipefail then sees a failure, although the result is correct:
#!/usr/bin/env bash
set -o pipefail
seq 1 100000 | head -n 2
echo "status $?"
Output
1
2
status 141

Bash says: "When a command terminates on a fatal signal whose number is N, Bash uses the value 128+N as the exit status."11 On Linux, SIGPIPE is signal 1312, so the status is 141. Do not use set -o pipefail around a pipeline that ends in head, or accept the status 141 from it.

Code

The build runs the native tests of each language in a pinned toolchain.

take.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/take-the-first-n-items/.

from itertools import count, islice


def take(items: list[int], n: int) -> list[int]:
    """Return a copy of the first n items; a shorter list gives all its items."""
    # A slice stops at the end of the list, so n can be larger than len(items).
    return items[:n]


def take_naturals(start: int, n: int) -> list[int]:
    """Return the first n items of the infinite sequence start, start + 1, ..."""
    # count is infinite and lazy; islice reads only n items from it.
    return list(islice(count(start), n))
test_take.py 45 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/take-the-first-n-items/.

import pytest

from take import take, take_naturals

CASES = {
    "first-three": ([1, 2, 3, 4, 5], 3, [1, 2, 3]),
    "first-two": ([10, 20, 30, 40], 2, [10, 20]),
    "zero": ([1, 2], 0, []),
    "empty": ([], 3, []),
    "more-than-length": ([1, 2], 5, [1, 2]),
    "equal-length": ([4, 5, 6], 3, [4, 5, 6]),
    "one": ([9, 8], 1, [9]),
    "negative": ([-1, -2, -3], 2, [-1, -2]),
    "extremes": ([-2147483648, 2147483647, 0], 2, [-2147483648, 2147483647]),
}

INFINITE = {
    "from-zero": (0, 5, [0, 1, 2, 3, 4]),
    "from-ten": (10, 3, [10, 11, 12]),
    "none": (7, 0, []),
    "one": (0, 1, [0]),
    "large-start": (999998, 2, [999998, 999999]),
}


@pytest.mark.parametrize("name", CASES)
def test_take(name):
    items, n, want = CASES[name]
    assert take(items, n) == want


@pytest.mark.parametrize("name", INFINITE)
def test_take_naturals(name):
    start, n, want = INFINITE[name]
    assert take_naturals(start, n) == want


def test_take_returns_a_copy():
    items = [1, 2, 3]
    first = take(items, 2)
    first.append(99)
    assert items == [1, 2, 3]
take.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/take-the-first-n-items/.

#include "take.hpp"

#include <ranges>

std::vector<int> take(std::span<const int> items, std::size_t n) {
    // views::take stops at the end of the span, so n can be larger than the size.
    auto first = items | std::views::take(n);
    return std::vector<int>(first.begin(), first.end());
}

std::vector<int> take_naturals(int start, std::size_t n) {
    std::vector<int> out;
    // views::iota(start) has no end; views::take reads only n values from it.
    for (int i : std::views::iota(start) | std::views::take(n)) {
        out.push_back(i);
    }
    return out;
}
take.hpp 15 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/take-the-first-n-items/.

#pragma once

#include <cstddef>
#include <span>
#include <vector>

// take returns a copy of the first n items; a shorter span gives all its items.
std::vector<int> take(std::span<const int> items, std::size_t n);

// take_naturals returns the first n items of the infinite sequence start,
// start + 1, ...
std::vector<int> take_naturals(int start, std::size_t n);
test_take.cpp 42 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/take-the-first-n-items/.

#include "take.hpp"

#include <cstddef>
#include <iostream>
#include <string_view>
#include <vector>

static int failures = 0;

using Ints = std::vector<int>;

static void check(std::string_view name, const Ints &got, const Ints &want) {
    if (got != want) {
        std::cerr << "case " << name << " failed\n";
        failures++;
    }
}

int main() {
    check("first-three", take(Ints{1, 2, 3, 4, 5}, 3), Ints{1, 2, 3});
    check("first-two", take(Ints{10, 20, 30, 40}, 2), Ints{10, 20});
    check("zero", take(Ints{1, 2}, 0), Ints{});
    check("empty", take(Ints{}, 3), Ints{});
    check("more-than-length", take(Ints{1, 2}, 5), Ints{1, 2});
    check("equal-length", take(Ints{4, 5, 6}, 3), Ints{4, 5, 6});
    check("one", take(Ints{9, 8}, 1), Ints{9});
    check("negative", take(Ints{-1, -2, -3}, 2), Ints{-1, -2});
    check("extremes", take(Ints{(-2147483647 - 1), 2147483647, 0}, 2), Ints{(-2147483647 - 1), 2147483647});
    check("from-zero", take_naturals(0, 5), Ints{0, 1, 2, 3, 4});
    check("from-ten", take_naturals(10, 3), Ints{10, 11, 12});
    check("none", take_naturals(7, 0), Ints{});
    check("one", take_naturals(0, 1), Ints{0});
    check("large-start", take_naturals(999998, 2), Ints{999998, 999999});
    if (failures > 0) {
        return 1;
    }
    std::cout << "all cases pass\n";
    return 0;
}
Take.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/take-the-first-n-items/.

import java.util.Arrays;
import java.util.stream.IntStream;

final class Take {
  private Take() {}

  /** Returns a copy of the first n items; a shorter array gives all its items. */
  static int[] take(int[] items, int n) {
    // copyOf pads with zeros when the length is larger, so use the smaller length.
    return Arrays.copyOf(items, Math.min(n, items.length));
  }

  /** Returns the first n items of the infinite sequence start, start + 1, ... */
  static int[] takeNaturals(int start, int n) {
    // iterate makes an infinite lazy stream; limit stops it after n items.
    return IntStream.iterate(start, i -> i + 1).limit(n).toArray();
  }
}
TakeTest.java 53 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/take-the-first-n-items/.

import static org.junit.jupiter.api.Assertions.assertArrayEquals;

import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

class TakeTest {
  static Stream<Arguments> cases() {
    return Stream.of(
        Arguments.of("first-three", new int[] {1, 2, 3, 4, 5}, 3, new int[] {1, 2, 3}),
        Arguments.of("first-two", new int[] {10, 20, 30, 40}, 2, new int[] {10, 20}),
        Arguments.of("zero", new int[] {1, 2}, 0, new int[] {}),
        Arguments.of("empty", new int[] {}, 3, new int[] {}),
        Arguments.of("more-than-length", new int[] {1, 2}, 5, new int[] {1, 2}),
        Arguments.of("equal-length", new int[] {4, 5, 6}, 3, new int[] {4, 5, 6}),
        Arguments.of("one", new int[] {9, 8}, 1, new int[] {9}),
        Arguments.of("negative", new int[] {-1, -2, -3}, 2, new int[] {-1, -2}),
        Arguments.of("extremes", new int[] {-2147483648, 2147483647, 0}, 2, new int[] {-2147483648, 2147483647}));
  }

  static Stream<Arguments> infinite() {
    return Stream.of(
        Arguments.of("from-zero", 0, 5, new int[] {0, 1, 2, 3, 4}),
        Arguments.of("from-ten", 10, 3, new int[] {10, 11, 12}),
        Arguments.of("none", 7, 0, new int[] {}),
        Arguments.of("one", 0, 1, new int[] {0}),
        Arguments.of("large-start", 999998, 2, new int[] {999998, 999999}));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("cases")
  void take(String name, int[] items, int n, int[] want) {
    assertArrayEquals(want, Take.take(items, n));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("infinite")
  void takeNaturals(String name, int start, int n, int[] want) {
    assertArrayEquals(want, Take.takeNaturals(start, n));
  }

  @Test
  void takeReturnsACopy() {
    int[] items = {1, 2, 3};
    Take.take(items, 2)[0] = 99;
    assertArrayEquals(new int[] {1, 2, 3}, items);
  }
}
take.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/take-the-first-n-items/.

#include "take.h"

#include <string.h>

size_t take(const int *items, size_t len, size_t n, int *out) {
    size_t k = n < len ? n : len;
    if (k > 0) {
        memcpy(out, items, k * sizeof *items);
    }
    return k;
}

int naturals_next(struct naturals *seq) {
    return seq->next++;
}

size_t take_naturals(int start, size_t n, int *out) {
    struct naturals seq = {start};
    // The loop asks the sequence for n values and no more.
    for (size_t i = 0; i < n; i++) {
        out[i] = naturals_next(&seq);
    }
    return n;
}
take.h 26 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/take-the-first-n-items/.

#ifndef TAKE_H
#define TAKE_H

#include <stddef.h>

// take copies the first n items of items[0..len) to out and returns their
// number, which is the smaller of n and len. out must have room for that
// many items.
size_t take(const int *items, size_t len, size_t n, int *out);

// struct naturals is a lazy infinite sequence: it holds only the next value.
struct naturals {
    int next;
};

// naturals_next returns the next value of the sequence and moves it on.
int naturals_next(struct naturals *seq);

// take_naturals writes the first n items of the sequence start, start + 1, ...
// to out and returns n. out must have room for n items.
size_t take_naturals(int start, size_t n, int *out);

#endif
test_take.c 65 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/take-the-first-n-items/.

#include "take.h"

#include <stdio.h>

static int failures = 0;

#define L(...) {__VA_ARGS__}

// An empty list has a 0 in it, because C has no empty array. The counts give
// the real lengths.
#define CHECK(name, len, given, n, m, expected)                                \
    do {                                                                       \
        const int g[] = given;                                                 \
        const int w[] = expected;                                              \
        int out[sizeof g / sizeof g[0]];                                       \
        size_t k = take(g, len, n, out);                                       \
        int ok = k == (size_t)(m);                                             \
        for (size_t i = 0; ok && i < k; i++) {                                 \
            ok = out[i] == w[i];                                               \
        }                                                                      \
        if (!ok) {                                                             \
            fprintf(stderr, "case %s failed\n", name);                         \
            failures++;                                                        \
        }                                                                      \
    } while (0)

#define CHECK_NATURALS(name, start, n, expected)                               \
    do {                                                                       \
        const int w[] = expected;                                              \
        int out[8];                                                            \
        size_t k = take_naturals(start, n, out);                               \
        int ok = k == (size_t)(n);                                             \
        for (size_t i = 0; ok && i < k; i++) {                                 \
            ok = out[i] == w[i];                                               \
        }                                                                      \
        if (!ok) {                                                             \
            fprintf(stderr, "case %s failed\n", name);                         \
            failures++;                                                        \
        }                                                                      \
    } while (0)

int main(void) {
    CHECK("first-three", 5, L(1, 2, 3, 4, 5), 3, 3, L(1, 2, 3));
    CHECK("first-two", 4, L(10, 20, 30, 40), 2, 2, L(10, 20));
    CHECK("zero", 2, L(1, 2), 0, 0, L(0));
    CHECK("empty", 0, L(0), 3, 0, L(0));
    CHECK("more-than-length", 2, L(1, 2), 5, 2, L(1, 2));
    CHECK("equal-length", 3, L(4, 5, 6), 3, 3, L(4, 5, 6));
    CHECK("one", 2, L(9, 8), 1, 1, L(9));
    CHECK("negative", 3, L(-1, -2, -3), 2, 2, L(-1, -2));
    CHECK("extremes", 3, L((-2147483647 - 1), 2147483647, 0), 2, 2, L((-2147483647 - 1), 2147483647));
    CHECK_NATURALS("from-zero", 0, 5, L(0, 1, 2, 3, 4));
    CHECK_NATURALS("from-ten", 10, 3, L(10, 11, 12));
    CHECK_NATURALS("none", 7, 0, L(0));
    CHECK_NATURALS("one", 0, 1, L(0));
    CHECK_NATURALS("large-start", 999998, 2, L(999998, 999999));
    if (failures > 0) {
        return 1;
    }
    printf("all cases pass\n");
    return 0;
}
Take.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/take-the-first-n-items/.

using System.Collections.Generic;
using System.Linq;

public static class Take
{
    // First returns a copy of the first n items; a shorter array gives all its items.
    public static int[] First(int[] items, int n)
    {
        // Take stops at the end of the sequence, so n can be larger than the length.
        return items.Take(n).ToArray();
    }

    // Naturals is the infinite sequence start, start + 1, ... It runs only when it is read.
    private static IEnumerable<int> Naturals(int start)
    {
        for (int i = start; ; i++)
        {
            yield return i;
        }
    }

    // FirstNaturals returns the first n items of the infinite sequence.
    public static int[] FirstNaturals(int start, int n)
    {
        return Naturals(start).Take(n).ToArray();
    }
}
TakeTests.cs 53 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/take-the-first-n-items/.

using Xunit;

public sealed class TakeTests
{
    public static TheoryData<string, int[], int, int[]> Cases => new()
    {
        { "first-three", new[] { 1, 2, 3, 4, 5 }, 3, new[] { 1, 2, 3 } },
        { "first-two", new[] { 10, 20, 30, 40 }, 2, new[] { 10, 20 } },
        { "zero", new[] { 1, 2 }, 0, new int[0] },
        { "empty", new int[0], 3, new int[0] },
        { "more-than-length", new[] { 1, 2 }, 5, new[] { 1, 2 } },
        { "equal-length", new[] { 4, 5, 6 }, 3, new[] { 4, 5, 6 } },
        { "one", new[] { 9, 8 }, 1, new[] { 9 } },
        { "negative", new[] { -1, -2, -3 }, 2, new[] { -1, -2 } },
        { "extremes", new[] { -2147483648, 2147483647, 0 }, 2, new[] { -2147483648, 2147483647 } },
    };

    public static TheoryData<string, int, int, int[]> Infinite => new()
    {
        { "from-zero", 0, 5, new[] { 0, 1, 2, 3, 4 } },
        { "from-ten", 10, 3, new[] { 10, 11, 12 } },
        { "none", 7, 0, new int[0] },
        { "one", 0, 1, new[] { 0 } },
        { "large-start", 999998, 2, new[] { 999998, 999999 } },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void First(string name, int[] items, int n, int[] want)
    {
        Assert.NotNull(name);
        Assert.Equal(want, Take.First(items, n));
    }

    [Theory]
    [MemberData(nameof(Infinite))]
    public void FirstNaturals(string name, int start, int n, int[] want)
    {
        Assert.NotNull(name);
        Assert.Equal(want, Take.FirstNaturals(start, n));
    }

    [Fact]
    public void FirstReturnsACopy()
    {
        int[] items = { 1, 2, 3 };
        Take.First(items, 2)[0] = 99;
        Assert.Equal(new[] { 1, 2, 3 }, items);
    }
}
take.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/take-the-first-n-items/.

/**
 * Returns a copy of the first n items; a shorter array gives all its items.
 * @param {number[]} items
 * @param {number} n at least 0
 * @returns {number[]}
 */
export function take(items, n) {
  // slice stops at the end of the array, so n can be larger than the length.
  return items.slice(0, n);
}

/** The infinite sequence start, start + 1, ... It runs only when it is read. */
function* naturals(start) {
  for (let i = start; ; i++) {
    yield i;
  }
}

/**
 * Returns the first n items of the infinite sequence start, start + 1, ...
 * @param {number} start
 * @param {number} n at least 0
 * @returns {number[]}
 */
export function takeNaturals(start, n) {
  // Iterator.prototype.take reads only n items from the generator.
  return naturals(start).take(n).toArray();
}
take.test.js 45 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/take-the-first-n-items/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { take, takeNaturals } from "./take.js";

const cases = [
  ["first-three", [1, 2, 3, 4, 5], 3, [1, 2, 3]],
  ["first-two", [10, 20, 30, 40], 2, [10, 20]],
  ["zero", [1, 2], 0, []],
  ["empty", [], 3, []],
  ["more-than-length", [1, 2], 5, [1, 2]],
  ["equal-length", [4, 5, 6], 3, [4, 5, 6]],
  ["one", [9, 8], 1, [9]],
  ["negative", [-1, -2, -3], 2, [-1, -2]],
  ["extremes", [-2147483648, 2147483647, 0], 2, [-2147483648, 2147483647]],
];

const infinite = [
  ["from-zero", 0, 5, [0, 1, 2, 3, 4]],
  ["from-ten", 10, 3, [10, 11, 12]],
  ["none", 7, 0, []],
  ["one", 0, 1, [0]],
  ["large-start", 999998, 2, [999998, 999999]],
];

for (const [name, items, n, want] of cases) {
  test(name, () => {
    assert.deepEqual(take(items, n), want);
  });
}

for (const [name, start, n, want] of infinite) {
  test(`naturals ${name}`, () => {
    assert.deepEqual(takeNaturals(start, n), want);
  });
}

test("take returns a copy", () => {
  const items = [1, 2, 3];
  take(items, 2).push(99);
  assert.deepEqual(items, [1, 2, 3]);
});
take.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/take-the-first-n-items/.

/** Returns a copy of the first n items; a shorter array gives all its items. */
export function take(items: readonly number[], n: number): number[] {
  // slice stops at the end of the array, so n can be larger than the length.
  return items.slice(0, n);
}

/** The infinite sequence start, start + 1, ... It runs only when it is read. */
function* naturals(start: number): Generator<number> {
  for (let i = start; ; i++) {
    yield i;
  }
}

/** Returns the first n items of the infinite sequence start, start + 1, ... */
export function takeNaturals(start: number, n: number): number[] {
  const out: number[] = [];
  if (n === 0) {
    return out;
  }
  // The loop stops the generator after n items, so it never reads the rest.
  for (const i of naturals(start)) {
    out.push(i);
    if (out.length === n) {
      break;
    }
  }
  return out;
}
take.test.ts 45 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/take-the-first-n-items/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { take, takeNaturals } from "./take.ts";

const cases: [string, number[], number, number[]][] = [
  ["first-three", [1, 2, 3, 4, 5], 3, [1, 2, 3]],
  ["first-two", [10, 20, 30, 40], 2, [10, 20]],
  ["zero", [1, 2], 0, []],
  ["empty", [], 3, []],
  ["more-than-length", [1, 2], 5, [1, 2]],
  ["equal-length", [4, 5, 6], 3, [4, 5, 6]],
  ["one", [9, 8], 1, [9]],
  ["negative", [-1, -2, -3], 2, [-1, -2]],
  ["extremes", [-2147483648, 2147483647, 0], 2, [-2147483648, 2147483647]],
];

const infinite: [string, number, number, number[]][] = [
  ["from-zero", 0, 5, [0, 1, 2, 3, 4]],
  ["from-ten", 10, 3, [10, 11, 12]],
  ["none", 7, 0, []],
  ["one", 0, 1, [0]],
  ["large-start", 999998, 2, [999998, 999999]],
];

for (const [name, items, n, want] of cases) {
  test(name, () => {
    assert.deepEqual(take(items, n), want);
  });
}

for (const [name, start, n, want] of infinite) {
  test(`naturals ${name}`, () => {
    assert.deepEqual(takeNaturals(start, n), want);
  });
}

test("take returns a copy", () => {
  const items = [1, 2, 3];
  take(items, 2).push(99);
  assert.deepEqual(items, [1, 2, 3]);
});
take.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/take-the-first-n-items/.

// Package take takes the first n items of a slice or of an infinite sequence.
package take

import (
	"iter"
	"slices"
)

// Take returns a copy of the first n items; a shorter slice gives all its items.
func Take(items []int, n int) []int {
	// items[:n] panics when n is larger than the length, so use the smaller one.
	return slices.Clone(items[:min(n, len(items))])
}

// Naturals is the infinite sequence start, start + 1, ... It runs only when it
// is read, and it stops when yield returns false.
func Naturals(start int) iter.Seq[int] {
	return func(yield func(int) bool) {
		for i := start; ; i++ {
			if !yield(i) {
				return
			}
		}
	}
}

// TakeNaturals returns the first n items of the infinite sequence.
func TakeNaturals(start, n int) []int {
	out := []int{}
	if n == 0 {
		return out
	}
	for i := range Naturals(start) {
		out = append(out, i)
		if len(out) == n {
			break
		}
	}
	return out
}
take_test.go 62 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/take-the-first-n-items/.

package take

import (
	"slices"
	"testing"
)

var cases = []struct {
	name  string
	items []int
	n     int
	want  []int
}{
	{"first-three", []int{1, 2, 3, 4, 5}, 3, []int{1, 2, 3}},
	{"first-two", []int{10, 20, 30, 40}, 2, []int{10, 20}},
	{"zero", []int{1, 2}, 0, []int{}},
	{"empty", []int{}, 3, []int{}},
	{"more-than-length", []int{1, 2}, 5, []int{1, 2}},
	{"equal-length", []int{4, 5, 6}, 3, []int{4, 5, 6}},
	{"one", []int{9, 8}, 1, []int{9}},
	{"negative", []int{-1, -2, -3}, 2, []int{-1, -2}},
	{"extremes", []int{-2147483648, 2147483647, 0}, 2, []int{-2147483648, 2147483647}},
}

var infinite = []struct {
	name     string
	start, n int
	want     []int
}{
	{"from-zero", 0, 5, []int{0, 1, 2, 3, 4}},
	{"from-ten", 10, 3, []int{10, 11, 12}},
	{"none", 7, 0, []int{}},
	{"one", 0, 1, []int{0}},
	{"large-start", 999998, 2, []int{999998, 999999}},
}

func TestTake(t *testing.T) {
	for _, c := range cases {
		if got := Take(c.items, c.n); !slices.Equal(got, c.want) {
			t.Errorf("%s: got %v, want %v", c.name, got, c.want)
		}
	}
}

func TestTakeNaturals(t *testing.T) {
	for _, c := range infinite {
		if got := TakeNaturals(c.start, c.n); !slices.Equal(got, c.want) {
			t.Errorf("%s: got %v, want %v", c.name, got, c.want)
		}
	}
}

func TestTakeReturnsACopy(t *testing.T) {
	items := []int{1, 2, 3}
	Take(items, 2)[0] = 99
	if !slices.Equal(items, []int{1, 2, 3}) {
		t.Errorf("the input changed: %v", items)
	}
}
take.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/take-the-first-n-items/.

/// Returns a copy of the first n items; a shorter slice gives all its items.
pub fn take(items: &[i32], n: usize) -> Vec<i32> {
    // Iterator::take stops at the end of the slice, so n can be larger than the length.
    items.iter().take(n).copied().collect()
}

/// Returns the first n items of the infinite sequence start, start + 1, ...
pub fn take_naturals(start: i32, n: usize) -> Vec<i32> {
    // start.. is an infinite range; take reads only n items from it.
    (start..).take(n).collect()
}
tests/take_test.rs 36 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/take-the-first-n-items/.

use algo_take_the_first_n_items::{take, take_naturals};

#[test]
fn cases() {
    let cases: Vec<(&str, &[i32], usize, Vec<i32>)> = vec![
        ("first-three", &[1, 2, 3, 4, 5], 3, vec![1, 2, 3]),
        ("first-two", &[10, 20, 30, 40], 2, vec![10, 20]),
        ("zero", &[1, 2], 0, vec![]),
        ("empty", &[], 3, vec![]),
        ("more-than-length", &[1, 2], 5, vec![1, 2]),
        ("equal-length", &[4, 5, 6], 3, vec![4, 5, 6]),
        ("one", &[9, 8], 1, vec![9]),
        ("negative", &[-1, -2, -3], 2, vec![-1, -2]),
        ("extremes", &[-2147483648, 2147483647, 0], 2, vec![-2147483648, 2147483647]),
    ];
    for (name, items, n, want) in cases {
        assert_eq!(take(items, n), want, "{name}");
    }
}

#[test]
fn infinite() {
    let cases: Vec<(&str, i32, usize, Vec<i32>)> = vec![
        ("from-zero", 0, 5, vec![0, 1, 2, 3, 4]),
        ("from-ten", 10, 3, vec![10, 11, 12]),
        ("none", 7, 0, vec![]),
        ("one", 0, 1, vec![0]),
        ("large-start", 999998, 2, vec![999998, 999999]),
    ];
    for (name, start, n, want) in cases {
        assert_eq!(take_naturals(start, n), want, "{name}");
    }
}
take.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/take-the-first-n-items/.

# take N ITEM...
# Prints the first N items, one on each line. Fewer items give all of them.
take() {
  local n=$1
  shift
  # ${@:1:n} is n arguments from the first one; it stops at the last argument.
  (( n > 0 && $# > 0 )) && printf '%s\n' "${@:1:n}"
  return 0
}

# naturals START
# Prints START, START + 1, ... without end. It stops when its output closes:
# a write to a closed pipe kills it or makes printf fail.
naturals() {
  local i
  for ((i = $1; ; i++)); do
    printf '%d\n' "$i" || return 0
  done
}

# take_naturals START N
# Prints the first N items of the infinite sequence. head reads N lines and
# exits, and then naturals stops.
take_naturals() {
  (( $2 > 0 )) || return 0
  naturals "$1" | head -n "$2"
}
test_take.bats 34 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/take-the-first-n-items/.

bats_require_minimum_version 1.5.0

setup() {
  source "$BATS_TEST_DIRNAME/take.sh"
}

check() { # check WANT COMMAND ARG...
  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=$("$@"; printf x)
  [ "$got" = "$want" ] || { printf 'got:  %q\nwant: %q\n' "$got" "$want"; return 1; }
}

@test "first-three" { check "1\n2\n3\n" take 3 1 2 3 4 5; }
@test "first-two" { check "10\n20\n" take 2 10 20 30 40; }
@test "zero" { check "" take 0 1 2; }
@test "empty" { check "" take 3; }
@test "more-than-length" { check "1\n2\n" take 5 1 2; }
@test "equal-length" { check "4\n5\n6\n" take 3 4 5 6; }
@test "one" { check "9\n" take 1 9 8; }
@test "negative" { check "-1\n-2\n" take 2 -1 -2 -3; }
@test "extremes" { check "-2147483648\n2147483647\n" take 2 -2147483648 2147483647 0; }
@test "naturals from-zero" { check "0\n1\n2\n3\n4\n" take_naturals 0 5; }
@test "naturals from-ten" { check "10\n11\n12\n" take_naturals 10 3; }
@test "naturals none" { check "" take_naturals 7 0; }
@test "naturals one" { check "0\n" take_naturals 0 1; }
@test "naturals large-start" { check "999998\n999999\n" take_naturals 999998 2; }

References

  1. itertools, Python 3.14 documentation, count; islice
  2. Iterator.prototype.take(), MDN Web Docs, Description
  3. Interface Stream, Java SE 25 API, limit(long)
  4. Trait Iterator, The Rust Standard Library, take
  5. std::ranges::take_view, std::ranges::views::take, cppreference.com, description
  6. Package iter, Go 1.26.5 standard library, Seq; Iterators
  7. Enumerable.Take, .NET API reference, Take(IEnumerable, Int32); Remarks
  8. GNU Coreutils manual, 5.1 head
  9. Array.prototype.slice(), MDN Web Docs, Description; Parameters
  10. Class Arrays, Java SE 25 API, copyOf(int[], int)
  11. Bash Reference Manual, 3.2.3 Pipelines; 3.7.5 Exit Status
  12. signal(7), Linux manual page, Signal numbering for standard signals

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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (bash)I0 not checked yet
  • the tests did not run in this build
Code (c)I0 not checked yet
  • the tests did not run in this build
Code (cpp)I0 not checked yet
  • the tests did not run in this build
Code (csharp)I0 not checked yet
  • the tests did not run in this build
Code (go)I0 not checked yet
  • the tests did not run in this build
Code (java)I0 not checked yet
  • the tests did not run in this build
Code (javascript)I0 not checked yet
  • the tests did not run in this build
Code (python)I0 not checked yet
  • the tests did not run in this build
Code (rust)I0 not checked yet
  • the tests did not run in this build
Code (typescript)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source