The feature proposed in #15865 catches most of the what's described here, with a couple differences:
- Matching is not strict.
- The proposed <match-op> is
in
. - The pattern is on the RHS.
I could be persueded that strictness is undesirable, but I also see it as a potential way to differentiate destructuring assignment and pattern matching (particularly in the case where no actual tests are a part of the pattern).
<expr> in <pattern>
looks great as a standalone construct on paper, but the question posed by data in <pattern>
or [1, 2, 3] in <pattern>
is hard to swallow in English. The implication is something like "[is] <expr> in [the set of all possible values that will match] <pattern>", which is mathematically sound, but not a natural way to read the expression. It's much more likely to be understood as "[is this] <expr> [contained by] <pattern>" (as in <pattern>.includes?(<value>)
), which the feature actually bears little similarity to. The ordering of <expr> in <pattern>
is also a reversal of how the same operator is currently used in Ruby (e.g. for x, y in { a: 1, b: 2 }
).
As for putting the pattern on the RHS, I personally dislike it. The pattern syntax already makes it a bit difficult to tell what's being assigned to vs. tested against, and it feels as though the pattern is the more important part of the expression – doubly so, since the pattern cannot be stored in a variable and must be written inline. Unfortunately, the proposed <match-op> also reads strangely in when using <pattern> in <expr>
, with the implied reading being akin to "[can you see a match for this] <pattern> in [this] <expr>". Arguably better, but still awkward.
The ideal English reading, IMHO, is something akin to "[does this] <pattern> [match this] <expr>". To that end match
or matches
would seem to be a better operator name than in
, but come with the caveat of being common variable names.
case/in
is already strict, isn't it?