Join GitHub today
GitHub is home to over 31 million developers working together to host and review code, manage projects, and build software together.Sign up
Shorthand syntax for single case DUs #727
Title of Suggestion
I propose we add a shorthand syntax for single case Discriminated Unions.
The existing way of approaching this problem in F# is usually repeating the type name.
//Current type SomeDomainType = SomeDomainType of int type Temperature = private Temperature of int //Proposed type SomeDomainType of int type Temperature private of int
Pros and Cons
The advantages of making this adjustment to F# are
The disadvantages of making this adjustment to F# are one more syntax to learn.
Estimated cost (XS, S, M, L, XL, XXL): S
Related suggestions: (put links to related suggestions here)
Affidavit (please submit!)
Please tick this by placing a cross in the box:
Please tick all that apply:
Just to expand on this, for people new to F# I've found a common pitfall is to not fully understand the difference between a DU case and the DU type itself. Even after understanding the difference they sometimes conflate these two things for a while. This syntax blurs the boundaries between those two things which could contribute to that misunderstanding.
I would also add as a distinct disadvantage that this would add yet another instance in F# where there are multiple equivalent ways to do exactly the same thing, making it harder to know what's idiomatic and harder to read code in general. I think F# already has more of these than many languages. This is made worse by being a late addition to the language, so even the most idiomatic code will never use this feature if it was written for earlier F# versions.
I think this syntax is better suited as a general extension of the existing syntax
Bonus points if we could use the parameters inside the type directly, unlike
type HttpHeader of name:string * value:string with member __.Formatted = sprintf "%s: %s" name value
Edit: note it would also subsume existing
type TemperatureException of value:int with inherit Exception(sprintf "Reached %d degrees" value) // No `this.Message` override needed!
I'm not yet sure about the proposed syntax, as it is not too inconvenient to define a single case DU right now when needed, but it looks fitting idioms.
Is this something that should go along the same line as haskell "newtype" or even related to some degree to units of measures?
Agreed. Using the same name for the DU type as for one of its cases is confusing. If anything, doing this should be warned about, not encouraged with a shorthand syntax.
I can certainly sympathize with the existing syntax with single-case DUs today - it kind of sucks, and the tooling point is valid. I wouldn't shocked if it were done differently had F# been first conceived today. However, I think this does break the following design principles: