F# 中的引用转换为另一种类型
Quotation Transformation in F# to another type
我有以下类型:
type Foo = { Name : string}
type Bar = {Name : string}
我有以下引用表达式:
<@ fun (x : Foo) -> x.Name = "1" @>
基本上,我想生成另一个引用表达式:
<@ fun (x : Bar) -> 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
那我可以
let f = <@ fun (x : Foo) -> x.Name = "1" @>
let transformed = subst f typeof<Bar>
let typedExpression: Expr<Bar -> bool> = downcast <@ %%transformed @>
我有以下类型:
type Foo = { Name : string}
type Bar = {Name : string}
我有以下引用表达式:
<@ fun (x : Foo) -> x.Name = "1" @>
基本上,我想生成另一个引用表达式:
<@ fun (x : Bar) -> 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
那我可以
let f = <@ fun (x : Foo) -> x.Name = "1" @>
let transformed = subst f typeof<Bar>
let typedExpression: Expr<Bar -> bool> = downcast <@ %%transformed @>