First Draft: Nominal Sum Types via `enum union` and `switch` Expressions
Meta
jared771 at gmail.com
Sun Sep 20 17:37:36 UTC 2026
On Sunday, 20 September 2026 at 10:33:40 UTC, Nick Treleaven
wrote:
> On Sunday, 20 September 2026 at 02:10:15 UTC, Meta wrote:
>> On Friday, 18 September 2026 at 12:46:32 UTC, Dukc wrote:
>>> ```d
>>> enum union A
>>> {
>>> case int, case Option!float, case string, case Exception;
>>>
>>> static A someInstance;
>>> }
>>>
>>> switch(A.someInstance)
>>> {
>>> case 42 () => ...,
>>> // matches ints other than 42
>>> case (int x) => ...,
>>
>> This can be done with guard patterns:
>> case int n if (n == 42) => ...,
>> case int n => ..., // Catch-all int case
>
> I think a guard is not really part of a pattern, it's just an
> extra test when the pattern on the left is matched.
> Literal/constant patterns seem to be commonly supported in e.g.
> C#, Rust, Swift, Kotlin.
> https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/patterns#constant-pattern
> https://doc.rust-lang.org/reference/patterns.html#r-patterns.literal
> https://docs.swift.org/latest/documentation/the-swift-programming-language/patterns/#Expression-Pattern
> https://kotlinlang.org/docs/control-flow.html#when-expressions-and-statements
>
> The D compiler can call `expr.isConst()` to tell if an
> expression is a compile-time constant. But even just supporting
> a literal pattern would improve usability - e.g. `case 42 =>
> expr`.
>
> Also, given that this DIP is using the existing `switch`
> statement syntax, it would be consistent with case statements:
> `case 42:`.
My point was that `case 42 =>` and `case int n if (n == 42) =>`
are equivalent, so his use case is covered. I decided against
adding full pattern matching in lieu of saving it for a future
DIP.
More information about the dip.development
mailing list