JavaHava
JavaHava

Reputation: 189

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

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#?

Upvotes: 2

Views: 154

Answers (1)

chadnt
chadnt

Reputation: 1135

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")]

Upvotes: 2

Related Questions