F#: Quotation with type definition?

安稳与你 提交于 2020-01-03 07:31:09

问题


I'm playing around with quotations and I can't see an expression pattern for type definitions. Is there really not one, or am I missing something?

<@@ type MyType (name:string) =
    member x.Name = name @@>

Gives "Unexpected keyword 'type' in quotation literal."


回答1:


You can't. You can only quote code, that is to say, any valid F# expression. Type definitions are not considered as code, but definitions.

What you might want to do is put ReflectedDefinition attribute on a type members:

type MyType (name : string) =
    [<ReflectedDefinition>] member x.Name = name

If you want to retrieve the AST of members that have ReflectedDefinition you can use Expr.TryGetReflectedDefinition function.

E.g, this sample code prints ASTs of all reflected definition members of MyType:

open Microsoft.FSharp.Quotations
open System.Reflection

type MyType (name : string) =
    [<ReflectedDefinition>] member x.Name = name

let mis = typeof<MyType>.GetMembers()
for mi in mis do
    try
        match Expr.TryGetReflectedDefinition(mi :?> MethodBase) with
        | Some(e) ->  printfn "%A" e
        | None    -> ()
    with _ -> ()
()


来源:https://stackoverflow.com/questions/3354880/f-quotation-with-type-definition

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!