Feedback: Guards and static/instance pattern declarations
Stephen Colebourne
scolebourne at joda.org
Thu Jan 28 22:45:32 UTC 2021
On Thu, 28 Jan 2021 at 19:19, Brian Goetz <brian.goetz at oracle.com> wrote:
> Here's a more concrete example of where this approach starts to lose it
> when we get past trivial guards. If we try to interpret an arbitrary
> boolean expression as pattern, when it is the right operand of a &&
> whose left operand is a pattern, what do we do with this:
>
> t instanceof Foo(var x) && x instanceof Bar(var y) && Q:
>
> `x instanceof Bar(var y)` is surely an allowable boolean expression, but
> now it is really not clear whether the user meant to match t to Foo(var
> x) and to Q, subject to the guard that x is a Bar(var y), or meant to do
> to separate instanceof tests, the second to "Bar(var y) && Q".
>From this, I understand that the main problem is how to determine
which target applies to Q - t or x.
I agree that in general this is a real problem as the syntax is
currently structured. I also think that for complex patterns, there is
probably no avoiding the problem. But here are a 2 orthogonal
thoughts:
1) Use when instead of true/false
t instanceof (Foo(var x) & when(x instanceof Bar(var y)) & Q)
This reads more naturally and looks less artificial. I'm not convinced
having the choice of true or false to write a guard is actually that
helpful anyway - if statements and ternary expressions don't have a
choice of a true and a false version.
2) Treat patterns more like objects:
Build on normal method chaining and params:
if (t instanceof Foo(var x).and(x instanceof Bar(var y)).and(Q)) {...}
vs
if (t instanceof Foo(var x).and(x instanceof Bar(var y).and(Q))) {...}
This has the same basic idea as `containsKey(k).get(var v)`. Allowing
different bits of a pattern to be flexibly joined as though by method
call. I recognise that this is a leap in how patterns are designed,
but making parts of a pattern combine like library methods does seems
like a win as it builds on existing knowledge of method chaining. If a
genuine pattern object is created (that can be assigned to a local
variable) then this becomes an even more natural way to think about
the problem. (Lambdas aren't special, they are just objects. That is a
key part of why they fit into Java so well. I think patterns deserve
the same treatment)
Stephen
More information about the amber-dev
mailing list