Composition of pattern questions

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


On Thu, 4 Mar 2021 at 15:30, Brian Goetz <brian.goetz at oracle.com> wrote:
> > What I was exploring is a syntax design space where guards are special
> > but patterns can still be composed.
>
> I think the root of your discomfort may be: we _already_ have a way to
> express guard-like constructs in instanceof using ordinary
> &&-composition

No. I'm not bothered by that really. Expression-world and
pattern-world are different, and both need a mechanism for an
expression to be applied Thus, I don't have a problem with all these
being valid:
 if (x instanceof Point(var x, var y) && x > 0 && y > 0) { ...}
 if (x instanceof Point(var x, var y) when(x > 0) && y > 0) { ...}
 if (x instanceof Point(var x, var y) when(x > 0 && y > 0)) { ...}
 if (x instanceof Point(var x when(x > 0), var y when(x > 0))) { ...}
where the end result is the same, but the mechanisms are different.


> _two_ features (& composition and true/false patterns) to get to a guard
> in a switch seems too roundabout, and you want something more direct?

The JEP is already telling you that guards are not the same as other
patterns - that they are pattern modifiers, not patterns. I do admire
the idea of guard patterns and the consistency of just composing them
- I think the idea was worth exploring. Ultimately however, I don't
think guard patterns work out that well, especially in syntax. The
extra & is jarring particularly as it is not adding anything
meaningful. It's not pure composition either, as guard patterns are
not allowed everywhere, only in some places.

Having just done a presentation on patterns, I think it is simpler to
explain that a guard can be added to any pattern:
"
There are various types of pattern, eg. type, array and record
Patterns can be nested
Patterns can be composed
Any pattern can have a guard, to modify its behaviour (including
nested and composed ones)
"
(partly because when thinking about a pattern, you are already
thinking about matching, so the refinement of a guard fits better into
the discussion linked to the pattern, as opposed to composition which
is harder to grasp wrt patterns than general expressions)

Stephen


More information about the amber-dev mailing list