Composition of pattern questions
Stephen Colebourne
scolebourne at joda.org
Wed Mar 3 21:58:00 UTC 2021
The current proposed syntax for pattern composition is:
case Rectangle(Point x, Point y) & true(x > 0 && y > 0)
case Rectangle(Point x & true(x > 0), Point y & true(y > 0))
case Map.withMapping("A")(var a) & true(a != null) &
Map.withMapping("B")(var b)
I have three questions around this:
1) What are the use cases for combined patterns beyond pattern+guard?
I believe that the main (only?) use cases are where pattern methods
are used to query containers like maps and JSON (the second example
above). Are there any other use cases? (I acknowledge that pattern
composition is more powerful, and generally the better tool for
language design, but not if the complexity is high and the use cases
are overly esoteric). For example, the `withMapping` example could be
written as a varargs method, reducing the apparent use cases:
case Map.withMappings("A", "B")(var a, var b) & true(a != null)
2) Why do we need both true() and false() for guard patterns?
Other similar constructs (if and ternary) make do with just one form,
so why do guard patterns need both true and false forms? (and yes, I'm
in the "its ugly" camp)
3) Are OR patterns ever going to be needed?
I know there has previously been discussion around OR patterns,
however it has currently been ruled out. It seems to me that if OR was
permanently ruled out (a choice which limits Java's future
development, but perhaps in an acceptable way), then there are a few
alternate syntax options.
For example, it seems like you could have a syntax that looks like a
simple guard but is actually full-blown AND-only pattern composition:
case Rectangle(Point x, Point y) when(x > 0 && y > 0)
case Rectangle(Point x when(x > 0), Point y when(y > 0))
case Map.withMapping("A")(var a) when(a != null) when
Map.withMapping("B")(var b)
Stephen
More information about the amber-dev
mailing list