let ``one`` x = One(x)
type Number =
| One of int
| Two
with
member this.Hi x = ``one`` x
Basically, I want to define a let binding that references a discriminated union, and I want to use it in one of the extensions to that union, because I know you can’t define let bindings inside unions for some strange reason. The double ticks are for emphasis.
Actually, what I want is to make a sort of concise constructor for members of the union. I understand discriminated unions can’t have constructors, but is there a way to do this, perhaps without using a let binding as above?
You can use type extensions to define the type, then write a number of let bindings (top-level or in a module) and then add
memberdeclaration to the type:If you write this in a single file, then this is an intrinsic type extension, which means that the code will be compiled as a standard type with members (and the members will be directly usable from C#). If you added the extension in another file, then that would be different (more like C# extension methods).
For F# class declarations, you can also use local
letbindings inside the class (before declaring members), but sadly this is not supported for discriminated unions.