Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Discriminated Unions and let bindings

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?

like image 802
GregRos Avatar asked Nov 19 '25 06:11

GregRos


1 Answers

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 member declaration to the type:

type Number =  
  | One of int
  | Two 

let one x = One(x) 

type Number with
  member this.Hi x = one x 

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 let bindings inside the class (before declaring members), but sadly this is not supported for discriminated unions.

like image 183
Tomas Petricek Avatar answered Nov 21 '25 05:11

Tomas Petricek