Programming Search⌘K

Taskintro

Use a tuple

Also called return two values, return multiple values, pair, unpack a tuple, destructure a tuple, multiple return values.

Return the smallest and the largest number of a list as one tuple, then unpack it into two variables, in each tier 1 language.

Task

Return two values from one function as a tuple. The function min_max(numbers) takes a list with at least one integer. It returns the pair (smallest, largest). The caller then unpacks the pair into two variables. For example, min_max([3, 1, 2]) is (1, 3). Each number fits in a signed 32-bit integer, and the function must not change the list.

A tuple groups values by position. A record groups them by name (see Define a record type). For the idea behind tuples, see Tuple.

Solutions

Language Result type Unpack
Python tuple[int, int], made by return lo, hi lo, hi = min_max(numbers)
JavaScript an array of length 2 const [lo, hi] = minMax(numbers)
TypeScript readonly [min: number, max: number] const [lo, hi] = minMax(numbers)
Java record Pair(int min, int max) a record pattern, instanceof Pair(int lo, int hi)
C# the value tuple (int Min, int Max) var (lo, hi) = MinMax.Of(numbers)
Go two results, (lo, hi int32) lo, hi := MinMax(numbers)
Rust (i32, i32) let (lo, hi) = min_max(&numbers)
C struct min_max { int32_t min; int32_t max; } read .min and .max
C++ std::tuple<std::int32_t, std::int32_t> auto [lo, hi] = min_max(numbers)
Bash the line MIN MAX on standard output read -r lo hi < <(min_max ...)
  • Make and unpack. In Python, "A tuple consists of a number of values separated by commas"1, so return lo, hi makes a tuple without parentheses. The caller unpacks it: "This is called, appropriately enough, sequence unpacking and works for any sequence on the right-hand side."1 JavaScript has no tuple type. A function returns an array, and "The destructuring syntax is a JavaScript syntax that makes it possible to unpack values from arrays, or properties from objects, into distinct variables."2 Rust uses a pattern with let, and the book says: "This is called destructuring because it breaks the single tuple into three parts."3
  • A type for each position. In Rust, "A tuple is a general way of grouping together a number of values with a variety of types into one compound type."3 In TypeScript, "A tuple type is another sort of Array type that knows exactly how many elements it contains, and exactly which types it contains at specific positions."4 The solution makes the tuple readonly, because "Tuples tend to be created and left un-modified in most code, so annotating types as readonly tuples when possible is a good default."4 In C++, "Class template std::tuple is a fixed-size collection of heterogeneous values."5 A structured binding unpacks it: it "Binds the specified names to subobjects or elements of the initializer."6
  • C# names the elements. "The tuples feature provides a concise syntax to group multiple data elements in a lightweight data structure."7 The solution names the elements Min and Max, but "The default names of tuple fields are Item1 , Item2 , Item3 , and so on."7 Two tuples compare with ==: "Tuple types support the == and != operators."7
  • Java uses a record. A Java method returns one value. A record is a short way to return two values, and "Records can be thought of as nominal tuples."8 The names min and max also tell the reader which value is which. For a quick pair, Map.entry(k, v) "Returns an unmodifiable Map.Entry containing the given key and value."9
  • Go returns two results. A Go function can return several results, and "A tuple assignment assigns the individual elements of a multi-valued operation to a list of variables."10 The results cannot be kept together in one variable. To keep them together, define a struct.
  • C returns a struct. "The return type of a function shall be void or a complete object type other than array type."11 A struct is such a type, so the solution returns a small struct by value. No heap memory and no output pointers are necessary.
  • Bash prints the values. A Bash function returns only an exit status. The solution prints the two numbers on one line, and the caller reads them with read -r lo hi.

Edge cases

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

  • one: a list with one number gives that number twice.
  • negative: all of the numbers are below 0, so a start value of 0 would give a wrong largest number. The solutions start from the first number.
  • all-same: equal numbers give an equal pair.
  • int32-extremes: the smallest and the largest 32-bit integers are in the list. A start value such as -1 or 1 << 30 would be wrong.
  • sorted and reversed: the order of the list does not change the answer.

