在C#中,我可以使用表达式树轻松地创建对象图的字符串表示。
public static string GetGraph<TModel, T>(TModel model, Expression<Func<TModel, T>> action) where TModel : class
{
var method = action.Body as MethodCallExpression;
var body = method != null ? method.Object != null ? method.Object as MemberExpression : method.Arguments.Any() ? method.Arguments.First() as MemberExpression : null : action.Body as MemberExpression;
if (body != null)
{
string graph = GetObjectGraph(body, typeof(TModel))
return graph;
}
throw new Exception("Could not create object graph");
}
在F#中,我一直在看引文试图做同样的事情,并且无法弄明白。我曾尝试使用PowerPack库将引号转换为Expression,但到目前为止还没有运气,而且互联网上的信息在这个主题上似乎相当稀疏。
如果输入为:
let result = getGraph myObject <@ myObject.MyProperty @>
输出应为“myobject.MyProperty”
答案 0 :(得分:5)
您可以在fsi session中看到从引号表达式中获得的内容:
> let v = "abc"
> <@ v.Length @>;;
val it : Expr<int>
= PropGet (Some (PropGet (None, System.String v, [])), Int32 Length, [])
> <@ "abc".Length @>;;
val it : Expr<int>
= PropGet (Some (Value ("abc")), Int32 Length, [])
您可以找到可用于解析qoutations的所有活动模式的描述
manual \ FSharp.Core \ Microsoft.FSharp.Quotations.Patterns.html
在您的F#安装目录下或msdn site
有很好的Chris Smith的书“Programming F#”,其中有一章名为“Quotations”:)
所以,毕竟,只是尝试编写简单的解析器:
open Microsoft.FSharp.Quotations
open Microsoft.FSharp.Quotations.Patterns
open Microsoft.FSharp.Quotations.DerivedPatterns
let rec getGraph (expr: Expr) =
let parse args =
List.fold_left (fun acc v -> acc ^ (if acc.Length > 0 then "," else "") ^ getGraph v) "" args
let descr s = function
| Some v -> "(* instance " ^ s ^ "*) " ^ getGraph v
| _ -> "(* static " ^ s ^ "*)"
match expr with
| Int32 i -> string i
| String s -> sprintf "\"%s\"" s
| Value (o,t) -> sprintf "%A" o
| Call (e, methodInfo, av) ->
sprintf "%s.%s(%s)" (descr "method" e) methodInfo.Name (parse av)
| PropGet(e, methodInfo, av) ->
sprintf "%s.%s(%s)" (descr "property" e) methodInfo.Name (parse av)
| _ -> failwithf "I'm don't understand such expression's form yet: %A" expr
P.S。当然,您需要一些代码才能将AST转换为人类可读的格式。
答案 1 :(得分:3)