Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using all cases of union type F#

Tags:

f#

This is very linked to the question here How to enumerate an enum/type in F#. I define a union type and then I need to use all the possible cases of the type in static method. For example:

type Interests =
| Music 
| Books
| Movies
    with 
        static member GetValue( this) = match this with 
                                         | Music  -> 0
                                         | Books -> 5
                                         | Movies -> 0
        static member GetSeqValues() = allCases|>Seq.map(GetValue)

How do I get allCases ?

Thanks a lot

like image 589
jlezard Avatar asked Dec 17 '10 12:12

jlezard


1 Answers

You can use FSharpType.GetUnionCases() from Microsoft.FSharp.Reflection to get all cases of a discriminated union. In your example, it would look like this:

type Interests = 
   | Music  
   | Books 
   | Movies
   static member GetValue(this) = (...)
   static member GetSeqValues() = 
     // Get all cases of the union
     let cases = FSharpType.GetUnionCases(typeof<Interests>)
     [ for c in cases do 
         // Create value for each case (assuming it has no arguments)
         let interest = FSharpValue.MakeUnion(c, [| |]) :?> Interests
         yield GetValue(interest) ]

However, the problem is that you may not be able to create instances to pass to your GetValue member, because some cases may have arguments (when calling MakeUnion you have to pass it an array of arguments and I used just an empty array). For example if you had:

type Sample =
 | A of int
 | B of bool
like image 62
Tomas Petricek Avatar answered Oct 30 '22 21:10

Tomas Petricek