Programming Search⌘K

Taskcore

Pattern match on a value

Also called match on a tuple, match with guards, match on an enum, classify a point, tuple patterns, case guards.

Name the place of a point in the plane with one match on the pair (x, y): tuple patterns for the axes, a guard for the diagonal, and a wildcard for the rest.

Task

Match one value against a list of patterns, and use a guard where a pattern alone cannot say what you need. The function classify(x, y) names the place of the point (x, y):

  • "origin" when x and y are both 0,
  • "x-axis" when y is 0, and x is not,
  • "y-axis" when x is 0, and y is not,
  • "diagonal" when x equals y, and the point is not the origin,
  • "other" for each other point.

For example, classify(5, 0) is "x-axis" and classify(4, 4) is "diagonal".

The value to match is the pair (x, y). The first three cases are patterns with literals and wildcards. The fourth case needs a guard, because a pattern cannot compare x with y. Pattern matching explains patterns, guards and exhaustiveness. This task applies them to a tuple. The last part of the solutions also matches on an enum.

Solutions

Language The match The pattern for the x-axis The guard
Python match (x, y): case (_, 0): case (a, b) if a == b:1
Rust match (x, y) (_, 0) => (a, b) if a == b =>2
C# (x, y) switch (_, 0) =>3 var (a, b) when a == b =>4
Java switch (new Point(x, y)) case Point(int a, int b) when b == 0 ->5 case Point(int a, int b) when a == b ->6
Go switch { case y == 0: case x == y:7
Bash case "$1,$2" in *,0)8 an if in the last clause
JavaScript, TypeScript, C, C++ none; an if chain if (y === 0) or if (y == 0) if (x === y) or if (x == y)
  • Python. A tuple pattern looks like the tuple it matches. The tutorial shows the same idea for a point: "Patterns can look like unpacking assignments, and can be used to bind variables"1. In case (_, 0):, the _ matches any x, and the 0 matches only a y of 0. For the diagonal, "We can add an if clause to a pattern, known as a “guard”. If the guard is false, match goes on to try the next case block"1.
  • Rust. The solution matches the tuple (x, y). "A match guard is an additional if condition, specified after the pattern in a match arm, that must also match for that arm to be chosen"2. The Rust Reference states that a guard comes after the pattern, "following the if keyword"9. The last arm is _, because a match must cover each value.
  • C#. A switch expression can match a tuple with a positional pattern: "You can also match expressions of tuple types against positional patterns"3. "A case guard is another condition that must be satisfied together with a matched pattern"4, and it comes after the when keyword4.
  • Java. Java has no tuples, so the solution puts x and y in a record. A record pattern such as Point(int a, int b) takes the record apart. JEP 440 adds "record patterns to deconstruct record values"5. JEP 441 allows "when clauses in switch blocks to specify guards to pattern case labels"6. Both are standard in Java 2156. In this solution, each case except the last has a guard.
  • Go. Go has no pattern matching. A switch with no expression tests each case as a condition, because "A missing switch expression is equivalent to the boolean value true"7.
  • JavaScript and TypeScript. JavaScript has no match statement. A TC39 proposal for pattern matching exists, but it is at stage 110. The solution tests the conditions in order with an if chain.
  • C and C++. These languages have no pattern matching on values, so the solution is an if chain.
  • Bash. A case command matches a string against glob patterns, "according to the rules described below in Pattern Matching"8. The solution makes the string x,y, so *,0 matches each point on the x-axis. A glob cannot compare two parts of the string, so the last clause uses an if in place of a guard.

A match on an enum

A match can also take apart an enum with data, and a guard can refine each variant. The Rust Book states that "the pattern to destructure an enum corresponds to the way the data stored within the enum is defined"2. Here a guard separates a square from the other rectangles:

enum Shape {
    Circle(f64),
    Rect(f64, f64),
}

fn describe(shape: &Shape) -> String {
    match shape {
        Shape::Circle(r) if *r == 0.0 => "a point".to_string(),
        Shape::Circle(r) => format!("a circle of radius {r}"),
        Shape::Rect(w, h) if w == h => format!("a square of side {w}"),
        Shape::Rect(w, h) => format!("a rectangle of {w} by {h}"),
    }
}

