# Vibe check: equality patterns

**URL:** <https://internals.rust-lang.org/t/vibe-check-equality-patterns/21775>\
**Category:** Uncategorized\
**Created:** [October 26, 2024, 8:20pm UTC](https://internals.rust-lang.org/t/vibe-check-equality-patterns/21775 "2024-10-26T20:20:36Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![Nadrieril](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/nadrieril/32/11435_2.png) [@Nadrieril](https://internals.rust-lang.org/u/Nadrieril)\
**Post date:** [October 26, 2024, 8:20pm UTC](https://internals.rust-lang.org/t/vibe-check-equality-patterns/21775/1 "2024-10-26T20:20:36Z")

</div>

Someone [recently suggested](https://github.com/rust-lang/rust/issues/132037) the following idea: we could allow patterns that repeat variables.

```rust
match ... {
    (a, a) => 1, // covers (true, true) and (false, false)
    (true, false) => 2,
    (false, true) => 3,
}

```

`(a, a)` would behave like `(a, b) if a == b` except it would work with exhaustiveness checking.

I did some reasearch. These patterns are called "nonlinear" (using "linear" in the resource sense, like in "linear types"). A bunch of languages have this feature including Erlang, Miranda, Prolog.

Ocaml and Haskell do not have them, and afaict the reasons boil down to:

- Not all values are comparable (see [here](https://www.mail-archive.com/haskell-cafe@haskell.org/msg59619.html)) -\> we can require `Eq`;
- The `==` implementation may differ from structural equality (see [here](https://stackoverflow.com/a/34956771), [here](https://www.mail-archive.com/haskell-cafe@haskell.org/msg62502.html)) -\> we can require recursive `StructuralEq`;
- This will be hard to specify (e.g. [here](https://www.mail-archive.com/haskell-cafe@haskell.org/msg59623.html)) -\> we can just compile `(a, a)` to `(a, a2) if a == a2`;
- This may be a typo -\> fair, exhaustiveness should catch common cases;
- This is a complicated feature -\> haha yep.

What I've not seen is discussion of how to check exhaustiveness for these patterns; I can't find anything in the literature. This seems to be the real complexity with this feature. I've thought about how to extend rust's exhaustiveness checker and I think I can reduce it to something like a multigraph coloring problem; not trivial but not impossible either.

How do we feel about that? Have you missed this feature before? Would it be worth the extra complexity?

---

<div class="post-metadata">

**Author:** ![quinedot](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/quinedot/32/7294_2.png) [@quinedot](https://internals.rust-lang.org/u/quinedot)\
**Post date:** [October 26, 2024, 8:48pm UTC](https://internals.rust-lang.org/t/vibe-check-equality-patterns/21775/2 "2024-10-26T20:48:52Z")

</div>

> [@Nadrieril](#):
>
> `(a, a)` would be sugar for `(a, b) if a == b` except it would work with exhaustiveness checking.

This is the crux of the question, isn't it? Guards would start participating in exhaustiveness checking.

If this starts working:

```rust
    match (bool1, bool2) {
        (a, a2) if a == a2 => {}
        (true, false) => {}
        (false, true) => {}
    }

```

Shouldn't this?

```rust
    match (bool1, bool2) {
        (a, a2) if a == a2 => {}
        (a, a2) if a != a2 => {}
    }

```

And then people will expect this to work even more than [they already do today:](https://github.com/rust-lang/rust/issues/129354)\[1\]

```rust
    match int {
        a if a > other_int => {}
        a if a < other_int => {}
        a if a == other_int => {}
    }

```

* * *

1. ignore the float aspect in the issue as that's just the first example I found; I've seen it on URLO before too

---

<div class="post-metadata">

**Author:** ![Nadrieril](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/nadrieril/32/11435_2.png) [@Nadrieril](https://internals.rust-lang.org/u/Nadrieril)\
**Post date:** [October 26, 2024, 8:54pm UTC](https://internals.rust-lang.org/t/vibe-check-equality-patterns/21775/3 "2024-10-26T20:54:22Z")

</div>

Ah, I shouldn't have said "sugar"; we can't have guards participating in exhaustiveness with any remote sense of consistency.

What I meant is: "`(a, a)` is a new pattern syntax that has the same runtime behavior as `(a, b) if a == b` and (as all patterns do) interacts with exhaustiveness".

---

<div class="post-metadata">

**Author:** ![quaternic](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/quaternic/32/10440_2.png) [@quaternic](https://internals.rust-lang.org/u/quaternic)\
**Post date:** [October 26, 2024, 9:28pm UTC](https://internals.rust-lang.org/t/vibe-check-equality-patterns/21775/4 "2024-10-26T21:28:55Z")

</div>

> [@Nadrieril](#):
>
> - The `==` implementation may differ from structural equality (see [here](https://stackoverflow.com/a/34956771), [here](https://www.mail-archive.com/haskell-cafe@haskell.org/msg62502.html)) -\> we can require recursive `StructuralEq`;
> - This will be hard to specify (e.g. [here](https://www.mail-archive.com/haskell-cafe@haskell.org/msg59623.html)) -\> we can just compile `(a, a)` to `(a, a2) if a == a2`;

It could be restricted to only types and patterns where it isn't observable which of the many bindings is used. Compared to current `const` patterns, that would at least rule out floats and binding by reference. We could recover the lost expressiveness by still allowing something like

```rust
(a @ x, x) => { use(a); }

```

where the binding `x: &T` exists only for pattern matching but isn't usable later.

---

<div class="post-metadata">

**Author:** ![Nadrieril](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/nadrieril/32/11435_2.png) [@Nadrieril](https://internals.rust-lang.org/u/Nadrieril)\
**Post date:** [October 26, 2024, 9:37pm UTC](https://internals.rust-lang.org/t/vibe-check-equality-patterns/21775/5 "2024-10-26T21:37:58Z")

</div>

I mean, yes, but it also seems perfectly fine to allow them for references if we consistently pick the syntactically first binding. People who care about the difference can write an `@` pattern like you suggest.

I hadn't thought of using `@` bindings like that, this would be useful for non-`Copy` types: `(a @ ref x, b @ ref x)` would compare for equality and give me ownership of both values.

---

<div class="post-metadata">

**Author:** ![Vorpal](https://avatars.discourse-cdn.com/v4/letter/v/aca169/32.png) [@Vorpal](https://internals.rust-lang.org/u/Vorpal)\
**Post date:** [October 26, 2024, 9:45pm UTC](https://internals.rust-lang.org/t/vibe-check-equality-patterns/21775/6 "2024-10-26T21:45:10Z")

</div>

This feature is something I miss from Erlang. And I regularly find myself writing this sort of code and then getting annoyed that it doesn't work.

The workaround with guards is unsatisfactory since you regularly end up with a trailing `_ => unreachable!()`, and you now have to check by hand that you actually did cover all the cases. It is always better when the compiler can check your work.

Also, the guard based workaround is more verbose _and_ less readable. It is just a worse alternative.

So I would love to see this feature.

---

<div class="post-metadata">

**Author:** ![jrose](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/jrose/32/9591_2.png) [@jrose](https://internals.rust-lang.org/u/jrose)\
**Post date:** [October 26, 2024, 9:46pm UTC](https://internals.rust-lang.org/t/vibe-check-equality-patterns/21775/7 "2024-10-26T21:46:05Z")

</div>

FWIW Swift has had Eq patterns from the start (actually it’s even more general than that, it’s a dedicated operation that Equatable is just one provider for). They do not participate in exhaustivity checking. Occasionally people complain about specific examples where they want the compiler to be smarter but mostly it’s fine, you just write (the equivalent of) `unreachable!()` if you really don’t have a catch-all case.

Rust, unfortunately, is a bit past that because it already allows consts to be used in an exhaustive way. But I don’t think it’s the worst idea; as noted it’s not really different from how arms with guards don’t figure into exhaustivity.

---

<div class="post-metadata">

**Author:** ![quaternic](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/quaternic/32/10440_2.png) [@quaternic](https://internals.rust-lang.org/u/quaternic)\
**Post date:** [October 26, 2024, 9:53pm UTC](https://internals.rust-lang.org/t/vibe-check-equality-patterns/21775/8 "2024-10-26T21:53:35Z")

</div>

> [@Nadrieril](#):
>
> I mean, yes, but it also seems perfectly fine to allow them for references if we consistently pick the syntactically first binding. People who care about the difference can write an `@` pattern like you suggest.

Maybe it would be fine, but I do see some potential for confusion there. Someone might expect that it's the _last_ binding that takes effect since that's how shadowing would work.

Also, if you are trying to mutate the value behind that reference, it would be preferable to get an error that requires you to be explicit about the target:

```rust
let mut x = (0,0);
if let (a,a) = &mut x {
    *a += 1; // not obvious if this increments x.0 or x.1 (or both?!)
}

```

---

<div class="post-metadata">

**Author:** ![zackw](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/zackw/32/2071_2.png) [@zackw](https://internals.rust-lang.org/u/zackw)\
**Post date:** [October 27, 2024, 2:00pm UTC](https://internals.rust-lang.org/t/vibe-check-equality-patterns/21775/9 "2024-10-27T14:00:58Z")

</div>

As the person who made the original suggestion, let me copy over my motivating example:

```rust
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum LogLevel {
    Quiet = 0,
    Progress = 1,
    Debug = 2,
}

// E0004: non-exhaustive patterns: (Quiet, Quiet) not covered
pub fn describe_log_level_change(old_lvl: LogLevel, lvl: LogLevel) -> &'static str {
    match (old_lvl, lvl) {
        (a, b) if a == b => "No change",
        (_, LogLevel::Debug) => "Debug logging activated",
        (LogLevel::Debug, _) => "Debug logging deactivated",
        (_, LogLevel::Progress) => "Progress reporting activated",
        (LogLevel::Progress, _) => "Progress reporting deactivated",
    }
}

```

My initial reaction to getting this error was "ugh why don't guards participate in exhaustiveness checking", but that's ruled out by Rice's Theorem unless we put severe restrictions on what can appear in a guard expression, and [if I add a trailing `(Quiet, Quiet) => unreachable!()` arm LLVM emits code for it](https://play.rust-lang.org/?version=nightly&mode=release&edition=2021&gist=0f0ace6e257c357828642a5f38120000), so it looks like we don't have the infrastructure to do that even if we wanted to.

And then without really thinking about it I tried writing `(a, a) => "No change"` instead and got a multiple bindings error, which I present as testimonial that the suggested notation is intuitive and won't break existing code.

---

<div class="post-metadata">

**Author:** ![idanarye](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/idanarye/32/3346_2.png) [@idanarye](https://internals.rust-lang.org/u/idanarye)\
**Post date:** [October 27, 2024, 7:47pm UTC](https://internals.rust-lang.org/t/vibe-check-equality-patterns/21775/10 "2024-10-27T19:47:05Z")

</div>

Since this is about exhaustiveness, maybe `(a, a)` should desugar to `(true, true) | (false, false)` instead of `(a, b) if a == b`? (with capturing of the value, of course). This does mean that it can only work for booleans and for enums that only have unit variants - but for other cases you can just use a guard since it does not help with the exhaustiveness.

---

<div class="post-metadata">

**Author:** ![Vorpal](https://avatars.discourse-cdn.com/v4/letter/v/aca169/32.png) [@Vorpal](https://internals.rust-lang.org/u/Vorpal)\
**Post date:** [October 27, 2024, 8:18pm UTC](https://internals.rust-lang.org/t/vibe-check-equality-patterns/21775/11 "2024-10-27T20:18:30Z")

</div>

What about if it only helps with exhaustiveness when it comes to those simple finite types? But can still be used for u8 etc.

---

<div class="post-metadata">

**Author:** ![farnz](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/farnz/32/6587_2.png) [@farnz](https://internals.rust-lang.org/u/farnz)\
**Post date:** [October 28, 2024, 8:34am UTC](https://internals.rust-lang.org/t/vibe-check-equality-patterns/21775/12 "2024-10-28T08:34:16Z")

</div>

> [@idanarye](#):
>
> This does mean that it can only work for booleans and for enums that only have unit variants - but for other cases you can just use a guard since it does not help with the exhaustiveness

At least in theory, you can generalise this to all types where the compiler knows enough to exhaustively generate all possible values of `a` - `u8`, `i64` etc can all be done by the equivalent of generating all possible values. You'd want to short-circuit that, because actually generating 264 match arms is going to be problematic for other reasons, but it works by the same argument.

---

<div class="post-metadata">

**Author:** ![robinm](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/robinm/32/6255_2.png) [@robinm](https://internals.rust-lang.org/u/robinm)\
**Post date:** [October 28, 2024, 9:48am UTC](https://internals.rust-lang.org/t/vibe-check-equality-patterns/21775/13 "2024-10-28T09:48:19Z")

</div>

Could exhaustiveness checking use the 2^n patterns (I assume exhaustiveness pattern has a compact way to represent it, otherwise, it would indeed be much to slow for n \> 32), while code generation use `(a, b) if a == b` ?

---

<div class="post-metadata">

**Author:** ![idanarye](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/idanarye/32/3346_2.png) [@idanarye](https://internals.rust-lang.org/u/idanarye)\
**Post date:** [October 28, 2024, 2:20pm UTC](https://internals.rust-lang.org/t/vibe-check-equality-patterns/21775/14 "2024-10-28T14:20:35Z")

</div>

Code generation can be smart about this, and doesn't have to actually lower this to existing code. Think about enums that don't have `Eq` (or even `PartialEq`) - they should still support this even if they can't `a == b`.

---

<div class="post-metadata">

**Author:** ![kornel](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/kornel/32/2711_2.png) [@kornel](https://internals.rust-lang.org/u/kornel)\
**Post date:** [October 28, 2024, 4:21pm UTC](https://internals.rust-lang.org/t/vibe-check-equality-patterns/21775/15 "2024-10-28T16:21:45Z")

</div>

It's too clever IMHO.

Patterns already allow the same binding to appear multiple times in alternatives `This(a) | That(a)`, so the proposed syntax gives a completely new meaning to only a subtly different variation of the syntax.

---

<div class="post-metadata">

**Author:** ![zackw](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/zackw/32/2071_2.png) [@zackw](https://internals.rust-lang.org/u/zackw)\
**Post date:** [October 28, 2024, 6:54pm UTC](https://internals.rust-lang.org/t/vibe-check-equality-patterns/21775/16 "2024-10-28T18:54:26Z")

</div>

If I modify my "motivating example" code to list all the (x, x) pairs instead of using `(a, b) if a == b`, [LLVM generates notably tighter code](https://play.rust-lang.org/?version=stable&mode=release&edition=2021&gist=9a20db01ac5108a1708c2eaa8168d167). Not only is the unreachable arm gone, but also it is able to merge the two final basic blocks. And I needed an `#[inline(never)]` annotation to get assembly code to be emitted at all for that version of the function, which suggests that the inliner's heuristics are assessing it as much lighter weight than the alternative.

@Nadrieril Since @kornel is concerned that `(a, a) => ...` and `This(a) | That(a) => ...` are confusingly similar despite very different behavior: do Erlang, Miranda, or Prolog do anything to make these cases more obviously different? I am not particularly familiar with any of them.

(They don't seem confusingly similar to _me_, but I have a lot of practice paying attention to small syntactic differences and a high tolerance for terse notation.)

---

<div class="post-metadata">

**Author:** ![Vorpal](https://avatars.discourse-cdn.com/v4/letter/v/aca169/32.png) [@Vorpal](https://internals.rust-lang.org/u/Vorpal)\
**Post date:** [October 28, 2024, 9:52pm UTC](https://internals.rust-lang.org/t/vibe-check-equality-patterns/21775/17 "2024-10-28T21:52:47Z")

</div>

> [@zackw](#):
>
> @Nadrieril Since @kornel is concerned that `(a, a) => ...` and `This(a) | That(a) => ...` are confusingly similar despite very different behavior: do Erlang, Miranda, or Prolog do anything to make these cases more obviously different? I am not particularly familiar with any of them.

It has been quite a while since I actually coded in Erlang. Well over 15 years by now. So take this with a grain of salt:

Erlang has assign-once read-only variables (I don't even think it has shadowing, don't quite remember). And pattern matching is everywhere, not just in match statement, but _all_ assignments are also pattern matching. As such matching on for example `(AVariable, AVariable)` is idiomatic and will bind the first use of it, and then try to use that binding to check the second use of it.

I don't remember that Erlang has anything like `This(a) | That(a)`. Looking through the docs I don't see anything like that either. And some of the examples (like [days for a given calendar month](https://www.erlang.org/docs/25/getting_started/seq_prog#if-and-case)) are written expanded. I would assume they would use such a more compact syntax if they had it.

Prolog is very similar here to Erlang, and since I have used it much more recently I'm almost certain it doesn't have `This(a) | That(a)` style syntax.

In both Prolog and Erlang (they are syntactically very similar, though semantics are very different) `|` is normally used to separate the head from the tail of a linked list (Lisp style cons list if that helps): `[H|T] = MyList` is a way to unpack a list of at least one element. So that operator definitely isn't it.

I'm not at all familiar with Miranda. Haskell might be worth taking a look at too, I never managed to get very far with learning it, but it does have simple pattern matching.

I do believe the match statement in Python supports `|` for `or` though. Might be worth checking?

---

<div class="post-metadata">

**Author:** ![zackw](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/zackw/32/2071_2.png) [@zackw](https://internals.rust-lang.org/u/zackw)\
**Post date:** [October 28, 2024, 10:26pm UTC](https://internals.rust-lang.org/t/vibe-check-equality-patterns/21775/18 "2024-10-28T22:26:29Z")

</div>

> [@Vorpal](#):
>
> I do believe the match statement in Python supports `|` for `or` though. Might be worth checking?

Python does indeed support "this or that" matching with `|` as the operator... and it _doesn't_ support bind-and-compare patterns:

> In a given pattern, a given name can only be bound once. E.g. `case x, x: ...` is invalid while `case [x] | x: ...` is allowed.
> 
> — [Python 3.13 language reference, section 8.6.4.4 "Capture Patterns"](https://docs.python.org/3.13/reference/compound_stmts.html#capture-patterns)

@Nadrieril said up top that Haskell doesn't have bind-and-compare either. I'll let someone else speak for Miranda.

---

<div class="post-metadata">

**Author:** ![robinm](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/robinm/32/6255_2.png) [@robinm](https://internals.rust-lang.org/u/robinm)\
**Post date:** [October 29, 2024, 10:06am UTC](https://internals.rust-lang.org/t/vibe-check-equality-patterns/21775/19 "2024-10-29T10:06:49Z")

</div>

By the way, it it necessary to add the new syntax `(a, a) => …` rather that just teaching the compiler that `(a, b) if a == b => …` can be optimized much better under some circumstances (which will also possibly speed up some existing program from free and not the new code using the new syntax)?

---

<div class="post-metadata">

**Author:** ![elidupree](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/elidupree/32/4304_2.png) [@elidupree](https://internals.rust-lang.org/u/elidupree)\
**Post date:** [October 29, 2024, 11:09am UTC](https://internals.rust-lang.org/t/vibe-check-equality-patterns/21775/20 "2024-10-29T11:09:11Z")

</div>

I don't think this is a completely new meaning: I think it is a natural generalization of the same meaning, which is "wherever the same variable name appears, that refers to the same variable" (which is basically just the definition of "variables", in general).

The "difference" is that in `This(a) | That(a)`, the actual object will only be one particular variant, while in `(a, a)`, there's just a single case with 2 sub-values – but that's the natural difference between a sum type and a product type, and is a separate matter from whether patterns may refer to the same variable multiple times.

[Next page](https://internals.rust-lang.org/t/vibe-check-equality-patterns/21775.md?page=2)
