Rehabilitating switch -- a scorecard

Remi Forax forax at univ-mlv.fr
Tue May 18 15:40:21 UTC 2021


----- Mail original -----
> De: "Brian Goetz" <brian.goetz at oracle.com>
> À: "John Rose" <john.r.rose at oracle.com>
> Cc: "amber-spec-experts" <amber-spec-experts at openjdk.java.net>
> Envoyé: Mardi 18 Mai 2021 04:37:55
> Objet: Re: Rehabilitating switch -- a scorecard

>> There are a few roads not taken:  “switch ()” with boolean
>> case expressions has not showed itself worthy yet.
> 
> Yep, this one can sit on the shelf.
> 
>> I’d also like to point out “switch (a, b)” as a possible area
>> of future work for switch, where the thing after “switch” is a
>> more generalized argument expression
> 
> ML supports this, because it just treats the operand as a tuple, and
> automatically destructures tuples.   The killer use case is, of course,
> FizzBuzz:
> 
>     switch (n % 3, n % 5) {
>         case (0, 0) -> "FizzBuzz";
>         case (0, _) -> "Fizz";
>         case (_, 0) -> "Buzz";
>         default -> n.toString();
>     }

with the destructuring pattern, our current version is

  record Result(int d3, int d5) {}
  switch(new Result(n % 3, n % 5)) {
    case Result(var d3, var d5) && d3 == 0 && d5 == 0 -> "FizzBuzz";
    case Result(var d3, var __) && d3 == 0 -> "Fizz";
    case Result(var __, var d5) && d5 == 0 -> "Buzz";
    default -> "" + n;
  }

to fill the gap, we need
 - _ as pattern equivalent to var _ + _ not be entered in the scope

 - constant as pattern, Foo(constant) being equivalent to Foo(var x) && x == constant

 - inference of Type in a destructuring pattern, case Foo(var x, var y) becomes case (var x, var y) if the type of the switched value is Foo
   This kind of inference is also useful in pattern assignment
     with Foo(var x, var y) = foo; being written (var x, var y) = foo;
   
 - tuple as first class citizen
   (expr, expr2) is equivalent to either creating a record + new SyntheticRecord(expr, expr2)  or new Tuple<int, int>(expr, expr2)
   This feature is also useful to model methods that returns several values/deconstructor, but it means that
      either methods descriptor will contains synthetic record name which is ugly (TypeRestriction may help here),
      or we are able to cook a primitive parametrized/specialized class Tuple, the creation can be an indy converted as (default  + a sequence of withfields),
      but we have to wait Valhalla.

Rémi


More information about the amber-spec-experts mailing list