gpt4 book ai didi

f# - fsharp 引用 Expr 列表 -> Expr 处理

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

我该怎么做才能使以下工作正常进行?

我需要创建一个接受 Expr 列表并返回 Expr 的函数(Expr 列表 -> Epxr)。

type DataObject() =
let data = System.Collections.Generic.Dictionary<int, obj>()
member this.AddValue propertyIndex value = data.Add(propertyIndex, value)
member this.GetValue propertyIndex =
match data.TryGetValue propertyIndex with
| (true, value) -> value
| (false, _) -> box "property not found"

...
(fun args ->
<@@
let data = new DataObject(values)
args |> List.iteri (fun i arg -> data.AddValue i <@@ (%%arg) : string @@>)
data
@@>)

我创建了 DataObject 类型来添加 args 的值。但不知何故我无法设法让代码遍历不同的 args (args.[0] .. args.[i])。我收到的消息是:

The variable 'arg' is bound in a quotation but is used as part of a spliced expression. This is not permitted since it may escape its scope.

如果我显式访问 args (args.[0], args.[1], ...) 解决方案有效,但一旦我尝试添加迭代,我就会遇到问题。因为 args 列表的长度是灵活的,所以这对我来说不是一个可行的解决方案。

我尝试了不同的方法,但都没有成功。有什么解决办法吗?

[编辑]

在我的解决方案中添加 Tomas 的反馈给我带来了这个:

type DataObject(values: obj []) =
let propertyMap = new Map<int, obj>(values |> Seq.mapi (fun i value -> (i, value)))
member this.GetValue propertyIndex : obj =
match propertyMap.TryFind propertyIndex with
| Some(value) -> value
| None -> box "property not found"

(fun args ->
let boxedArgs =
args |> List.map (fun arg ->
match arg with
| Quotations.Patterns.Var var ->
if var.Type = typeof<int> then
<@@ (box (%%arg: int)) @@>
else if var.Type = typeof<string> then
<@@ (box (%%arg: string)) @@>
else if var.Type = typeof<System.Guid> then
<@@ (box (%%arg: System.Guid)) @@>
else
failwith ("Aha: " + var.Type.ToString())
| _ -> failwith ("Unknown Expr as parameter"))
<@@ new DataObject(%%(Expr.NewArray(typeof<obj>, boxedArgs))) @@>))

这有效!唯一的问题是我想摆脱 if ... else 构造以获得正确的转换。有什么想法吗?

最佳答案

这是一个棘手的问题!要理解为什么您的代码不起作用,您需要清楚地区分两个级别 - 在一个级别 (meta),您正在编写引文,在另一个级别 (base ) 您正在使用数据对象运行一些代码。

您的代码不起作用的原因是 args 是元级别的表达式列表,您正试图在基本级别对其进行迭代。迭代需要在元级别发生。

解决此问题的一种方法是在元级别进行迭代并生成一个函数列表,这些函数为所有参数调用 AddValue。然后你可以组合函数:

(fun args -> 
// Given arguments [a0; a1; ...] Generate a list of functions:
//
// [ fun data -> data.AddValue 0 a0; data ]
// [ fun data -> data.AddValue 1 a1; data ... ]
args
|> List.mapi (fun i arg ->
<@ fun (data:DataObject) -> data.AddValue i (%%arg : string); data @>)

// Compose all the functions just by calling them - note that the above functions
// take DataObject, mutate it and then return it. Given [f0; f1; ...] produce:
//
// ... (f1 (f0 (new DataObject())))
//
|> List.fold (fun dobj fe -> <@ (%fe) (%dobj) @>) <@ new DataObject() @> )

这写起来很有趣,但它变得非常复杂。在实践中,您可以通过向数据对象添加 AddValues 方法(采用 obj[])并使用 Expr.NewArray 使事情变得容易得多创建包含所有参数值(来自元级别)的单个数组(在基本级别):

<@@ let d = new DataObject()
d.AddValues(%(Expr.NewArray(typeof<obj>, args)))
d @@>

关于f# - fsharp 引用 Expr 列表 -> Expr 处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19881410/

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