How to loop through discriminated union cases and call thier member functions on them?

Viewed 83

The goal is the loop through each descrimintated union cases and print out the description for each case e.g

type car = 
| Benz 
| Honda 
    member this.description() = 
        match this with 
        |Benz -> "Benz description"
        |Honda -> "Honda description"

The calling code would use FSharpType.GetUnionCases typeof<Car> and loop through the union cases.

Is this possible to achieve in F#?

1 Answers

I think you can use FSharpValue.MakeUnion. This example will return a sequence of tuples with the union type and description:

type Car = 
| Benz 
| Honda 
    member this.description() = 
        match this with 
        |Benz -> "Benz description"
        |Honda -> "Honda description"

FSharpType.GetUnionCases typeof<Car>
|> Seq.map (fun uci ->
    let c = FSharpValue.MakeUnion(uci, [||]) :?> Car
    (c, c.description()))

Example:

val it: seq<car * string> =
  seq [(Benz, "Benz description"); (Honda, "Honda description")]
Related