Programming Search⌘K

Conceptadvanced

Refutable and irrefutable patterns

Also called refutability, refutable pattern, irrefutable pattern, unconditional pattern, if let, while let, let else, let-else.

A pattern is refutable when it can fail to match a value, and irrefutable when it always matches. A binding such as let needs an irrefutable pattern; a test such as if let takes a refutable one.

Applies to
core-languages

Idea

A pattern tests a value and binds names. Some patterns cannot fail. The Rust Book states: "Patterns that will match for any possible value passed are irrefutable"1. A single name, such as x in let x = 5;, is irrefutable, "because x matches anything and therefore cannot fail to match"1. Other patterns can fail: "Patterns that can fail to match for some possible value are refutable"1. Some(x) is refutable, because the value can be None.

The difference decides where a pattern can go. A binding has no place to go when its pattern fails, so it needs an irrefutable pattern. A test has an else branch, so it can take a refutable pattern. This Rust program uses both kinds:

fn parse_pair(s: &str) -> Option<(i32, i32)> {
    // let-else: a refutable pattern, and an else block that returns.
    let Some((a, b)) = s.split_once(',') else {
        return None;
    };
    let (Ok(x), Ok(y)) = (a.trim().parse(), b.trim().parse()) else {
        return None;
    };
    Some((x, y))
}

fn main() {
    // let: an irrefutable tuple pattern.
    let point = (3, 4);
    let (x, y) = point;
    println!("x = {x}, y = {y}");

    // if let: a refutable pattern, and code for the match only.
    if let Some((a, b)) = parse_pair("5, 6") {
        println!("parsed {a} and {b}");
    }
    println!("{:?}", parse_pair("oops"));

    // while let: the loop runs while the pattern matches.
    let mut stack = vec![1, 2, 3];
    let mut popped = Vec::new();
    while let Some(top) = stack.pop() {
        popped.push(top);
    }
    println!("{popped:?}");
}
Output
x = 3, y = 4
parsed 5 and 6
None
[3, 2, 1]

How it works

  • Which patterns are irrefutable. The Rust Reference defines the two kinds: "A pattern is said to be refutable when it has the possibility of not being matched by the value it is being matched against. Irrefutable patterns, on the other hand, always match the value they are being matched against"2. A name and the wildcard are irrefutable: "The wildcard pattern is always irrefutable"2. A literal is refutable: "Literal patterns are always refutable"2. A compound pattern takes its kind from its parts: "The tuple pattern is refutable when one of its subpatterns is refutable"2.
  • The type decides. Refutability depends on the type of the value, not only on the pattern. A range pattern of an integer type is irrefutable when it covers the whole type: "For example, 0u8..=255u8 is irrefutable"2. "Slice patterns are irrefutable when matching an array as long as each element is irrefutable"2, because the length of an array is part of its type. On a slice, the length is not known, so the same pattern can fail.
  • Bindings take irrefutable patterns. "Function parameters, let statements, and for loops can only accept irrefutable patterns because the program cannot do anything meaningful when values don’t match"1. The Rust compiler rejects a refutable pattern in a let, with error E0005: "Patterns used to bind names must be irrefutable, that is, they must guarantee that a name will be extracted in all cases"3.
  • Tests take refutable patterns. "The if let and while let expressions and the let...else statement accept refutable and irrefutable patterns, but the compiler warns against irrefutable patterns"1, because a test that cannot fail is useless. A match takes refutable patterns in its arms, but the arms together must be exhaustive.
  • let-else. A let statement can have an else block. The Rust Reference states: "If an else block is not present, the pattern must be irrefutable. If an else block is present, the pattern may be refutable"4. "The else block must always diverge"4: it must return, break, continue or panic, because the names of the pattern do not exist after a failed match.

In languages

