Programming Search⌘K

Taskcore

Destructure a value

Also called unpack a tuple, sequence unpacking, destructuring assignment, structured bindings, record patterns, deconstruct a tuple, Manhattan distance.

Take two points apart into the names x1, y1, x2 and y2 with one statement each, and return their Manhattan distance.

Task

Take a compound value apart into names with one statement, in place of one index or one field access for each part. The function manhattan(p, q) gets two points. Each point is a list [x, y] of two integers. The function gives the names x1 and y1 to the parts of p, and x2 and y2 to the parts of q. Then it returns the Manhattan distance |x1 - x2| + |y1 - y2|.

For example, manhattan([1, 2], [4, 6]) is 3 + 4 = 7.

The distance is not the important part. The important part is the statement that gives the names. Python calls it sequence unpacking, JavaScript and Kotlin call it destructuring, and C++ calls it a structured binding. Some languages have no such statement, and the solution reads each part by its index. Pattern match on a value uses the same kind of pattern in a match, where the pattern can fail.

Solutions

Language The statement for p The mechanism
Python x1, y1 = p sequence unpacking1
JavaScript const [x1, y1] = p; array destructuring2
TypeScript const [x1, y1] = p; array destructuring of a tuple type [number, number]
Rust let [x1, y1] = p; a slice pattern in a let statement34
C++ const auto [x1, y1] = p; a structured binding5
C# p is [var x1, var y1] a list pattern6
Java case Segment(Point(int x1, int y1), Point(int x2, int y2)) -> a nested record pattern7
Go x1, y1 := p[0], p[1] a tuple assignment8
C int x1 = p[0], y1 = p[1]; none; one index for each name
Bash read -r x1 y1 on the line of the array read splits a line into words9
  • Python. The tutorial names the statement x, y, z = t: "This is called, appropriately enough, sequence unpacking and works for any sequence on the right-hand side"1. So x1, y1 = p works for a list, as it works for a tuple.
  • JavaScript and TypeScript. "The destructuring syntax is a JavaScript syntax that makes it possible to unpack values from arrays, or properties from objects, into distinct variables"2. In TypeScript, the type [number, number] tells the compiler that a point has two parts.
  • Rust. A let statement takes a pattern, in the form let PATTERN = EXPRESSION;, and "Rust compares the expression against the pattern and assigns any names it finds"3. The solution uses the array type [i32; 2], so the pattern [x1, y1] always matches: "Slice patterns are irrefutable when matching an array as long as each element is irrefutable"4. With a slice &[i32], the pattern can fail. A slice pattern on a slice "is irrefutable only in the form with a single .. rest pattern"4. A let statement accepts only a pattern that cannot fail10.
  • C++. A structured binding "Binds the specified names to subobjects or elements of the initializer"5. The solution uses std::array<int, 2>, so each point has exactly two elements, and the binding names both.
  • C#. A list pattern tests a sequence, and "a list pattern matches when each nested pattern matches the corresponding element of an input sequence"6. The pattern [var x1, var y1] also tests that the array has two elements, so the solution throws an exception for each other length. For tuples and records, C# also has a deconstruction, which assigns the parts of a value "to multiple variables in a single operation"11, such as var (x1, y1) = point;.
  • Java. Java has no destructuring statement. The solution puts the two points in records, and a record pattern in a switch takes them apart. JEP 440 adds "record patterns to deconstruct record values", and "Record patterns and type patterns can be nested"7. It is standard in Java 217.
  • Go. Go has no destructuring. "A tuple assignment assigns the individual elements of a multi-valued operation to a list of variables"8, so x1, y1 := p[0], p[1] gives the names in one statement. It still reads each part by its index.
  • C. C has no destructuring and no tuple assignment, so the solution declares each name with one index.
  • Bash. read puts the words of a line in names. It reads one line, and it will "split it into words as described above in Word Splitting, and assign the first word to the first name, the second word to the second name, and so on"9. The solution joins the array into one line, and read splits it again.

Objects and swaps

Destructuring also takes the properties of an object by name, and it can swap two variables. MDN states that "Without destructuring, swapping two values requires a temporary variable"2.

const point = { x: 3, y: -1 };
const { x, y } = point;

let a = 1;
let b = 3;
[a, b] = [b, a];

console.log(x, y, a, b);
Output
3 -1 3 1

