Pattern matching equal or same elements

What do you folks think about being able to pattern match same/equal elements? Here is an example:

arr match
  case Array(x, x) => ... // where the array has two elements that are equal
  ...

Currently, we get a x is already defined error. And we would have to use if guard like so:

case Array(x, y) if x == y => ....

I am ignorant to know if this is even feasible from a compiler’s perspective. But thought I should throw it out here because I think it would be useful.

Curious to know what you folks think.

1 Like

I think it would be very cool and useful, and a further extension of the multiple case ideas (see for example QoL: Sound binding in pattern alternatives)

We could even allow patterns like the following:

x match
  case ExtractorA(y) & ExtractorB(y) => // branch if x matches both extractors, by analogy to
  case ExtractorA(y) | ExtractorB(y) => // branch if x matches either extractors

Alternatively, the symbol could be @, as this is a generalisation of it:

x match
  case  y@Extractor(z) => // is equivalent to
  case y & Extractor(z) =>
2 Likes

There is an open relevant proposal SIP-60 - Alternative bind patterns by yilinwei · Pull Request #74 · scala/improvement-proposals · GitHub

3 Likes