我正试图从字符串中创建 DU(Discriminated Union) 报告。我唯一看到的方法是通过枚举使用 Microsoft.FSharp.Reflection.FSharpType.GetUnionCases
获得 DU 报告,然后选择与字符串匹配的 UnionCase
(使用 .Name
),然后使用 FSharpValue.MakeUnion
创建实际的 DU 报告。
有没有更简单/更优雅的方法来做到这一点? 在我的场景中,我有一个包含数百个关键字的 DU,我必须从文件中读取字符串(关键字)并将它们转换为类型。 我通过将情况放入地图中进行了一些“优化”,但我希望有更好的方法来执行此操作。 例如,我有以下内容:
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
]
type Dict<'A> = Dict of Dictionary<string,'A> with static member (?) (Dict d, key) = ...
- kaefer