FLINQとQuotationVisualizerのサンプルはこの関数を使用しましたが、どこにも見つかりません。ありがとう。
1 に答える
7
このdeepMacroExpandUntil
関数は、2つのことだけを行う非常に単純なユーティリティでした。
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#スニペットにも投稿しました。
于 2012-04-15T13:39:21.407 に答える