Comments/Feature Requests regarding JEP 305: Pattern Matching

Maurizio Cimadamore maurizio.cimadamore at
Wed Jul 5 21:03:01 UTC 2017

On 05/07/17 21:34, William Shackleford wrote:
> In addition to being more concise:
>   n is not both used as the positive part of the NegNode and as the input
> parameter.
Note that this is likely to be a bug in the original example. It is not 
possible for a pattern binding to 'shadow' a method parameter name.
> It works with classes that have more fields/methods than constructor
> arguments.
> It seems to me that is better to consistently use a single syntax style
> rather than having one for classes
> that have only one or two fields that happen to match the constructor
> arguments and another more
> general style. This is especially true given that it doesn't even seem to
> make the code more concise.
Generally what you say is true - in many cases you will be able to write 
things even without nested patterns.

It is very likely that at the very least we will add some support for 
unnamed binding (with underscore '_' ) - in the spirit of unused lambda 
parameters (see JEP 302 [1]).

But where I think you reach the end of the road with that approach is 
when matching arbitrary expressions. Let's say you want to 'simplify' an 
expression - that is, given an input expression, you want to construct 
another expression that is simpler than the one in the input, by 
recognizing things such as:

-N + N = 0
0 + N = N
0 * N = 0
1 * N = N

To recognize some of those cases, you need to build more complex 
patterns; for instance, for the first case you need a pattern like this:

case AddNode(NegNode(IntNode(var n1)), IntNode(var n2)) && n1 == n2: ...

[sidebar: '&&  n1 == n2' is what we call a _guard_ - a binary expression 
that further controls whether a pattern matches or not]

Writing something like the one above without nested patterns would be 
extremely hard - you could start by checking that the outermost 
expression is an AddNode, as in your example, but then you would still 
need 2 dynamic checks for the two nodes, and then a further dynamic 
check for accessing the guts of the NegNode. In other words, getting at 
the two int values would be extremely unpleasant and verbose w/o any 
support for nested patterns.

For simpler examples, I'm with you, simpler patterns might be just fine.


[1] -

More information about the amber-dev mailing list