fn main() {
    let shapes = [
        Shape::Circle(0.0),
        Shape::Circle(1.5),
        Shape::Rect(2.0, 2.0),
        Shape::Rect(2.0, 3.0),
    ];
    for shape in &shapes {
        println!("{}", describe(shape));
    }
}
Output
a point
a circle of radius 1.5
a square of side 2
a rectangle of 2 by 3

Edge cases

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

  • origin: the point (0, 0) is on both axes and on the diagonal. The case for the origin must come first, or a later case takes the point.
  • negative-x-axis and negative-diagonal: negative coordinates. The patterns test only for 0, so the sign does not change the result.
  • anti-diagonal: (3, -3) has the same size of x and y, but not the same value, so it is "other".
  • one-one: the point nearest to the origin on the diagonal.

Pitfalls

  • A guard before a literal pattern. The cases are tried in order, so a wide case before a narrow case takes its values. Here the diagonal case comes first, and the origin is on the diagonal:

This code runs but gives a wrong answer on purpose.

def classify(x, y):
    match (x, y):
        case (a, b) if a == b:
            return "diagonal"
        case (0, 0):
            return "origin"
        case (_, 0):
            return "x-axis"
        case (0, _):
            return "y-axis"
        case _:
            return "other"


print(classify(0, 0), classify(4, 4), classify(5, 0))
Output
diagonal diagonal x-axis

Put the narrow case (0, 0) first.

  • A guard and exhaustiveness. A compiler that checks exhaustiveness does not look inside a guard. The Rust Book states that "the compiler doesn’t try to check for exhaustiveness when match guard expressions are involved"2. These two guards cover each pair, but the match does not compile:

This code does not compile, on purpose.

fn classify(x: i32, y: i32) -> &'static str {
    match (x, y) {
        (a, b) if a == b => "diagonal",
        (a, b) if a != b => "not diagonal",
    }
}

fn main() {
    println!("{}", classify(1, 2));
}

The fix is an arm without a guard as the last arm, such as _ => "not diagonal".

  • A name that binds. In a pattern, a name such as a does not compare. It binds the value, and it matches each value. In the Python tutorial example, "the variable binds a value from the subject (point)"1. So case (a, 0): matches each point on the x-axis, and does not test that x equals some earlier variable a. To compare with a variable, use a guard, such as case (a, 0) if a == limit:.
  • The binding happens before the guard. In Python, "value capture happens before the guard is evaluated"1. So a case that fails its guard can still change a name. The language reference warns: "Do not rely on bindings being made for a failed match. Conversely, do not rely on variables remaining unchanged after a failed match"11. Use a name only in the case that bound it.

Code

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

classify.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/pattern-match-on-a-value/.

def classify(x: int, y: int) -> str:
    """Name the place of the point (x, y): origin, x-axis, y-axis, diagonal or other."""
    match (x, y):
        case (0, 0):
            return "origin"
        case (_, 0):
            return "x-axis"
        case (0, _):
            return "y-axis"
        case (a, b) if a == b:
            return "diagonal"
        case _:
            return "other"
test_classify.py 24 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/pattern-match-on-a-value/.

import pytest

from classify import classify

CASES = {
    "x-axis": (5, 0, "x-axis"),
    "y-axis": (0, -3, "y-axis"),
    "diagonal": (4, 4, "diagonal"),
    "other": (2, 7, "other"),
    "origin": (0, 0, "origin"),
    "negative-diagonal": (-2, -2, "diagonal"),
    "anti-diagonal": (3, -3, "other"),
    "negative-x-axis": (-7, 0, "x-axis"),
    "one-one": (1, 1, "diagonal"),
}


@pytest.mark.parametrize("name", CASES)
def test_classify(name):
    x, y, want = CASES[name]
    assert classify(x, y) == want
classify.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/pattern-match-on-a-value/.

#include "classify.hpp"

std::string classify(int x, int y) {
    // C++ has no pattern matching, so an if chain tests the cases in order.
    if (x == 0 && y == 0) {
        return "origin";
    }
    if (y == 0) {
        return "x-axis";
    }
    if (x == 0) {
        return "y-axis";
    }
    if (x == y) {
        return "diagonal";
    }
    return "other";
}
classify.hpp 10 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/pattern-match-on-a-value/.

#pragma once

#include <string>