LanguageVerdictNote
PythonNative
C++Absent
JavaNative
CAbsent
C#Native
JavaScriptAbsent
TypeScriptAbsent
GoIdiom
RustNative
KotlinIdiomA destructuring declaration such as `val (a, b) = pair` has no test; it calls the componentN() functions. A test that can fail is an `is` check in `if` or `when`, with a smart cast. Kotlin has no form like let-else. No example file exists because kotlinc is not installed.
SQLAbsentSQL has no patterns that bind names. No example file exists.
BashAbsent
PowerShellAbsentPowerShell has no patterns that bind names. Multiple assignment such as `$a, $b = 1, 2` has no test. No example file exists because pwsh is not installed.
HTMLDoes not applyHTML has no patterns.
CSSDoes not applyCSS has no patterns that bind names.
Regular expressionsDoes not applyA regular expression can fail to match, but it is not a pattern in a binding of a programming language.
Language Where a pattern must not fail Where a pattern can fail A failed binding gives
Rust let, function parameters, for1 match, if let, while let, let...else1 a compile-time error (E0005)3
Python an assignment such as a, b = t, a for target case5 an exception at run time
JavaScript, TypeScript destructuring none undefined for a missing element; a TypeError for null6
Java none; patterns appear only in tests instanceof, switch7 no binding form
C# a deconstruction, which "assigns the individual parts of a value"8 to variables is, switch no test; each part is assigned
Haskell a pattern binding in let and where, made lazy9 function equations, case9 an error when a name is used
  • Rust. The compiler checks refutability for each place. A let with Some(y) gives "refutable pattern in local binding: None not covered"3.
  • Python. Python checks a binding at run time. "Sequence unpacking requires that there are as many variables on the left side of the equals sign as there are elements in the sequence"10, and an assignment that breaks this rule raises an exception. In a match, the language reference names a match-all case: "A case block is considered irrefutable if it has no guard and its pattern is irrefutable"5, and "A match statement may have at most one irrefutable case block, and it must be last"5.
  • JavaScript. Array destructuring does not fail when the array is short: "The values of the remaining variables will be undefined"6. But "destructuring null or undefined throws a TypeError"6.
  • Java. The JLS does not use the word irrefutable. It calls such a pattern unconditional: "A pattern p is said to be unconditional for a type T if it can be determined at compile time that every value of type T will match p"7.
  • Haskell. The Haskell report also splits patterns into the two kinds. "Matching an irrefutable pattern is non-strict: the pattern matches even if the value to be matched is ⊥. Matching a refutable pattern is strict"9. A pattern of the form ~apat is irrefutable "whether or not apat is irrefutable"9: the match is deferred until a name is used.
PythonGitHub
for line in ["width=80", "oops", "height=24"]:
    match line.split("=", 1):
        case [key, value]:
            print(f"{key} -> {value}")
        case _:
            print(f"skip: {line}")
Output
width -> 80
skip: oops
height -> 24
  • Verdict: native. The sequence pattern [key, value] is refutable: it fails for a list of one item. The wildcard _ is irrefutable, so its case block must be the last one. A plain assignment key, value = parts has no test; it raises an exception when the lengths differ.
#include <iostream>
#include <string>
#include <utility>

int main() {
    for (std::string line : {"width=80", "oops", "height=24"}) {
        auto eq = line.find('=');
        if (eq == std::string::npos) {
            std::cout << "skip: " << line << "\n";
            continue;
        }
        // A structured binding takes the pair apart; it has no test.
        auto [key, value] = std::pair{line.substr(0, eq), line.substr(eq + 1)};
        std::cout << key << " -> " << value << "\n";
    }
}
Output
width -> 80
skip: oops
height -> 24
  • Verdict: absent. C++ has no patterns that can fail. A structured binding names the parts of a pair or an array without a test, so the program tests find before the binding.
JavaGitHub
public class Main {
    record Pair(String key, String value) {}

    static Pair parse(String line) {
        int i = line.indexOf('=');
        return i < 0 ? null : new Pair(line.substring(0, i), line.substring(i + 1));
    }

    public static void main(String[] args) {
        for (String line : new String[] {"width=80", "oops", "height=24"}) {
            // A record pattern after instanceof fails for null.
            if (parse(line) instanceof Pair(String key, String value)) {
                System.out.println(key + " -> " + value);
            } else {
                System.out.println("skip: " + line);
            }
        }
    }
}
Output
width -> 80
skip: oops
height -> 24
  • Verdict: native. Java uses patterns only in instanceof and in switch, where a failed match is handled. A record pattern does not match null, so parse returns null for a line without =. The JLS calls a pattern that each value of a type matches unconditional.
