Type Inference for Struct/Enum Literals

Quirin Schroll qs.il.paperinik at gmail.com
Mon Jul 8 18:17:16 UTC 2024


On Sunday, 7 July 2024 at 19:07:10 UTC, Nick Treleaven wrote:
> On Saturday, 6 July 2024 at 08:04:36 UTC, ryuukk_ wrote:
>> The pushback is from people who never got to learn new 
>> languages, they believe this is what everyone wants to write
>
> They do not believe that.
>
> The proposal is fine except where it breaks existing code. I 
> don't think editions should redefine syntax without a very good 
> reason. There is a limited budget for breakage per edition. (An 
> example of such a reason is breaking bug-prone code).
>
>> `MySelfExplanatoryType flag = MySelfExplanatoryType.A | 
>> MySelfExplanatoryType.B MySelfExplanatoryType.C;`

For that, we could add this to the language:
```d
with MySelfExplanatoryType flag = A | B | C;
```

And generally, why not use the `enum` keyword? Let `enum.X` infer 
the `enum` type depending on use. Yes, `enum.` is 5 characters 
whereas `.` is just 1, but it’s so much clearer and breaks no 
code.

I get that `setState(invalid)` is nicer to the programmer than 
`setState(enum.invalid)`, but the advantage is that there’s zero 
ambiguity of intent.

There could even be a new parameter storage class named `with` 
that would allow dropping `enum.` for constants of a particular 
`enum` type:
```d
class Widget
{
     void setState(with State newState) { … }

     void set(StateTag _ = StateTag(), with State newState) { … }
     void set(ShapeTag _ = ShapeTag(), with Shape newShape) { … }
}

void main()
{
     Widget w = new Widget;
     w.setState(State.invalid); // okay
     w.setState(enum.invalid); // new: okay, general enum type 
inference
     w.setState(invalid); // new: okay, special `with` parameter

     w.set(newState: invalid); // new: okay, special `with` 
parameter
     w.set(newShape: square); // new: okay, special `with` 
parameter
}
```
A `with` parameter is allowed for `enum` type parameters, and 
advised when
1. * either the name of the function makes absolutely clear what 
is passed,
    * or there is a mechanism in place that requires use of named 
arguments and the arguments’ name makes things clear, and
2. there is probable cause that the function is called with 
members of the `enum` type.


More information about the dip.ideas mailing list