mercredi 20 septembre 2017

How do I get a discriminated union case from a string?

I have a discriminated union and I want to select a case based on a string (which is read from a JSON file). This is easy to do:

type MyDU = A | B
let str = "B"
let myDU : MyDU =
    match str with
    | "A" -> MyDU.A
    | "B" -> MyDU.B
    | _ -> failwith "whatever"
// val myDU : MyDU = B

However, sometimes there are many cases, which would require a lot of typing.

The Microsoft.FSharp.Reflection library allows me to get a UnionCaseInfo object:

open Microsoft.FSharp.Reflection
let myDUInfo : UnionCaseInfo =
    FSharpType.GetUnionCases(typeof<MyDU>)
    |> Array.find (fun x -> x.Name = str)
// val myDUInfo : UnionCaseInfo = MyDU.B

I would like to convert myDUInfo into a union case so as to get the same result as the code above relying on match, but without having to type the strings corresponding to all the cases.

Is this possible?





Aucun commentaire:

Enregistrer un commentaire