FLINQ 和 Quotation Visualizer 示例使用了这个函数,但我在任何地方都找不到它。谢谢。
问问题
133 次
1 回答
7
该deepMacroExpandUntil
函数是一个非常简单的实用程序,只做了两件事:
ReflectedDefinition
它用方法的主体替换了所有带有属性的方法调用- 它减少了 lambda 应用程序,因此
(fun x -> x * x) (1+2)
将成为(1+2)*(1+2)
这在编写一些报价处理代码时非常有用,但较新版本的 F# 包含ExprShape
活动模式,这使得手动编写报价处理变得非常容易。
要实现类似的东西deepMacroExpandUntil
,你会写这样的东西:
open Microsoft.FSharp.Quotations
/// The parameter 'vars' is an immutable map that assigns expressions to variables
/// (as we recursively process the tree, we replace all known variables)
let rec expand vars expr =
// First recursively process & replace variables
let expanded =
match expr with
// If the variable has an assignment, then replace it with the expression
| ExprShape.ShapeVar v when Map.containsKey v vars -> vars.[v]
// Apply 'expand' recursively on all sub-expressions
| ExprShape.ShapeVar v -> Expr.Var v
| Patterns.Call(body, DerivedPatterns.MethodWithReflectedDefinition meth, args) ->
let this = match body with Some b -> Expr.Application(meth, b) | _ -> meth
let res = Expr.Applications(this, [ for a in args -> [a]])
expand vars res
| ExprShape.ShapeLambda(v, expr) ->
Expr.Lambda(v, expand vars expr)
| ExprShape.ShapeCombination(o, exprs) ->
ExprShape.RebuildShapeCombination(o, List.map (expand vars) exprs)
// After expanding, try reducing the expression - we can replace 'let'
// expressions and applications where the first argument is lambda
match expanded with
| Patterns.Application(ExprShape.ShapeLambda(v, body), assign)
| Patterns.Let(v, assign, body) ->
expand (Map.add v (expand vars assign) vars) body
| _ -> expanded
以下示例显示了函数的两个方面 - 它用函数foo
体替换函数,然后替换应用程序,因此您最终得到(10 + 2) * (10 + 2)
:
[<ReflectedDefinition>]
let foo a = a * a
expand Map.empty <@ foo (10 + 2) @>
编辑:我还将示例发布到F# snippets。
于 2012-04-15T13:39:21.407 回答