// classify names the place of the point (x, y): origin, x-axis, y-axis,
// diagonal or other.
std::string classify(int x, int y);
test_classify.cpp 34 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/pattern-match-on-a-value/.

#include "classify.hpp"

#include <iostream>
#include <string>
#include <string_view>

static int failures = 0;

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

int main() {
    check("x-axis", 5, 0, "x-axis");
    check("y-axis", 0, -3, "y-axis");
    check("diagonal", 4, 4, "diagonal");
    check("other", 2, 7, "other");
    check("origin", 0, 0, "origin");
    check("negative-diagonal", -2, -2, "diagonal");
    check("anti-diagonal", 3, -3, "other");
    check("negative-x-axis", -7, 0, "x-axis");
    check("one-one", 1, 1, "diagonal");
    if (failures > 0) {
        return 1;
    }
    std::cout << "all cases pass\n";
    return 0;
}
Classify.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/pattern-match-on-a-value/.

final class Classify {
  private Classify() {}

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

  /** Names the place of the point (x, y): origin, x-axis, y-axis, diagonal or other. */
  static String classify(int x, int y) {
    // Record patterns take the point apart, and each when clause is a guard.
    return switch (new Point(x, y)) {
      case Point(int a, int b) when a == 0 && b == 0 -> "origin";
      case Point(int a, int b) when b == 0 -> "x-axis";
      case Point(int a, int b) when a == 0 -> "y-axis";
      case Point(int a, int b) when a == b -> "diagonal";
      case Point(int a, int b) -> "other";
    };
  }
}
ClassifyTest.java 30 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/pattern-match-on-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 ClassifyTest {
  static Stream<Arguments> cases() {
    return Stream.of(
        Arguments.of("x-axis", 5, 0, "x-axis"),
        Arguments.of("y-axis", 0, -3, "y-axis"),
        Arguments.of("diagonal", 4, 4, "diagonal"),
        Arguments.of("other", 2, 7, "other"),
        Arguments.of("origin", 0, 0, "origin"),
        Arguments.of("negative-diagonal", -2, -2, "diagonal"),
        Arguments.of("anti-diagonal", 3, -3, "other"),
        Arguments.of("negative-x-axis", -7, 0, "x-axis"),
        Arguments.of("one-one", 1, 1, "diagonal"));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("cases")
  void classify(String name, int x, int y, String want) {
    assertEquals(want, Classify.classify(x, y), name);
  }
}
classify.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/pattern-match-on-a-value/.

#include "classify.h"

const char *classify(int x, int y) {
    // C has no pattern matching, so an if chain tests the cases in order.
    if (x == 0 && y == 0) {
        return "origin";
    }
    if (y == 0) {
        return "x-axis";
    }
    if (x == 0) {
        return "y-axis";
    }
    if (x == y) {
        return "diagonal";
    }
    return "other";
}
classify.h 11 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/pattern-match-on-a-value/.

#ifndef CLASSIFY_H
#define CLASSIFY_H

// classify names the place of the point (x, y): origin, x-axis, y-axis,
// diagonal or other. It returns a string literal; the caller must not free it.
const char *classify(int x, int y);

#endif
test_classify.c 33 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/pattern-match-on-a-value/.

#include "classify.h"

#include <stdio.h>
#include <string.h>

static int failures = 0;

static void check(const char *name, int x, int y, const char *want) {
    if (strcmp(classify(x, y), want) != 0) {
        fprintf(stderr, "case %s failed\n", name);
        failures++;
    }
}

int main(void) {
    check("x-axis", 5, 0, "x-axis");
    check("y-axis", 0, -3, "y-axis");
    check("diagonal", 4, 4, "diagonal");
    check("other", 2, 7, "other");
    check("origin", 0, 0, "origin");
    check("negative-diagonal", -2, -2, "diagonal");
    check("anti-diagonal", 3, -3, "other");
    check("negative-x-axis", -7, 0, "x-axis");
    check("one-one", 1, 1, "diagonal");
    if (failures > 0) {
        return 1;
    }
    printf("all cases pass\n");
    return 0;
}
PointClassifier.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/pattern-match-on-a-value/.

public static class PointClassifier
{
    // Names the place of the point (x, y): origin, x-axis, y-axis, diagonal or other.
    public static string Classify(int x, int y) => (x, y) switch
    {
        (0, 0) => "origin",
        (_, 0) => "x-axis",
        (0, _) => "y-axis",
        var (a, b) when a == b => "diagonal",
        _ => "other",
    };
}
PointClassifierTests.cs 28 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/pattern-match-on-a-value/.

using Xunit;

public sealed class PointClassifierTests
{
    public static TheoryData<string, int, int, string> Cases => new()
    {
        { "x-axis", 5, 0, "x-axis" },
        { "y-axis", 0, -3, "y-axis" },
        { "diagonal", 4, 4, "diagonal" },
        { "other", 2, 7, "other" },
        { "origin", 0, 0, "origin" },
        { "negative-diagonal", -2, -2, "diagonal" },
        { "anti-diagonal", 3, -3, "other" },
        { "negative-x-axis", -7, 0, "x-axis" },
        { "one-one", 1, 1, "diagonal" },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void Check(string name, int x, int y, string want)
    {
        Assert.NotNull(name);
        Assert.Equal(want, PointClassifier.Classify(x, y));
    }
}
classify.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/pattern-match-on-a-value/.

/**
 * Names the place of the point (x, y): origin, x-axis, y-axis, diagonal or other.
 * @param {number} x
 * @param {number} y
 * @returns {string}
 */
export function classify(x, y) {
  // JavaScript has no match statement, so an if chain tests the patterns in
  // order. The first test that is true gives the result.
  if (x === 0 && y === 0) {
    return "origin";
  }
  if (y === 0) {
    return "x-axis";
  }
  if (x === 0) {
    return "y-axis";
  }
  if (x === y) {
    return "diagonal";
  }
  return "other";
}
classify.test.js 25 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/pattern-match-on-a-value/.

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

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

const cases = [
  ["x-axis", 5, 0, "x-axis"],
  ["y-axis", 0, -3, "y-axis"],
  ["diagonal", 4, 4, "diagonal"],
  ["other", 2, 7, "other"],
  ["origin", 0, 0, "origin"],
  ["negative-diagonal", -2, -2, "diagonal"],
  ["anti-diagonal", 3, -3, "other"],
  ["negative-x-axis", -7, 0, "x-axis"],
  ["one-one", 1, 1, "diagonal"],
];

for (const [name, x, y, want] of cases) {
  test(name, () => {
    assert.equal(classify(x, y), want);
  });
}
classify.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/pattern-match-on-a-value/.

/** Names the place of the point (x, y): origin, x-axis, y-axis, diagonal or other. */
export function classify(x: number, y: number): string {
  // JavaScript has no match statement, so an if chain tests the patterns in
  // order. The first test that is true gives the result.
  if (x === 0 && y === 0) {
    return "origin";
  }
  if (y === 0) {
    return "x-axis";
  }
  if (x === 0) {
    return "y-axis";
  }
  if (x === y) {
    return "diagonal";
  }
  return "other";
}
classify.test.ts 25 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/pattern-match-on-a-value/.

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

import { classify } from "./classify.ts";

const cases: [string, number, number, string][] = [
  ["x-axis", 5, 0, "x-axis"],
  ["y-axis", 0, -3, "y-axis"],
  ["diagonal", 4, 4, "diagonal"],
  ["other", 2, 7, "other"],
  ["origin", 0, 0, "origin"],
  ["negative-diagonal", -2, -2, "diagonal"],
  ["anti-diagonal", 3, -3, "other"],
  ["negative-x-axis", -7, 0, "x-axis"],
  ["one-one", 1, 1, "diagonal"],
];

for (const [name, x, y, want] of cases) {
  test(name, () => {
    assert.equal(classify(x, y), want);
  });
}
classify.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/pattern-match-on-a-value/.

// Package classify names the place of a point in the plane.
package classify

// Classify names the place of the point (x, y): origin, x-axis, y-axis,
// diagonal or other.
func Classify(x, y int) string {
	// Go has no pattern matching. A switch with no expression tests each
	// case as a condition, in order.
	switch {
	case x == 0 && y == 0:
		return "origin"
	case y == 0:
		return "x-axis"
	case x == 0:
		return "y-axis"
	case x == y:
		return "diagonal"
	default:
		return "other"
	}
}
classify_test.go 30 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/pattern-match-on-a-value/.

package classify

import "testing"

var cases = []struct {
	name string
	x, y int
	want string
}{
	{"x-axis", 5, 0, "x-axis"},
	{"y-axis", 0, -3, "y-axis"},
	{"diagonal", 4, 4, "diagonal"},
	{"other", 2, 7, "other"},
	{"origin", 0, 0, "origin"},
	{"negative-diagonal", -2, -2, "diagonal"},
	{"anti-diagonal", 3, -3, "other"},
	{"negative-x-axis", -7, 0, "x-axis"},
	{"one-one", 1, 1, "diagonal"},
}

func TestClassify(t *testing.T) {
	for _, c := range cases {
		if got := Classify(c.x, c.y); got != c.want {
			t.Errorf("%s: got %q, want %q", c.name, got, c.want)
		}
	}
}
classify.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/pattern-match-on-a-value/.

/// Names the place of the point (x, y): origin, x-axis, y-axis, diagonal or other.
pub fn classify(x: i32, y: i32) -> &'static str {
    match (x, y) {
        (0, 0) => "origin",
        (_, 0) => "x-axis",
        (0, _) => "y-axis",
        (a, b) if a == b => "diagonal",
        _ => "other",
    }
}
tests/classify_test.rs 22 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/pattern-match-on-a-value/.

use algo_pattern_match_on_a_value::classify;

#[test]
fn cases() {
    let cases: &[(&str, i32, i32, &str)] = &[
        ("x-axis", 5, 0, "x-axis"),
        ("y-axis", 0, -3, "y-axis"),
        ("diagonal", 4, 4, "diagonal"),
        ("other", 2, 7, "other"),
        ("origin", 0, 0, "origin"),
        ("negative-diagonal", -2, -2, "diagonal"),
        ("anti-diagonal", 3, -3, "other"),
        ("negative-x-axis", -7, 0, "x-axis"),
        ("one-one", 1, 1, "diagonal"),
    ];
    for &(name, x, y, want) in cases {
        assert_eq!(classify(x, y), want, "{name}");
    }
}
classify.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/pattern-match-on-a-value/.

# classify X Y
# Prints the place of the point (X, Y): origin, x-axis, y-axis, diagonal or other.
classify() {
  # case matches the string "X,Y" against glob patterns, in order.
  case "$1,$2" in
    0,0)
      echo origin
      ;;
    *,0)
      echo x-axis
      ;;
    0,*)
      echo y-axis
      ;;
    *)
      # A glob cannot compare X with Y, so an if does the work of a guard.
      if (($1 == $2)); then
        echo diagonal
      else
        echo other
      fi
      ;;
  esac
}
test_classify.bats 23 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/pattern-match-on-a-value/.

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

