Composition of pattern questions

Stephen Colebourne scolebourne at joda.org
Thu Mar 4 10:43:43 UTC 2021


On Wed, 3 Mar 2021 at 22:51, Brian Goetz <brian.goetz at oracle.com> wrote:
> In fact, as I mentioned on the other list, the main issue here is that
> most of the use cases for AND patterns are _also_ less immediate, except
> we had an immediate need for guards, which leaves us with a bad choice:
> expose a concept before the user base is really ready (engendering
> exactly the pushback you're delivering now), or, nail yet another ad-hoc
> bag on the side of switch, which will eventually become redundant
> because it will be expressible using more primitive concepts.
>
> It sounds like your vote is "bag, please"?

Not quite. I accept that composition is generally a good language
design choice, but wanted to check there are no use cases I was
missing. However, it's not clear guards need to compose in exactly the
same way as patterns (and the current grammar already has them as a
special case). Your answers also suggest you aren't willing to give up
& entirely, which seems reasonable.

What I was exploring is a syntax design space where guards are special
but patterns can still be composed. The document even says "Guard
patterns are intended to _refine_ the meaning of other patterns".
AFAICT, what I'm suggesting is this grammar and examples:

Pattern:
: PatternOperand { Guard }
: Pattern `&` Pattern

PatternOperand:
: TypePattern
: ArrayPattern
: RecordPattern

Guard:
 : `when(` Expression `)`

 case Rectangle(Point x, Point y) when(x > 0 && y > 0)
 if (m instanceof (Map.withMapping("key1")(var v1) when(v1 != null)
    & Map.withMapping("key2")(var v2 when(v2 != null)))) { ... }

This seems to fulfil the requirements, be more readable, and doesn't
lose much power - writing "GuardPattern & GuardPattern" can be
refactored to a single expression, and I'm not sure "PatternOperand |
GuardPattern" is useful for anything. But perhaps I'm missing
something?

Stephen


More information about the amber-dev mailing list