deepMacroExpandUntil发生了什么

时间:2012-04-14 23:27:47

标签: f# quotations

FLINQ和Quotation Visualizer示例使用了这个功能,但我无法在任何地方找到它。感谢。

1 个答案:

答案 0 :(得分: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