#include <stdio.h>
#include <string.h>

int main(void) {
    const char *lines[] = {"width=80", "oops", "height=24"};
    for (int i = 0; i < 3; i++) {
        const char *eq = strchr(lines[i], '=');
        if (eq == NULL) {
            printf("skip: %s\n", lines[i]);
            continue;
        }
        printf("%.*s -> %s\n", (int)(eq - lines[i]), lines[i], eq + 1);
    }
    return 0;
}
Output
width -> 80
skip: oops
height -> 24
  • Verdict: absent. C has no patterns. The program tests the result of strchr for NULL, and then reads the two parts by position.
using System;

foreach (var line in new[] { "width=80", "oops", "height=24" })
{
    // A list pattern is refutable: it fails when the array has another length.
    if (line.Split('=', 2) is [var key, var value])
    {
        Console.WriteLine($"{key} -> {value}");
    }
    else
    {
        Console.WriteLine($"skip: {line}");
    }
}
Output
width -> 80
skip: oops
height -> 24
  • Verdict: native. A pattern after is can fail, and the if handles the failure. The list pattern [var key, var value] matches only an array of two elements. A deconstruction such as var (a, b) = pair; takes a tuple apart without a test.
JavaScriptGitHub
for (const line of ["width=80", "oops", "height=24"]) {
  // Array destructuring never fails: a missing element is undefined.
  const [key, value] = line.split("=", 2);
  if (value === undefined) {
    console.log(`skip: ${line}`);
    continue;
  }
  console.log(`${key} -> ${value}`);
}
Output
width -> 80
skip: oops
height -> 24
  • Verdict: absent. JavaScript has no patterns that can fail and no match statement. Array destructuring gives undefined for a missing element, so the program tests the value after the destructuring. Destructuring null or undefined throws a TypeError.
TypeScriptGitHub
for (const line of ["width=80", "oops", "height=24"]) {
  // Array destructuring never fails: a missing element is undefined.
  const [key, value]: (string | undefined)[] = line.split("=", 2);
  if (value === undefined) {
    console.log(`skip: ${line}`);
    continue;
  }
  console.log(`${key} -> ${value}`);
}
Output
width -> 80
skip: oops
height -> 24
  • Verdict: absent. As in JavaScript, array destructuring never fails, and a missing element is undefined. The type annotation makes the compiler require the test for undefined.
package main

import (
	"fmt"
	"strings"
)

func main() {
	for _, line := range []string{"width=80", "oops", "height=24"} {
		key, value, ok := strings.Cut(line, "=")
		if !ok {
			fmt.Println("skip: " + line)
			continue
		}
		fmt.Println(key + " -> " + value)
	}
}
Output
width -> 80
skip: oops
height -> 24
  • Verdict: idiom. Go has no patterns. A function that can fail returns an extra boolean, and the program tests it: here strings.Cut returns ok. The assignment of three results never fails.
RustGitHub
fn main() {
    for line in ["width=80", "oops", "height=24"] {
        // A refutable pattern: split_once can return None.
        let Some(pair) = line.split_once('=') else {
            println!("skip: {line}");
            continue;
        };
        // An irrefutable pattern: each pair has two parts.
        let (key, value) = pair;
        println!("{key} -> {value}");
    }
}
Output
width -> 80
skip: oops
height -> 24
  • Verdict: native. A plain let takes only an irrefutable pattern, such as the tuple pattern (key, value). The pattern Some(pair) is refutable, so it needs let...else, if let or match. The else block must diverge, here with continue.
BashGitHub
for line in width=80 oops height=24; do
  case $line in
    *=*) echo "${line%%=*} -> ${line#*=}" ;;
    *) echo "skip: $line" ;;
  esac