Pitfalls

  • Python a tuple with one item needs a comma. The parentheses alone do not make a tuple: "a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses)."1 Also, "Sequence unpacking requires that there are as many variables on the left side of the equals sign as there are elements in the sequence."1
a = (5)
b = (5,)
print(type(a).__name__, type(b).__name__)
try:
    lo, hi = (1, 2, 3)
except ValueError as e:
    print(type(e).__name__)
Output
int tuple
ValueError
  • JavaScript a missing position is undefined. If the array is shorter than the pattern, "only the first N variables are assigned values. The values of the remaining variables will be undefined."2 No error occurs, and a later sum gives NaN. Check the length, or give a default value:
const [lo, hi] = [5];
console.log(hi, lo + hi);
const [a, b = a] = [5];
console.log(a, b);
Output
undefined NaN
5 5
  • TypeScript a tuple is an array at run time. A tuple type is an Array type4, so a tuple type that is not readonly has push. The type checker accepts push on [number, number], and the tuple then has three elements. Use readonly [number, number], which has no push:
const pair: [number, number] = [1, 3];
pair.push(5);
console.log(pair.length);
const fixed: readonly [number, number] = [1, 3];
console.log(fixed.length);
Output
3
2
  • Java Map.entry does not accept null. The entries "disallow null keys and values. Attempts to create them with null keys or values result in NullPointerException ."9 A record accepts null components:
import java.util.Map;

public class Main {
  record Pair(String a, String b) {}

  public static void main(String[] args) {
    try {
      Map.entry("a", null);
    } catch (NullPointerException e) {
      System.out.println("NullPointerException");
    }
    System.out.println(new Pair("a", null));
  }
}
Output
NullPointerException
Pair[a=a, b=null]
  • C# assignment ignores the element names. Tuples are assigned by position: "The assignment process ignores the names of tuple fields"7. A tuple with the names in the other order thus gets the values in the wrong fields, with no warning:
using System;

(int Min, int Max) pair = (1, 3);
(int Max, int Min) swapped = pair;
Console.WriteLine(swapped.Max + " " + swapped.Min);
Output
1 3
  • C++ auto [a, b] binds to a copy. "A structured binding declaration first introduces a uniquely-named variable (here denoted by e ) to hold the value of the initializer"6. With auto, that variable is a copy, so a change to lo does not change the tuple. Use auto & to change the tuple:
#include <iostream>
#include <tuple>

int main() {
    std::tuple<int, int> t{1, 3};
    auto [lo, hi] = t;
    lo = 7;
    std::cout << std::get<0>(t) << '\n';
    auto &[rlo, rhi] = t;
    rlo = 7;
    std::cout << std::get<0>(t) << ' ' << hi + rhi << '\n';
}
Output
1
7 6
  • Bash read at the end of a pipe loses the values. "Each command in a multi-command pipeline, where pipes are created, is executed in its own subshell, which is a separate process"12. The variables that read sets are in that subshell, so they are empty after the pipe. Use process substitution:
min_max() { echo "1 3"; }
min_max | read -r lo hi
echo "[$lo] [$hi]"
read -r lo hi < <(min_max)
echo "[$lo] [$hi]"
Output
[] []
[1] [3]

Code

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

min_max.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/use-a-tuple/.


def min_max(numbers: list[int]) -> tuple[int, int]:
    """Returns (smallest, largest) of a list with at least one number."""
    lo = hi = numbers[0]
    for n in numbers[1:]:
        if n < lo:
            lo = n
        elif n > hi:
            hi = n
    return lo, hi  # the comma makes the tuple
test_min_max.py 32 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/use-a-tuple/.

import pytest

from min_max import min_max

CASES = {
    "mixed": ([3, 1, 2], (1, 3)),
    "longer": ([4, 9, -2, 7, 0], (-2, 9)),
    "one": ([5], (5, 5)),
    "negative": ([-3, -1, -7], (-7, -1)),
    "all-same": ([2, 2, 2], (2, 2)),
    "int32-extremes": ([2147483647, 0, -2147483648], (-2147483648, 2147483647)),
    "sorted": ([1, 2, 3, 4], (1, 4)),
    "reversed": ([4, 3, 2, 1], (1, 4)),
}


