[pattern-switch] Totality

Brian Goetz brian.goetz at oracle.com
Sun Aug 30 14:23:38 UTC 2020


Yes, this looks very much like a PoC I did once too.  The upshot of that experiment is that operators like AND, OR, nesting, and guarding are amenable to implementation as combinators, which is nice.  

> To deal with the deconstruction, i need 3 primitives
> - deconstruct(Object value) that calls the deconstructor if the deconstructed object is a class

Here you’re making an assumption about the language model, which is that classes may only have one deconstructor.  This is a pretty serious limitation, and forces pattern matching to stay very much on the periphery of the object model.  (I know why you want to make this assumption, because you want the bindings to be the return type and there is no return type overloading.)  

> - extract(Record record, String name) that can extract the value of a record component from its name
> - with(Record record, String name, Object value) that creates a new record with the value of the record component corresponding to the name changed
> 
> The implementation of those primitives relies on the reflection so it's slow and wrong in term of security, but it's enough for a prototype [2]

Yes, but.  It also makes an assumption about runtime resolution of bindings based on component name.  Again, you are making a big assumption about “how the language should work”, but again it has gotten buried in an implementation detail.  So whatever we learn from this model comes attached to some big assumptions.  

FWIW, my implementation treated a pattern as a bundle of method handles, one was a mapping from the match target to an opaque carrier (null meant no match), and N method handles from the carrier to the binding value.  In many cases the target itself was a suitable carrier.  

> The deconstruction is based on the names of the record components and not their declared positions in the record. 
> You may think that this way of doing the deconstruction is not typesafe but the fact that all the fields of the carrier record are typed means that all the bound variables have the correct type.

Yes, but type safety is one of the lesser of my concerns here.  



More information about the amber-spec-experts mailing list