I am trying to create DU cases from strings. The only way I can do this is to list the DU cases through Microsoft.FSharp.Reflection.FSharpType.GetUnionCases , and then select UnionCase that matches the string (using .Name ), and then make the actual DU case from it using FSharpValue.MakeUnion .
Isn't there an easier / more elegant way to do this? In my scenario, I have a DU with several hundred cases for keywords. I have to read lines (keywords) from a file and make types out of them. I did some βoptimizationβ by putting matters at stake, but I was hoping there would be a better way to do this.
I have the following, for example:
type Keyword = | FOO | BAR | BAZ | BLAH let mkKeywords (file: string) = use sr = new StreamReader(file) let caseMap = FSharpType.GetUnionCases(typeof<Keyword>) |> Array.map (fun c -> (c.Name, FSharpValue.MakeUnion(c, [||]) :?> Keyword)) |> Map.ofArray [ while not sr.EndOfStream do let l = sr.ReadLine().Trim() match caseMap.TryFind l with | Some c -> yield c | None -> failwith <| "Could not find keyword: " + l ]
siki
source share