@pytest.mark.parametrize("case", CASES)
def test_min_max(case):
    numbers, want = CASES[case]
    before = list(numbers)
    lo, hi = min_max(numbers)  # sequence unpacking
    assert (lo, hi) == want
    assert numbers == before


def test_result_is_a_tuple():
    got = min_max([3, 1, 2])
    assert isinstance(got, tuple)
    assert got[0] == 1 and got[1] == 3
min_max.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-tuple/.

#include "min_max.hpp"

#include <algorithm>

std::tuple<std::int32_t, std::int32_t> min_max(const std::vector<std::int32_t> &numbers) {
    std::int32_t lo = numbers[0];
    std::int32_t hi = numbers[0];
    for (std::int32_t n : numbers) {
        lo = std::min(lo, n);
        hi = std::max(hi, n);
    }
    return {lo, hi};
}
min_max.hpp 11 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-tuple/.

#pragma once

#include <cstdint>
#include <tuple>
#include <vector>

// min_max returns (smallest, largest) of a vector with at least one number.
std::tuple<std::int32_t, std::int32_t> min_max(const std::vector<std::int32_t> &numbers);
test_min_max.cpp 38 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-tuple/.

#include "min_max.hpp"

#include <cstdint>
#include <iostream>
#include <limits>
#include <string_view>
#include <vector>

static int failures = 0;

static void check(std::string_view label, const std::vector<std::int32_t> &numbers, std::int32_t lo, std::int32_t hi) {
    auto [got_lo, got_hi] = min_max(numbers); // structured binding
    if (got_lo != lo || got_hi != hi) {
        std::cerr << "case " << label << " failed\n";
        failures++;
    }
}

int main() {
    constexpr auto top = std::numeric_limits<std::int32_t>::max();
    constexpr auto bottom = std::numeric_limits<std::int32_t>::min();
    check("mixed", {3, 1, 2}, 1, 3);
    check("longer", {4, 9, -2, 7, 0}, -2, 9);
    check("one", {5}, 5, 5);
    check("negative", {-3, -1, -7}, -7, -1);
    check("all-same", {2, 2, 2}, 2, 2);
    check("int32-extremes", {top, 0, bottom}, bottom, top);
    check("sorted", {1, 2, 3, 4}, 1, 4);
    check("reversed", {4, 3, 2, 1}, 1, 4);
    if (failures > 0) {
        return 1;
    }
    std::cout << "all cases pass\n";
    return 0;
}
MinMax.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-tuple/.

import java.util.List;

final class MinMax {
  private MinMax() {}

  /** Java has no tuple type. A record is a named tuple with named components. */
  record Pair(int min, int max) {}

  /** Returns the smallest and the largest of a list with at least one number. */
  static Pair minMax(List<Integer> numbers) {
    int lo = numbers.get(0);
    int hi = lo;
    for (int n : numbers) {
      lo = Math.min(lo, n);
      hi = Math.max(hi, n);
    }
    return new Pair(lo, hi);
  }
}
MinMaxTest.java 44 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-tuple/.

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