Kotlin has the same statement for objects, the destructuring declaration: "A destructuring declaration creates multiple variables at once"12. It calls the functions component1(), component2() and so on of the object, and a data class declares them12.

Edge cases

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

  • same-point: the two points are equal, so the distance is 0.
  • negative: all the coordinates are negative. The absolute value makes each difference positive.
  • large: the coordinates are at the limits of the contract, -1000000 and 1000000. The distance is 4000000, which fits in a 32-bit integer.
  • The contract states that each point has exactly 2 items. The pitfalls show what a point with a different length does in each language.

Pitfalls

  • A missing element in JavaScript. JavaScript does not check the length. If the array has fewer elements than the pattern has names, "only the first N variables are assigned values. The values of the remaining variables will be undefined"2. A point with no y gives no error, but the distance becomes NaN:

This code runs but gives a wrong answer on purpose.

function manhattan(p, q) {
  const [x1, y1] = p;
  const [x2, y2] = q;
  return Math.abs(x1 - x2) + Math.abs(y1 - y2);
}

console.log(manhattan([1, 2], [4, 6]));
console.log(manhattan([1], [4, 6]));
Output
7
NaN

Check the length before you destructure a value from outside the program, or use a default value such as const [x1 = 0, y1 = 0] = p;.

  • A length mismatch in other languages. Python is strict: "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 list of 3 items makes x1, y1 = p raise a ValueError. Rust checks the length at compile time. "If the number of elements in the pattern doesn’t match the number of elements in the tuple, the overall type won’t match and we’ll get a compiler error"3:

This code does not compile, on purpose.

fn main() {
    let (x, y) = (1, 2, 3);
    println!("{x} {y}");
}
  • Extra words in Bash. read does not drop extra words: "If there are more words than names, the remaining words and their intervening delimiters are assigned to the last name"9. With the line 3 4 5, read -r x y sets y to 4 5, and the arithmetic then fails.
  • A refutable pattern in a binding. A let in Rust must take a pattern that always matches, because "Function parameters, let statements, and for loops can only accept irrefutable patterns"10. let [x1, y1] = p; compiles for the array [i32; 2], but not for a slice &[i32], because a slice can have each length. For a slice, use a match, or the let...else statement, which accepts a pattern that can fail10.

Code

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

manhattan.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/destructure-a-value/.

def manhattan(p: list[int], q: list[int]) -> int:
    """Return the Manhattan distance between the points p = [x, y] and q = [x, y]."""
    x1, y1 = p
    x2, y2 = q
    return abs(x1 - x2) + abs(y1 - y2)
test_manhattan.py 22 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/destructure-a-value/.

import pytest

from manhattan import manhattan

CASES = {
    "first": ([1, 2], [4, 6], 7),
    "on-a-line": ([0, 0], [10, 0], 10),
    "down-left": ([5, 5], [2, 1], 7),
    "mixed-signs": ([3, -1], [-2, 4], 10),
    "same-point": ([7, 7], [7, 7], 0),
    "negative": ([-3, -4], [-1, -1], 5),
    "large": ([1000000, -1000000], [-1000000, 1000000], 4000000),
}


@pytest.mark.parametrize("name", CASES)
def test_manhattan(name):
    p, q, want = CASES[name]
    assert manhattan(p, q) == want
manhattan.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/destructure-a-value/.

#include "manhattan.hpp"

#include <cstdlib>

int manhattan(const std::array<int, 2> &p, const std::array<int, 2> &q) {
    // Structured bindings give a name to each element of the array.
    const auto [x1, y1] = p;
    const auto [x2, y2] = q;
    return std::abs(x1 - x2) + std::abs(y1 - y2);
}
manhattan.hpp 10 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/destructure-a-value/.

#pragma once

#include <array>

// manhattan returns the Manhattan distance between the points p = {x, y} and
// q = {x, y}.
int manhattan(const std::array<int, 2> &p, const std::array<int, 2> &q);
test_manhattan.cpp 32 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/destructure-a-value/.

#include "manhattan.hpp"

#include <array>
#include <iostream>
#include <string_view>

static int failures = 0;

static void check(std::string_view name, const std::array<int, 2> &p, const std::array<int, 2> &q, int want) {
    if (manhattan(p, q) != want) {
        std::cerr << "case " << name << " failed\n";
        failures++;
    }
}

