gpt4 book ai didi

types - 在 F# 中创建提供类型的列表

转载 作者:行者123 更新时间:2023-12-01 09:54:07 25 4
gpt4 key购买 nike

我正在尝试将基本的 JSON 类型提供程序添加到 fsharpx .目前我正在为 JSON 数组而苦苦挣扎。考虑以下测试用例:

type SimpleArray = JSON< "{\"items\":[{\"id\":\"Open\"},{\"id\":\"Pause\"}]}">

let a = SimpleArray()

[<Test>]
let ``Can parse simple arrays``() =
a.items.[0].id
|> should equal "Open"

a.items.[1].id
|> should equal "Pause"

想法是我想使用数组中的第一个元素来获取集合元素的类型。然后我想向 SimpleArray 类型添加一个属性“items”,它给出了这个新类型的列表。

代码可以在github repo中找到Github .有趣的部分从第 38 行开始。如您所见,整个过程必须是递归的,因为 JArray 还可以包含嵌套的 JArray。

| JArray list ->
let newType = annotateAsJson list.[0] (runtimeType<obj> (ownerTy.Name + "_" + e.Key))
ownerTy.AddMember newType
Some(provideProperty
e.Key
newType // TODO: make this a list
(fun args -> Expr.Coerce(<@@ (%%args.[0] : obj) @@>, newType)) // TODO: return the list
:> MemberInfo)

谢谢,史蒂芬

最佳答案

问题到底是什么?看起来您需要提供多种类型(例如,在您的示例中,您有包含 items 的外部类型,然后是包含 id 的内部类型)。您可能希望内部类型是外部类型中的嵌套类型。然后使提供的 items 属性包含内部类型的列表。您是否有遇到麻烦的特定方面?

编辑

如果只是想知道如何自己创建 Type 实例,您试过了吗

typedefof<_ list>.MakeGenericType(newType)

这假定基础值本身是一个 obj 列表,这是必需的,因为 newType 删除为 obj

关于types - 在 F# 中创建提供类型的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9561653/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com