import java.util.ArrayList;
import java.util.List;
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 MinMaxTest {
  static Stream<Arguments> cases() {
    return Stream.of(
        Arguments.of("mixed", List.of(3, 1, 2), 1, 3),
        Arguments.of("longer", List.of(4, 9, -2, 7, 0), -2, 9),
        Arguments.of("one", List.of(5), 5, 5),
        Arguments.of("negative", List.of(-3, -1, -7), -7, -1),
        Arguments.of("all-same", List.of(2, 2, 2), 2, 2),
        Arguments.of("int32-extremes", List.of(Integer.MAX_VALUE, 0, Integer.MIN_VALUE), Integer.MIN_VALUE, Integer.MAX_VALUE),
        Arguments.of("sorted", List.of(1, 2, 3, 4), 1, 4),
        Arguments.of("reversed", List.of(4, 3, 2, 1), 1, 4));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("cases")
  void minMax(String name, List<Integer> numbers, int min, int max) {
    List<Integer> before = new ArrayList<>(numbers);
    MinMax.Pair got = MinMax.minMax(numbers);
    assertEquals(min, got.min());
    assertEquals(max, got.max());
    assertEquals(before, numbers);
  }

  @Test
  void deconstructWithARecordPattern() {
    if (MinMax.minMax(List.of(3, 1, 2)) instanceof MinMax.Pair(int lo, int hi)) {
      assertEquals(1, lo);
      assertEquals(3, hi);
    }
  }
}
min_max.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-tuple/.

#include "min_max.h"

struct min_max min_max(const int32_t *numbers, size_t n) {
    struct min_max r = {numbers[0], numbers[0]};
    for (size_t i = 1; i < n; i++) {
        if (numbers[i] < r.min) {
            r.min = numbers[i];
        }
        if (numbers[i] > r.max) {
            r.max = numbers[i];
        }
    }
    return r; // a struct is returned by value
}
min_max.h 20 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-tuple/.

#ifndef MIN_MAX_H
#define MIN_MAX_H

#include <stddef.h>
#include <stdint.h>

// C has no tuple type. A small struct carries the two values.
struct min_max {
    int32_t min;
    int32_t max;
};

// min_max returns the smallest and the largest of the n numbers. n must be at
// least 1.
struct min_max min_max(const int32_t *numbers, size_t n);

#endif
test_min_max.c 37 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-tuple/.

#include "min_max.h"

#include <stdio.h>

static int failures = 0;

#define L(...) {__VA_ARGS__}

#define CHECK(label, nums, lo, hi)                                             \
    do {                                                                       \
        const int32_t numbers[] = nums;                                        \
        const size_t n = sizeof numbers / sizeof numbers[0];                   \
        struct min_max got = min_max(numbers, n);                              \
        if (got.min != (lo) || got.max != (hi)) {                              \
            fprintf(stderr, "case %s failed\n", label);                        \
            failures++;                                                        \
        }                                                                      \
    } while (0)

int main(void) {
    CHECK("mixed", L(3, 1, 2), 1, 3);
    CHECK("longer", L(4, 9, -2, 7, 0), -2, 9);
    CHECK("one", L(5), 5, 5);
    CHECK("negative", L(-3, -1, -7), -7, -1);
    CHECK("all-same", L(2, 2, 2), 2, 2);
    CHECK("int32-extremes", L(INT32_MAX, 0, INT32_MIN), INT32_MIN, INT32_MAX);
    CHECK("sorted", L(1, 2, 3, 4), 1, 4);
    CHECK("reversed", L(4, 3, 2, 1), 1, 4);
    if (failures > 0) {
        return 1;
    }
    printf("all cases pass\n");
    return 0;
}
MinMax.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-tuple/.

using System.Collections.Generic;

public static class MinMax
{
    // Returns a value tuple with named elements. The names help the reader;
    // the type is (int, int).
    public static (int Min, int Max) Of(IReadOnlyList<int> numbers)
    {
        int lo = numbers[0], hi = numbers[0];
        foreach (int n in numbers)
        {
            if (n < lo) lo = n;
            if (n > hi) hi = n;
        }
        return (lo, hi);
    }
}
MinMaxTests.cs 39 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-tuple/.

using System.Linq;
using Xunit;

public sealed class MinMaxTests
{
    public static TheoryData<string, int[], int, int> Cases => new()
    {
        { "mixed", new[] { 3, 1, 2 }, 1, 3 },
        { "longer", new[] { 4, 9, -2, 7, 0 }, -2, 9 },
        { "one", new[] { 5 }, 5, 5 },
        { "negative", new[] { -3, -1, -7 }, -7, -1 },
        { "all-same", new[] { 2, 2, 2 }, 2, 2 },
        { "int32-extremes", new[] { int.MaxValue, 0, int.MinValue }, int.MinValue, int.MaxValue },
        { "sorted", new[] { 1, 2, 3, 4 }, 1, 4 },
        { "reversed", new[] { 4, 3, 2, 1 }, 1, 4 },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void Check(string name, int[] numbers, int min, int max)
    {
        Assert.NotNull(name);
        var before = numbers.ToArray();
        var (lo, hi) = MinMax.Of(numbers); // deconstruction
        Assert.Equal(min, lo);
        Assert.Equal(max, hi);
        Assert.Equal(before, numbers);
    }

    [Fact]
    public void TuplesCompareByValue()
    {
        Assert.True(MinMax.Of(new[] { 3, 1, 2 }) == (1, 3));
        Assert.Equal(3, MinMax.Of(new[] { 3, 1, 2 }).Max);
    }
}
min_max.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-tuple/.

// minMax returns [smallest, largest] of an array with at least one number.
// JavaScript has no tuple type, so the pair is an array of length 2.
export function minMax(numbers) {
  let lo = numbers[0];
  let hi = numbers[0];
  for (const n of numbers) {
    if (n < lo) lo = n;
    if (n > hi) hi = n;
  }
  return [lo, hi];
}
min_max.test.js 27 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-tuple/.

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

import { minMax } from "./min_max.js";

const cases = [
  ["mixed", [3, 1, 2], [1, 3]],
  ["longer", [4, 9, -2, 7, 0], [-2, 9]],
  ["one", [5], [5, 5]],
  ["negative", [-3, -1, -7], [-7, -1]],
  ["all-same", [2, 2, 2], [2, 2]],
  ["int32-extremes", [2147483647, 0, -2147483648], [-2147483648, 2147483647]],
  ["sorted", [1, 2, 3, 4], [1, 4]],
  ["reversed", [4, 3, 2, 1], [1, 4]],
];

for (const [name, numbers, want] of cases) {
  test(name, () => {
    const before = [...numbers];
    const [lo, hi] = minMax(numbers); // destructuring
    assert.deepEqual([lo, hi], want);
    assert.deepEqual(numbers, before);
  });
}
min_max.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-tuple/.

// A readonly tuple type: an array of exactly two numbers that the caller
// cannot change.
export type MinMax = readonly [min: number, max: number];

export function minMax(numbers: readonly number[]): MinMax {
  let lo = numbers[0];
  let hi = numbers[0];
  for (const n of numbers) {
    if (n < lo) lo = n;
    if (n > hi) hi = n;
  }
  return [lo, hi];
}
min_max.test.ts 27 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-tuple/.

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

import { minMax } from "./min_max.ts";

const cases: [string, number[], [number, number]][] = [
  ["mixed", [3, 1, 2], [1, 3]],
  ["longer", [4, 9, -2, 7, 0], [-2, 9]],
  ["one", [5], [5, 5]],
  ["negative", [-3, -1, -7], [-7, -1]],
  ["all-same", [2, 2, 2], [2, 2]],
  ["int32-extremes", [2147483647, 0, -2147483648], [-2147483648, 2147483647]],
  ["sorted", [1, 2, 3, 4], [1, 4]],
  ["reversed", [4, 3, 2, 1], [1, 4]],
];

for (const [name, numbers, want] of cases) {
  test(name, () => {
    const before = [...numbers];
    const [lo, hi] = minMax(numbers);
    assert.deepEqual([lo, hi], want);
    assert.deepEqual(numbers, before);
  });
}
min_max.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-tuple/.

// Package minmax returns two values from one function.
package minmax

// MinMax returns the smallest and the largest of a slice with at least one
// number. Go has no tuple type; a function can return several results.
func MinMax(numbers []int32) (lo, hi int32) {
	lo, hi = numbers[0], numbers[0]
	for _, n := range numbers {
		lo = min(lo, n)
		hi = max(hi, n)
	}
	return lo, hi
}
min_max_test.go 38 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-tuple/.

package minmax

import (
	"math"
	"slices"
	"testing"
)

var cases = []struct {
	name    string
	numbers []int32
	lo, hi  int32
}{
	{"mixed", []int32{3, 1, 2}, 1, 3},
	{"longer", []int32{4, 9, -2, 7, 0}, -2, 9},
	{"one", []int32{5}, 5, 5},
	{"negative", []int32{-3, -1, -7}, -7, -1},
	{"all-same", []int32{2, 2, 2}, 2, 2},
	{"int32-extremes", []int32{math.MaxInt32, 0, math.MinInt32}, math.MinInt32, math.MaxInt32},
	{"sorted", []int32{1, 2, 3, 4}, 1, 4},
	{"reversed", []int32{4, 3, 2, 1}, 1, 4},
}

func TestMinMax(t *testing.T) {
	for _, c := range cases {
		before := slices.Clone(c.numbers)
		lo, hi := MinMax(c.numbers)
		if lo != c.lo || hi != c.hi {
			t.Errorf("%s: got (%d, %d), want (%d, %d)", c.name, lo, hi, c.lo, c.hi)
		}
		if !slices.Equal(c.numbers, before) {
			t.Errorf("%s: the input changed", c.name)
		}
	}
}
min_max.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-tuple/.

/// Returns (smallest, largest) of a slice with at least one number.
pub fn min_max(numbers: &[i32]) -> (i32, i32) {
    let mut pair = (numbers[0], numbers[0]);
    for &n in numbers {
        pair.0 = pair.0.min(n);
        pair.1 = pair.1.max(n);
    }
    pair
}
tests/min_max_test.rs 22 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-tuple/.

use algo_use_a_tuple::min_max;

#[test]
fn cases() {
    let cases: Vec<(&str, Vec<i32>, (i32, i32))> = vec![
        ("mixed", vec![3, 1, 2], (1, 3)),
        ("longer", vec![4, 9, -2, 7, 0], (-2, 9)),
        ("one", vec![5], (5, 5)),
        ("negative", vec![-3, -1, -7], (-7, -1)),
        ("all-same", vec![2, 2, 2], (2, 2)),
        ("int32-extremes", vec![i32::MAX, 0, i32::MIN], (i32::MIN, i32::MAX)),
        ("sorted", vec![1, 2, 3, 4], (1, 4)),
        ("reversed", vec![4, 3, 2, 1], (1, 4)),
    ];
    for (name, numbers, want) in cases {
        let (lo, hi) = min_max(&numbers); // destructuring
        assert_eq!((lo, hi), want, "case {name}");
    }
}
min_max.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/use-a-tuple/.

# min_max NUMBER...
# Prints "MIN MAX" on one line. Bash has no tuple type, so a function returns
# several values as words of its output, and the caller reads them back.
min_max() {
  local lo=$1 hi=$1 n
  for n in "$@"; do
    ((n < lo)) && lo=$n
    ((n > hi)) && hi=$n
  done
  printf '%s %s\n' "$lo" "$hi"
}
test_min_max.bats 25 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/use-a-tuple/.

bats_require_minimum_version 1.5.0

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

check() { # check LO HI NUMBER...
  local lo hi want_lo=$1 want_hi=$2
  shift 2
  read -r lo hi < <(min_max "$@")
  [ "$lo $hi" = "$want_lo $want_hi" ] || { printf 'got:  %s %s\nwant: %s %s\n' "$lo" "$hi" "$want_lo" "$want_hi"; return 1; }
}

@test "mixed" { check 1 3 3 1 2; }
@test "longer" { check -2 9 4 9 -2 7 0; }
@test "one" { check 5 5 5; }
@test "negative" { check -7 -1 -3 -1 -7; }
@test "all-same" { check 2 2 2 2 2; }
@test "int32-extremes" { check -2147483648 2147483647 2147483647 0 -2147483648; }
@test "sorted" { check 1 4 1 2 3 4; }
@test "reversed" { check 1 4 4 3 2 1; }

References

  1. The Python Tutorial, 5.3 Tuples and Sequences, 5.3 Tuples and Sequences
  2. MDN Web Docs, Destructuring, Array destructuring
  3. The Rust Programming Language, 3.2 Data Types, The Tuple Type
  4. TypeScript Handbook, Object Types, Tuple Types; readonly Tuple Types
  5. cppreference.com, std::tuple, Description
  6. cppreference.com, Structured binding declaration, Binding process
  7. C# reference, Tuple types, Tuple field names; Tuple assignment and deconstruction; Tuple equality
  8. JEP 395: Records, Summary
  9. Java SE 27 API, Interface Map, entry(K, V); Unmodifiable Maps
  10. The Go Programming Language Specification, Return statements; Assignment statements
  11. ISO/IEC 9899:201x, committee draft N1570 (C11), 6.9.1 Function definitions
  12. Bash Reference Manual, 3.2.3 Pipelines

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