done
Output
width -> 80
skip: oops
height -> 24
  • Verdict: absent. A case glob such as *=* can fail, but it binds no names. The clause takes the parts with parameter expansion. The last pattern * matches each string.
  • if let and exhaustiveness. if let handles one pattern and ignores the others. The Rust Book warns: "you lose the exhaustive checking match enforces that ensures that you aren’t forgetting to handle any cases"11. Exhaustive matching explains that check.
  • while let. "the while let conditional loop allows a while loop to run for as long as a pattern continues to match"12. A loop that pops a stack or reads from a channel ends when the pattern fails.
  • Destructuring. A binding with an irrefutable pattern takes a value apart. Destructure a value shows this in each language.
  • Lazy patterns. In Haskell, "Pattern bindings are matched lazily; an implicit ~ makes these patterns irrefutable"9. So a refutable pattern in a let does not fail when it is bound, but when a name from it is first used.

Pitfalls

A refutable pattern in a let

A let cannot handle a failed match, so Rust rejects a refutable pattern there:

This code does not compile, on purpose.

fn main() {
    let input: Option<i32> = Some(1);
    let Some(n) = input;
    println!("{n}");
}

Use if let, match, or let...else with a block that diverges. E0005 gives the same advice: "you probably need to use a match or if let"3.

A binding that fails at run time

In Python, an assignment with several targets is a binding with no else branch. It fails at run time when the lengths differ:

def parse(line):
    key, value = line.split("=")
    return key, value


for line in ["width=80", "oops"]:
    try:
        print(parse(line))
    except ValueError as e:
        print(type(e).__name__)
Output
('width', '80')
ValueError

Use a match with a sequence pattern, which can fail and go on to the next case, or test the length first.

An irrefutable pattern in a test

An irrefutable pattern in if let or while let always matches, so the else branch never runs and a while let never ends. Rust warns about it, because a pattern in these places is "intended to handle possible failure"1. In Python, an irrefutable case before other cases is an error, because the case blocks after it can never run5.

A let-else block that does not diverge

The else block of let...else must leave the current block, because "The else block must always diverge"4. A block that only prints a message, and then goes on, does not compile. End it with return, break, continue or a panic.

Cost

  • Bindings cost nothing extra. An irrefutable pattern needs no test at run time. The JLS says of an unconditional pattern that "the run time, testing aspect of pattern matching could be elided"7.
  • Tests cost a test. A pattern that is not unconditional keeps its test at run time, and each failed test sends control to the next arm or the else branch.

History

  • Haskell 2010. The Haskell report defines irrefutable and refutable patterns, and the ~apat form that makes a pattern irrefutable9.
  • 2020. PEP 634, created on 12 September 2020 for Python 3.10, defined irrefutable case blocks: "A pattern is considered irrefutable if we can prove from its syntax alone that it will always succeed"13. It also made the rule that such a case block must be last13.
  • 2022. Rust 1.65, released on 3 November 2022, added let-else. Before it, "Normal let statements can only use irrefutable patterns, statically known to always match"14. "With let-else, a refutable pattern can match and bind variables in the surrounding scope like a normal let, or else diverge (e.g. break, return, panic!) when the pattern doesn't match"14.

References

  1. Refutability: Whether a Pattern Might Fail to Match, The Rust Programming Language, the whole section
  2. Patterns, The Rust Reference, Refutability; the notes on refutability in each kind of pattern
  3. Error code E0005, Rust error codes index, the whole page
  4. Statements, The Rust Reference, let statements
  5. Compound statements, The Python Language Reference, 8.6.3 Irrefutable Case Blocks
  6. Destructuring, MDN Web Docs, Destructuring with more elements than the source; Destructuring primitive values
  7. The Java Language Specification, Java SE 25 Edition, 14.30.3 Properties of Patterns
  8. Deconstructing tuples and other types, C# fundamentals, the first paragraph
  9. Haskell 2010 Language Report, Chapter 3 Expressions, 3.17.2 Informal Semantics of Pattern Matching
  10. Data Structures, The Python Tutorial, 5.3 Tuples and Sequences
  11. Concise Control Flow with if let and let...else, The Rust Programming Language, the first part
  12. All the Places Patterns Can Be Used, The Rust Programming Language, while let Conditional Loops; Function Parameters
  13. PEP 634: Structural Pattern Matching: Specification, Irrefutable case blocks; the header (Created 12-Sep-2020, Python-Version 3.10)
  14. Announcing Rust 1.65.0, The Rust Blog, let-else statements; the date (Nov. 3, 2022)

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)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/BM4PBY/text.yaml