F#中的引号转换为另一种类型
我有以下几种:F#中的引号转换为另一种类型,f#,quotations,F#,Quotations,我有以下几种: type Foo = { Name : string} type Bar = {Name : string} 我引用了下面这句话: <@ fun (x : Foo) -> x.Name = "1" @> x.Name=“1”@> 基本上,我想从中生成另一个引用的表达式,如下所示: <@ fun (x : Bar) -> x.Name = "1" @> x.Name=“1”@> 我该怎么做?好的,我得到了以下解决方案: let subs
type Foo = { Name : string}
type Bar = {Name : string}
我引用了下面这句话:
<@ fun (x : Foo) -> x.Name = "1" @>
x.Name=“1”@>
基本上,我想从中生成另一个引用的表达式,如下所示:
<@ fun (x : Bar) -> x.Name = "1" @>
x.Name=“1”@>
我该怎么做?好的,我得到了以下解决方案:
let subst expression newType =
let newVar name = Var.Global(name,newType)
let rec substituteExpr expression =
match expression with
| Call(Some (ShapeVar var),mi,other) ->
Expr.Call(Expr.Var(newVar var.Name), newType.GetMethod(mi.Name),other)
| PropertyGet (Some (ShapeVar var) ,pi, _) ->
Expr.PropertyGet(Expr.Var( newVar var.Name), newType.GetProperty(pi.Name),[])
| ShapeVar var -> Expr.Var <| newVar var.Name
| ShapeLambda (var, expr) ->
Expr.Lambda (newVar var.Name, substituteExpr expr)
| ShapeCombination(shapeComboObject, exprList) ->
RebuildShapeCombination(shapeComboObject, List.map substituteExpr exprList)
substituteExpr expression
让subst表达式newType=
让newVar name=Var.Global(名称,newType)
让rec替换expr表达式=
匹配表达式
|调用(部分(ShapeVar)、mi和其他)->
Expr.Call(Expr.Var(newVar.Name)、newType.GetMethod(mi.Name)、other)
|PropertyGet(部分(ShapeVar)、pi)->
Expr.PropertyGet(Expr.Var(newVar.Name),newType.GetProperty(pi.Name),[])
|形状变量->表达式变量
表达式Lambda(newVar变量名称,substituteExpr Expr)
|ShapeCombination(shapeComboObject,exprList)->
重建ShapeCombination(shapeComboObject,List.map substituteExpr exprList)
替换EXPR表达式
那我就可以了
let f = <@ fun (x : Foo) -> x.Name = "1" @>
let transformed = subst f typeof<Bar>
let typedExpression: Expr<Bar -> bool> = downcast <@ %%transformed @>
让f=x.Name=“1”@>
设transformed=subst f typeof
let typedExpression:Expr bool>=向下广播