作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
FLINQ 和 Quotation Visualizer 示例使用了此函数,但我无法在任何地方找到它。谢谢。
最佳答案
deepMacroExpandUntil
函数是一个非常简单的实用程序,它只做了两件事:
ReflectedDefinition
属性(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/
FLINQ 和 Quotation Visualizer 示例使用了此函数,但我无法在任何地方找到它。谢谢。 最佳答案 deepMacroExpandUntil 函数是一个非常简单的实用程序,它只做了
我是一名优秀的程序员,十分优秀!