First Draft: Nominal Sum Types via `enum union` and `switch` Expressions
Meta
jared771 at gmail.com
Thu Sep 24 20:45:15 UTC 2026
On Thursday, 24 September 2026 at 12:40:30 UTC, Dejan Lekic wrote:
>> And it's now implemented:
>> ```d
>> enum union Shape
>> {
>> case Circle(double);
>> case Rect(double, double);
>> case Point();
>> }
>>
>> double area(Shape s)
>> {
>> return switch (s)
>> {
>> static foreach (T; __traits(allVariants, Shape))
>> {
>> static if (__traits(identifier, T) == "Circle")
>> {
>> case Circle(r) => 3.14159 * r * r,
>> }
>> else static if (__traits(identifier, T) == "Rect")
>> {
>> case Rect(w, h) => w * h,
>> }
>> else
>> {
>> // Optional trailing delimiter before right
>> curly
>> case Point() => 0.0
>> }
>> }
>> };
>> }
>>
>> Shape sh = Shape.Rect(3.0, 4.0);
>> assert(area(sh) == 12.0);
>> ```
>
> Is it me or this is just terrible, and this is just a tiny
> example. For anything more serious (read - real world use
> cases) the amount of ugly code like the one above would be
> enormous...
This is just an example to show that static if/static foreach
work. While it *is* possible to write code like this with my DIP,
you will almost never see it in practice, outside heavy
metaprogramming scenarios like serialization libraries, writing
compilers/interpreters, bare metal, etc.
More information about the dip.development
mailing list