gpt4 book ai didi

f# - deepMacroExpandUntil 发生了什么

转载 作者:行者123 更新时间:2023-12-01 10:06:21 25 4
gpt4 key购买 nike

FLINQ 和 Quotation Visualizer 示例使用了此函数,但我无法在任何地方找到它。谢谢。

最佳答案

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 .

关于f# - deepMacroExpandUntil 发生了什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10158221/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com