在构建表达式树时遇到了一些问题。当使用代码引号时,我可以做同样的事情,但到目前为止,我还没有通过表达式来做到这一点。
首先看一下我通过代码引用的方法
open Microsoft.FSharp.Quotations
open Microsoft.FSharp.Quotations.Patterns
open Microsoft.FSharp.Quotations.DerivedPatterns
type Container<'a> = Container of 'a
type FromD<'a> = {a: Container<'a>; b: Container<'a>}
type ToD<'a> = {a: Container<'a>; b: Container<'a>}
let private eval e = QuotationEvaluator.Evaluate e
let f1 f =
let ex =
<@
fun (x:FromD<'a>) ->
{
a = f x.a;
b = f x.b
}
: ToD<'b>
@>
eval ex
以上签名为(Container<'a> -> Container<'b>) -> (FromD<'a> -> ToD<'b>)
。这正是我想要的。f1
生成的表达式树为
Lambda (x,
NewRecord (ToD`1,
Application (ValueWithName (<fun:r1@60>, f),
PropertyGet (Some (x), a, [])),
Application (ValueWithName (<fun:r1@60>, f),
PropertyGet (Some (x), b, []))))
现在一些测试代码将FromD
转换为ToD
,并对Container
也应用转换
let transform (Container (v:'a)) : Container<'b> = Container (sprintf "%A" v)
[<Test>]
let ``test F1`` () =
let r1 = f1 transform {a = Container true; b = Container true}
let r2 = f1 transform {a = Container 1; b = Container 2}
printfn "F1: %A, F1: %A" r1 r2
一切都像我想要的一样,r1
和r2
产生了预期的结果。
现在我想重新创建f1
使用表达式而不是代码引号。
这是我的第一次尝试(使用一些辅助函数)
//fields :: Type -> PropertyInfo []
let fields t = FSharpType.GetRecordFields t
//nameMap :: Type -> Map<string,PropertyInfo>
let nameMap t =
t
|> fields
|> Array.map (fun x -> x.Name, x)
|> Map.ofArray
let f2<'x, 't> f =
let xt = typeof<'x>
let tt = typeof<'t>
let ps = nameMap xt
let x = Var("x", xt)
let vx = Expr.Var(x)
let fnv = Expr.ValueWithName(f, "f")
let ex =
Expr.Lambda(x,
Expr.NewRecord(tt,
[
Expr.Application(fnv, Expr.PropertyGet(vx, ps.Item "a", []))
Expr.Application(fnv, Expr.PropertyGet(vx, ps.Item "b", []))
]))
let ex2 : Expr<'x -> 't> = ex |> Expr.Cast
let ex3 = eval ex2
ex3
和一些测试代码
let ``test F2`` () =
let r3 = (f2<FromD<bool>, ToD<string>> transform) {a = Container true; b = Container true}
printfn "R3 %A" r3
首先,在这个例子中f2
的签名是(Container<obj> -> Container<string>) -> ('x -> 't)
而不是(Container<'a> -> Container<'b>) -> (FromD<'a> -> ToD<'b>)
因此,不知何故,类型推断器在这一点上有点急于。
这将导致下面的错误消息
System.ArgumentException : Type mismatch when building 'f': function argument type doesn't match. Expected 'tst+Container`1[System.Boolean]', but received type 'tst+Container`1[System.Object]'.
Parameter name: receivedType
at Microsoft.FSharp.Quotations.PatternsModule.checkTypesSR[a] (System.Type expectedType, System.Type receivedType, a name, System.String threeHoleSR) [0x00019] in <57acd2f6dff9fae1a7450383f6d2ac57>:0
at Microsoft.FSharp.Quotations.PatternsModule.checkAppliedLambda (Microsoft.FSharp.Quotations.FSharpExpr f, Microsoft.FSharp.Quotations.FSharpExpr v) [0x00084] in <57acd2f6dff9fae1a7450383f6d2ac57>:0
at Microsoft.FSharp.Quotations.PatternsModule.mkApplication (Microsoft.FSharp.Quotations.FSharpExpr v_0, Microsoft.FSharp.Quotations.FSharpExpr v_1) [0x00001] in <57acd2f6dff9fae1a7450383f6d2ac57>:0
at Microsoft.FSharp.Quotations.FSharpExpr.Application (Microsoft.FSharp.Quotations.FSharpExpr functionExpr, Microsoft.FSharp.Quotations.FSharpExpr argument) [0x00001] in <57acd2f6dff9fae1a7450383f6d2ac57>:0
at tst.f2[x,t] (Microsoft.FSharp.Core.FSharpFunc`2[T,TResult] f) [0x0005f] in <582303e818eafa12a7450383e8032358>:0
at tst.test F2 () [0x00005] in <582303e818eafa12a7450383e8032358>:0
at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (System.Reflection.MonoMethod,object,object[],System.Exception&)
at System.Reflection.MonoMethod.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00038] in <8cd55ece525b4760b63de40980e005aa>:0
因此,在构建表达式树时似乎存在一些问题,因为类型推断器说我的函数具有bool
类型参数,但实际参数是object
。
现在我可以通过这样重写函数来克服这个问题
let f2<'x, 't> f =
let xt = typeof<'x>
let tt = typeof<'t>
let ps = nameMap xt
let x = Var("x", xt)
let vx = Expr.Var(x)
let fnv = Expr.ValueWithName(f, typeof<Container<bool> -> Container<string>>, "f")
let ex =
Expr.Lambda(x,
Expr.NewRecord(tt,
[
Expr.Application(fnv, Expr.PropertyGet(vx, ps.Item "a", []))
Expr.Application(fnv, Expr.PropertyGet(vx, ps.Item "b", []))
]))
let ex2 : Expr<'x -> 't> = ex |> Expr.Cast
let ex3 = eval ex2
ex3
在本例中,我强制ValueWithName
为特定类型,而不是f.GetType()
。
我为这个例子创建了一个非常特定的类型(typeof<Container<bool> -> Container<string>>
),也使这个例子更容易理解。
这将帮助我度过施工阶段,也与演员一起工作。
构造的表达式树也和前面一样。
但是现在它在求值时崩溃了,并显示以下错误信息
System.ArgumentException : Argument types do not match
at System.Linq.Expressions.Expression.Constant (System.Object value, System.Type type) [0x00049] in <4a648327db854c86ab0ece073e38f4b3>:0
at FSharp.Quotations.Evaluator.QuotationEvaluationTypes.LetRecConvExpr (FSharp.Quotations.Evaluator.QuotationEvaluationTypes+ConvEnv env, Microsoft.FSharp.Core.FSharpOption`1[T] letrec, Microsoft.FSharp.Quotations.FSharpExpr inp) [0x00185] in <56703c1ea378c767a74503831e3c7056>:0
at FSharp.Quotations.Evaluator.QuotationEvaluationTypes.ConvExpr (FSharp.Quotations.Evaluator.QuotationEvaluationTypes+ConvEnv env, Microsoft.FSharp.Quotations.FSharpExpr inp) [0x00001] in <56703c1ea378c767a74503831e3c7056>:0
at FSharp.Quotations.Evaluator.QuotationEvaluationTypes.LetRecConvExpr (FSharp.Quotations.Evaluator.QuotationEvaluationTypes+ConvEnv env, Microsoft.FSharp.Core.FSharpOption`1[T] letrec, Microsoft.FSharp.Quotations.FSharpExpr inp) [0x02065] in <56703c1ea378c767a74503831e3c7056>:0
at FSharp.Quotations.Evaluator.QuotationEvaluationTypes.ConvExpr (FSharp.Quotations.Evaluator.QuotationEvaluationTypes+ConvEnv env, Microsoft.FSharp.Quotations.FSharpExpr inp) [0x00001] in <56703c1ea378c767a74503831e3c7056>:0
at FSharp.Quotations.Evaluator.QuotationEvaluationTypes+ConvExprs@703.Invoke (Microsoft.FSharp.Quotations.FSharpExpr inp) [0x00001] in <56703c1ea378c767a74503831e3c7056>:0
at Microsoft.FSharp.Primitives.Basics.List.map[T,TResult] (Microsoft.FSharp.Core.FSharpFunc`2[T,TResult] mapping, Microsoft.FSharp.Collections.FSharpList`1[T] x) [0x0003f] in <57acd2f6dff9fae1a7450383f6d2ac57>:0
at Microsoft.FSharp.Collections.ListModule.Map[T,TResult] (Microsoft.FSharp.Core.FSharpFunc`2[T,TResult] mapping, Microsoft.FSharp.Collections.FSharpList`1[T] list) [0x00001] in <57acd2f6dff9fae1a7450383f6d2ac57>:0
at FSharp.Quotations.Evaluator.QuotationEvaluationTypes.ConvExprs (FSharp.Quotations.Evaluator.QuotationEvaluationTypes+ConvEnv env, Microsoft.FSharp.Collections.FSharpList`1[T] es) [0x00007] in <56703c1ea378c767a74503831e3c7056>:0
at FSharp.Quotations.Evaluator.QuotationEvaluationTypes.LetRecConvExpr (FSharp.Quotations.Evaluator.QuotationEvaluationTypes+ConvEnv env, Microsoft.FSharp.Core.FSharpOption`1[T] letrec, Microsoft.FSharp.Quotations.FSharpExpr inp) [0x020e6] in <56703c1ea378c767a74503831e3c7056>:0
at FSharp.Quotations.Evaluator.QuotationEvaluationTypes.ConvExpr (FSharp.Quotations.Evaluator.QuotationEvaluationTypes+ConvEnv env, Microsoft.FSharp.Quotations.FSharpExpr inp) [0x00001] in <56703c1ea378c767a74503831e3c7056>:0
at FSharp.Quotations.Evaluator.QuotationEvaluationTypes.LetRecConvExpr (FSharp.Quotations.Evaluator.QuotationEvaluationTypes+ConvEnv env, Microsoft.FSharp.Core.FSharpOption`1[T] letrec, Microsoft.FSharp.Quotations.FSharpExpr inp) [0x027f0] in <56703c1ea378c767a74503831e3c7056>:0
at FSharp.Quotations.Evaluator.QuotationEvaluationTypes.ConvExpr (FSharp.Quotations.Evaluator.QuotationEvaluationTypes+ConvEnv env, Microsoft.FSharp.Quotations.FSharpExpr inp) [0x00001] in <56703c1ea378c767a74503831e3c7056>:0
at FSharp.Quotations.Evaluator.QuotationEvaluationTypes.Conv[a] (a e, System.Boolean eraseEquality) [0x0001d] in <56703c1ea378c767a74503831e3c7056>:0
at FSharp.Quotations.Evaluator.QuotationEvaluationTypes.CompileImpl[a] (a e, System.Boolean eraseEquality) [0x00001] in <56703c1ea378c767a74503831e3c7056>:0
at FSharp.Quotations.Evaluator.QuotationEvaluationTypes.Compile[a] (a e) [0x00001] in <56703c1ea378c767a74503831e3c7056>:0
at FSharp.Quotations.Evaluator.QuotationEvaluator.Evaluate[T] (Microsoft.FSharp.Quotations.FSharpExpr`1[T] e) [0x00001] in <56703c1ea378c767a74503831e3c7056>:0
at tst.f2[x,t] (Microsoft.FSharp.Core.FSharpFunc`2[T,TResult] f) [0x000f5] in <5823081418eafa12a745038314082358>:0
at tst.test F2 () [0x00005] in <5823081418eafa12a745038314082358>:0
at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (System.Reflection.MonoMethod,object,object[],System.Exception&)
at System.Reflection.MonoMethod.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00038] in <8cd55ece525b4760b63de40980e005aa>:0
有谁知道是怎么回事吗?
f2
的类型以'x -> 't
结束,因为这正是您在这一行中指定的:
let ex2 : Expr<'x -> 't> = ex |> Expr.Cast
f2
甚至不知道FromD
和ToD
这样的东西的存在,所以它不可能在它的类型中有它们。
但是,如果您在测试中查看r3
的第一部分的类型,您将看到它是FromD<_> -> ToD<_>
,因为它们被指定为f2
的类型参数,分别代表'x
和't
。
至于Container<obj>
——它实际上比你想象的要差一点。如果单独查看f2
,您将看到它的类型是obj -> 'x -> 't
。这是因为f2
的主体中没有任何内容提示f
应该是什么类型。所以它被强制为obj
作为所有的最终超类型。
当您实际使用 f2
和参数transform
作为参数f
时,编译器会将f
的类型固定为Container<_> -> Container<string>
(因为这是transform
的类型),后来变成Container<obj> -> Container<string>
,因为程序中没有任何东西可以进一步约束该类型。
从上面来看,修复是不言而喻的:只需显式声明f
的类型。
let f2<'x, 't, 'a, 'b> (f: Container<'a> -> Container<'b>) =
...
这将在第一个应用程序之前为您提供正确的类型。
但小心!
由于所有的处理都发生在运行时,编译器不能保证所有地方的类型安全。因此,你自己必须小心防范它们。以下是代码所依赖的一些(尽管可能不是全部)在编译时不能强制执行的东西:
- 类型
'x
必须是字段名为a
和b
且类型为'a
的记录。 - 类型
't
必须是包含两个字段的记录,分别命名为a
和b
,以特定的顺序声明,并且都具有类型'b
。
如果你只是想"在记录上映射",我可能会考虑一个不那么雄心勃勃的解决方案,例如:
let fromDMap f (fromD: FromD<_>) : ToD<_> = { a = f fromD.a; b = f fromD.b }
// Usage:
let r3 = fromDMap transform {a = Container true; b = Container true}
当然,如果你想创建一个"泛型"函数来映射任意类型的同名字段,这种方法就行不通了。但是,我想冒昧地说,这样的函数可能有点太泛型了。
注:你的函数transform
有一个声明的类型,它比函数实际的类型更通用。声明的返回类型是Container<'b>
,但它实际返回的是Container<string>
。因此,'b
被约束为string
。