Continue in switch

Stephen Colebourne scolebourne at joda.org
Wed May 9 00:13:11 UTC 2018


On 8 May 2018 at 20:31, Brian Goetz <brian.goetz at oracle.com> wrote:
> While this is semantically attractive (the guard condition is declarative),
> I worry that it is not likely to be very satisfying in practice.  In toy
> examples, it looks great, but as examples expand to a more realistic scale,
> the pattern, guard, and imperative consequence can easily mush together.
> For example:
>
>     case Point(var x, var y)
>         where x > 0 && y > 0 && x < y -> x + y;
>
> You can try reformatting:
>
>     case Point(var x, var y)
>         where x > 0 && y > 0 && x < y
>             -> x + y;

Is this not just a syntax thing because of using arrow? Here is one
possible alternate syntax:

  case Point(var x, var y)
      where (x > 0 && y > 0 && x < y)
      do x + y;

> The obvious choice is to give "continue" semantics within a switch:
>
>     case Foo(var x, var y):
>         if (x > y)
>             continue;  // keep processing at next case
>         foo(x, y);
>         break;

I don't think this is as attractive as the where clause, although
obviously its more flexible. Moreover, I think that flexibility
probably results in more side-effecting code, and more complex logic
(poor code style). The where clause is much more direct (like the
potential requires clause in records).

> Of course, compatibility raises its ugly head.  You could have a switch
> today with continue-in-switch-in-for:
>
>     for (...) {
>         switch (x) {
>             case 0: continue;  // valid today, means continue the loop
>         }
>     }
>
> This code works today, which means a continue in a switch in a loop would be
> ambiguous, and would require a label.

I was surprised that continue was valid in a switch statement. This is
because I view break and continue as a pair, so I would have expected
break and continue to both have been given meaning by the old switch
statement. As such, I'd support phasing out use of unlabelled continue
within switch (and not allowing it in the 3 new variants of switch).

> As a means of mitigation, we could also allow the syntax "continue switch"

Perhaps, but I view it as a bit of a hack. (And while "continue if" is
clever, I think it would result in poor code style)

Stephen


More information about the amber-spec-observers mailing list