How to get function argument name in F #?

Can I write a function that returns the name of the function given as an argument?

let funName f: string =
   // returns the name of f.

For example, if I pass printfnfunName as an argument, it returns "printfn".

> funName printfn;;
val it : string = "printfn"

EDIT: I wanted to write a function docthat returns the XML documentation associated with this function.

let doc f = // returns the XML documentation of the function `f`.

To get a summary of the function using something like NuDoq , I wanted to know the name of the function.

+4
source share
2 answers

, , , , F # .

open Microsoft.FSharp.Quotations

let rec funName = function
| Patterns.Call(None, methodInfo, _) -> methodInfo.Name
| Patterns.Lambda(_, expr) -> funName expr
| _ -> failwith "Unexpected input"

let foo () = 42
funName <@ foo @>       // "foo"

, .

funName <@ printfn @>   // "PrintFormatLine"
funName <@ id @>        // "Identity"
+7

, F # 4.0 , kaefer:

open Microsoft.FSharp.Quotations

type DocumentGetter =
    static member GetName([<ReflectedDefinition>]x:Expr<_->_>) = 
        match x with
        | DerivedPatterns.Lambdas(_, Patterns.Call(_,methodInfo,_)) ->
            methodInfo.Name

let f x y = x + y

DocumentGetter.GetName f
+2

All Articles