The `|` symbol is required for single-case generic Discriminated Unions
See original GitHub issueThis is a single-case DU:
type Foo = Foo
However, the |
symbol is required for single-case generic DUs.
// Does not compile
type Bar<'t> = Bar
// Compiles
type Bar<'t> = | Bar
From StackOverflow:
I think there are two interesting cases here. The first one is:
type Foo = Foo
This looks like a self-referential type alias at first, but that’s not allowed, so the compiler instead accepts it as a valid DU. This is correct, although subtle, behavior.
The second interesting case is:
type Bar<'t> = Bar // Error: The type 'Bar<_>' expects 1 type argument(s) but is given 0
This also looks like a self-referential type alias at first, but with the wrong number of type parameters. Since the reference is invalid, the compiler issues an error before it has a chance to realize that it’s actually looking at a valid DU definition. I think one could reasonably argue that this is a bug in the compiler, and I suggest submitting it as an issue to the F# compiler team. The expected behavior is that this is a valid DU, just like
type Foo = Foo
andtype Bar<'t> = | Bar
.Note also that the following is (correctly) not allowed:
type Bar<'t> = Bar<'t> // Error: This type definition involves an immediate cyclic reference through an abbreviation
Expected behavior
These should be equivalent:
type Bar<'t> = Bar
type Bar<'t> = | Bar
Actual behavior
This does not compile:
type Bar<'t> = Bar
Known workarounds
Add the |
Related information
Ubuntu 20.04
dotnet --version
6.0.300
Issue Analytics
- State:
- Created a year ago
- Reactions:1
- Comments:9 (9 by maintainers)
Top GitHub Comments
The canonical representation of DUs has a vertical line before the first case:
type SomeDU = | SomeCase...
. See https://github.com/fsharp/fslang-suggestions/issues/958#issuecomment-765381374 . Existing cases where the compiler allows the vertical line to be omitted are unfortunate, and while they currently need to be there for backwards compat, they should be warned about eventually by analyzers.The fact that it is not obvious whether the code here is a DU or type alias underlines the need to enforce the canonical formatting.
I’ll close as this can be a language suggestion