int main() {
    check("first", {1, 2}, {4, 6}, 7);
    check("on-a-line", {0, 0}, {10, 0}, 10);
    check("down-left", {5, 5}, {2, 1}, 7);
    check("mixed-signs", {3, -1}, {-2, 4}, 10);
    check("same-point", {7, 7}, {7, 7}, 0);
    check("negative", {-3, -4}, {-1, -1}, 5);
    check("large", {1000000, -1000000}, {-1000000, 1000000}, 4000000);
    if (failures > 0) {
        return 1;
    }
    std::cout << "all cases pass\n";
    return 0;
}
Manhattan.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/destructure-a-value/.

final class Manhattan {
  private Manhattan() {}

  private record Point(int x, int y) {}

  private record Segment(Point from, Point to) {}

  /** Returns the Manhattan distance between the points p = {x, y} and q = {x, y}. */
  static int manhattan(int[] p, int[] q) {
    Segment s = new Segment(new Point(p[0], p[1]), new Point(q[0], q[1]));
    // A nested record pattern takes the segment and both points apart at once.
    return switch (s) {
      case Segment(Point(int x1, int y1), Point(int x2, int y2)) ->
          Math.abs(x1 - x2) + Math.abs(y1 - y2);
    };
  }
}
ManhattanTest.java 28 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/destructure-a-value/.

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

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 ManhattanTest {
  static Stream<Arguments> cases() {
    return Stream.of(
        Arguments.of("first", new int[] {1, 2}, new int[] {4, 6}, 7),
        Arguments.of("on-a-line", new int[] {0, 0}, new int[] {10, 0}, 10),
        Arguments.of("down-left", new int[] {5, 5}, new int[] {2, 1}, 7),
        Arguments.of("mixed-signs", new int[] {3, -1}, new int[] {-2, 4}, 10),
        Arguments.of("same-point", new int[] {7, 7}, new int[] {7, 7}, 0),
        Arguments.of("negative", new int[] {-3, -4}, new int[] {-1, -1}, 5),
        Arguments.of("large", new int[] {1000000, -1000000}, new int[] {-1000000, 1000000}, 4000000));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("cases")
  void manhattan(String name, int[] p, int[] q, int want) {
    assertEquals(want, Manhattan.manhattan(p, q), name);
  }
}
manhattan.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/destructure-a-value/.

#include "manhattan.h"

#include <stdlib.h>

int manhattan(const int p[2], const int q[2]) {
    // C has no destructuring, so each name gets one element by its index.
    int x1 = p[0], y1 = p[1];
    int x2 = q[0], y2 = q[1];
    return abs(x1 - x2) + abs(y1 - y2);
}
manhattan.h 11 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/destructure-a-value/.

#ifndef MANHATTAN_H
#define MANHATTAN_H

// manhattan returns the Manhattan distance between the points p = {x, y} and
// q = {x, y}.
int manhattan(const int p[2], const int q[2]);

#endif
test_manhattan.c 30 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/destructure-a-value/.

#include "manhattan.h"

#include <stdio.h>

static int failures = 0;

static void check(const char *name, const int p[2], const int q[2], int want) {
    if (manhattan(p, q) != want) {
        fprintf(stderr, "case %s failed\n", name);
        failures++;
    }
}

int main(void) {
    check("first", (const int[]){1, 2}, (const int[]){4, 6}, 7);
    check("on-a-line", (const int[]){0, 0}, (const int[]){10, 0}, 10);
    check("down-left", (const int[]){5, 5}, (const int[]){2, 1}, 7);
    check("mixed-signs", (const int[]){3, -1}, (const int[]){-2, 4}, 10);
    check("same-point", (const int[]){7, 7}, (const int[]){7, 7}, 0);
    check("negative", (const int[]){-3, -4}, (const int[]){-1, -1}, 5);
    check("large", (const int[]){1000000, -1000000}, (const int[]){-1000000, 1000000}, 4000000);
    if (failures > 0) {
        return 1;
    }
    printf("all cases pass\n");
    return 0;
}
Manhattan.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/destructure-a-value/.

using System;

public static class Manhattan
{
    // Returns the Manhattan distance between the points p = [x, y] and q = [x, y].
    public static int Distance(int[] p, int[] q)
    {
        // A list pattern tests the length and names the elements in one step.
        if (p is [var x1, var y1] && q is [var x2, var y2])
        {
            return Math.Abs(x1 - x2) + Math.Abs(y1 - y2);
        }
        throw new ArgumentException("a point has exactly two coordinates");
    }
}
ManhattanTests.cs 26 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/destructure-a-value/.

using Xunit;

public sealed class ManhattanTests
{
    public static TheoryData<string, int[], int[], int> Cases => new()
    {
        { "first", new[] { 1, 2 }, new[] { 4, 6 }, 7 },
        { "on-a-line", new[] { 0, 0 }, new[] { 10, 0 }, 10 },
        { "down-left", new[] { 5, 5 }, new[] { 2, 1 }, 7 },
        { "mixed-signs", new[] { 3, -1 }, new[] { -2, 4 }, 10 },
        { "same-point", new[] { 7, 7 }, new[] { 7, 7 }, 0 },
        { "negative", new[] { -3, -4 }, new[] { -1, -1 }, 5 },
        { "large", new[] { 1000000, -1000000 }, new[] { -1000000, 1000000 }, 4000000 },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void Check(string name, int[] p, int[] q, int want)
    {
        Assert.NotNull(name);
        Assert.Equal(want, Manhattan.Distance(p, q));
    }
}
manhattan.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/destructure-a-value/.

/**
 * Returns the Manhattan distance between the points p = [x, y] and q = [x, y].
 * @param {number[]} p
 * @param {number[]} q
 * @returns {number}
 */
export function manhattan(p, q) {
  const [x1, y1] = p;
  const [x2, y2] = q;
  return Math.abs(x1 - x2) + Math.abs(y1 - y2);
}
manhattan.test.js 23 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/destructure-a-value/.

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

import { manhattan } from "./manhattan.js";

const cases = [
  ["first", [1, 2], [4, 6], 7],
  ["on-a-line", [0, 0], [10, 0], 10],
  ["down-left", [5, 5], [2, 1], 7],
  ["mixed-signs", [3, -1], [-2, 4], 10],
  ["same-point", [7, 7], [7, 7], 0],
  ["negative", [-3, -4], [-1, -1], 5],
  ["large", [1000000, -1000000], [-1000000, 1000000], 4000000],
];

for (const [name, p, q, want] of cases) {
  test(name, () => {
    assert.equal(manhattan(p, q), want);
  });
}
manhattan.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/destructure-a-value/.

/** A point as a pair [x, y]. */
export type Point = [number, number];

/** Returns the Manhattan distance between the points p and q. */
export function manhattan(p: Point, q: Point): number {
  const [x1, y1] = p;
  const [x2, y2] = q;
  return Math.abs(x1 - x2) + Math.abs(y1 - y2);
}
manhattan.test.ts 23 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/destructure-a-value/.

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

import { manhattan, type Point } from "./manhattan.ts";

const cases: [string, Point, Point, number][] = [
  ["first", [1, 2], [4, 6], 7],
  ["on-a-line", [0, 0], [10, 0], 10],
  ["down-left", [5, 5], [2, 1], 7],
  ["mixed-signs", [3, -1], [-2, 4], 10],
  ["same-point", [7, 7], [7, 7], 0],
  ["negative", [-3, -4], [-1, -1], 5],
  ["large", [1000000, -1000000], [-1000000, 1000000], 4000000],
];

for (const [name, p, q, want] of cases) {
  test(name, () => {
    assert.equal(manhattan(p, q), want);
  });
}
manhattan.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/destructure-a-value/.

// Package manhattan computes the Manhattan distance between two points.
package manhattan

// Manhattan returns the Manhattan distance between the points p = {x, y} and
// q = {x, y}.
func Manhattan(p, q [2]int) int {
	// Go has no destructuring. A tuple assignment gives one name to each
	// element.
	x1, y1 := p[0], p[1]
	x2, y2 := q[0], q[1]
	return abs(x1-x2) + abs(y1-y2)
}

func abs(n int) int {
	if n < 0 {
		return -n
	}
	return n
}
manhattan_test.go 28 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/destructure-a-value/.

package manhattan

import "testing"

var cases = []struct {
	name string
	p, q [2]int
	want int
}{
	{"first", [2]int{1, 2}, [2]int{4, 6}, 7},
	{"on-a-line", [2]int{0, 0}, [2]int{10, 0}, 10},
	{"down-left", [2]int{5, 5}, [2]int{2, 1}, 7},
	{"mixed-signs", [2]int{3, -1}, [2]int{-2, 4}, 10},
	{"same-point", [2]int{7, 7}, [2]int{7, 7}, 0},
	{"negative", [2]int{-3, -4}, [2]int{-1, -1}, 5},
	{"large", [2]int{1000000, -1000000}, [2]int{-1000000, 1000000}, 4000000},
}

func TestManhattan(t *testing.T) {
	for _, c := range cases {
		if got := Manhattan(c.p, c.q); got != c.want {
			t.Errorf("%s: got %d, want %d", c.name, got, c.want)
		}
	}
}
manhattan.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/destructure-a-value/.

/// Returns the Manhattan distance between the points p = [x, y] and q = [x, y].
pub fn manhattan(p: [i32; 2], q: [i32; 2]) -> i32 {
    // An array of fixed size always matches [x, y], so let can take it apart.
    let [x1, y1] = p;
    let [x2, y2] = q;
    (x1 - x2).abs() + (y1 - y2).abs()
}
tests/manhattan_test.rs 20 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/destructure-a-value/.

use algo_destructure_a_value::manhattan;

#[test]
fn cases() {
    let cases: &[(&str, [i32; 2], [i32; 2], i32)] = &[
        ("first", [1, 2], [4, 6], 7),
        ("on-a-line", [0, 0], [10, 0], 10),
        ("down-left", [5, 5], [2, 1], 7),
        ("mixed-signs", [3, -1], [-2, 4], 10),
        ("same-point", [7, 7], [7, 7], 0),
        ("negative", [-3, -4], [-1, -1], 5),
        ("large", [1000000, -1000000], [-1000000, 1000000], 4000000),
    ];
    for &(name, p, q, want) in cases {
        assert_eq!(manhattan(p, q), want, "{name}");
    }
}
manhattan.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/destructure-a-value/.

# manhattan P Q
# Takes the names of two arrays (x y) and prints their Manhattan distance.
manhattan() {
  local -n manhattan_p=$1 manhattan_q=$2
  local x1 y1 x2 y2 dx dy
  # read splits a line into words and gives one word to each name.
  read -r x1 y1 <<<"${manhattan_p[*]}"
  read -r x2 y2 <<<"${manhattan_q[*]}"
  dx=$((x1 - x2))
  dy=$((y1 - y2))
  printf '%s\n' "$((${dx#-} + ${dy#-}))"
}
test_manhattan.bats 55 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/destructure-a-value/.

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

check() { # check WANT (the points are the arrays p and q)
  local got
  got=$(manhattan p q)
  [ "$got" = "$1" ] || { printf 'got:  %s\nwant: %s\n' "$got" "$1"; return 1; }
}

@test "first" {
  p=(1 2)
  q=(4 6)
  check 7
}

@test "on-a-line" {
  p=(0 0)
  q=(10 0)
  check 10
}

@test "down-left" {
  p=(5 5)
  q=(2 1)
  check 7
}

@test "mixed-signs" {
  p=(3 -1)
  q=(-2 4)
  check 10
}

@test "same-point" {
  p=(7 7)
  q=(7 7)
  check 0
}

@test "negative" {
  p=(-3 -4)
  q=(-1 -1)
  check 5
}

@test "large" {
  p=(1000000 -1000000)
  q=(-1000000 1000000)
  check 4000000
}

References

  1. Data Structures, The Python Tutorial, 5.3 Tuples and Sequences
  2. Destructuring, MDN Web Docs, Description; Destructuring with more elements than the source; Swapping variables
  3. All the Places Patterns Can Be Used, The Rust Programming Language, let Statements
  4. Patterns, The Rust Reference, Slice patterns
  5. Structured binding declaration, cppreference.com, the first paragraph
  6. Pattern matching, C# language reference, List patterns
  7. JEP 440: Record Patterns, Summary; Pattern matching and records; the header (Release 21)
  8. The Go Programming Language Specification, Assignment statements
  9. Bash Builtin Commands, Bash Reference Manual, read
  10. Refutability: Whether a Pattern Might Fail to Match, The Rust Programming Language, the first paragraphs
  11. Deconstructing tuples and other types, C# fundamentals, the first paragraph
  12. Destructuring declarations, Kotlin documentation, the first paragraphs

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