check() { # check X Y WANT
  local got
  got=$(classify "$1" "$2")
  [ "$got" = "$3" ] || { printf 'got:  %s\nwant: %s\n' "$got" "$3"; return 1; }
}

@test "x-axis" { check 5 0 x-axis; }
@test "y-axis" { check 0 -3 y-axis; }
@test "diagonal" { check 4 4 diagonal; }
@test "other" { check 2 7 other; }
@test "origin" { check 0 0 origin; }
@test "negative-diagonal" { check -2 -2 diagonal; }
@test "anti-diagonal" { check 3 -3 other; }
@test "negative-x-axis" { check -7 0 x-axis; }
@test "one-one" { check 1 1 diagonal; }

References

  1. More Control Flow Tools, The Python Tutorial, 4.7 match Statements
  2. Pattern Syntax, The Rust Programming Language, Destructuring Enums; Adding Conditionals with Match Guards
  3. Pattern matching, C# language reference, Positional pattern
  4. switch expression, C# language reference, Case guards
  5. JEP 440: Record Patterns, Summary; the header (Release 21)
  6. JEP 441: Pattern Matching for switch, Case refinement; the header (Release 21)
  7. The Go Programming Language Specification, Expression switches
  8. Conditional Constructs, Bash Reference Manual, case
  9. The Rust Reference, Match expressions, Match guards
  10. ECMAScript Pattern Matching, TC39 proposal, README, Status
  11. Compound statements, The Python Language Reference, 8.6.1 Overview

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