Feedback: Guards and static/instance pattern declarations
Brian Goetz
brian.goetz at oracle.com
Sun Jan 24 17:46:49 UTC 2021
>
>> * the use of & is nasty given its meaning of evaluating both sides
>
> Yeah, the both-sides thing is a concern.
On further thought (actually, retracing my steps from the first time), it’s not really as concerning as it first looks, for reasons that connect to the “bun” argument — that the & is applying in “pattern world”, not “left to right expression world”.
A good way to think of a pattern is that it is a deferred computation, not unlike a lambda. When I say `x instanceof P`, P is a recipe for computation, which will be “invoked” via instanceof at the appropriate time. To the extent that P refers to state from the enclosing computation, we almost certainly impose the same requirement as we do on lambdas: that it be effectively final; this avoids messy and generally unhelpful questions about the semantics of patterns. (Guard patterns can refer to bindings from earlier in the pattern, and to “captured” locals from the local context, so long as they are effectively final.) So when we say P&Q, we mean the conjunction of the patterns P and Q, but we are not saying “compete P, compute Q, and take their intersection”; we are specifying a new pattern, but we haven’t evaluated anything yet.
More concretely, if we say
if (t instanceof Foo(var x, var y) & true(x > y) & Bar(var z)) { … }
then we are defining a pattern that is the combination of three simpler patterns. When we test against that composite pattern, there are of course rules for how to interpret matching. In my recent mail about “next steps”, there's something like:
- matches(x, A&B) === matches(x, A) && matches(x, B)
Bottom line is I think it will be useful to think of a complex pattern as being a specifier for some deferred computation, like a lambda. The & conjunction builds bigger deferred computations from smaller ones. The bun lets us pull expressions that are suitable for deferred computation into the pattern.
More information about the amber-dev
mailing list