[英]How to get the name of function argument in F#?
我可以編寫一個函數來返回作為參數給出的函數的名稱嗎?
let funName f: string =
// returns the name of f.
例如,如果我將printfn
作為參數傳遞給funName,則返回“printfn”。
> funName printfn;;
val it : string = "printfn"
編輯:我想編寫一個函數doc
,它返回與給定函數關聯的XML文檔。
let doc f = // returns the XML documentation of the function `f`.
要使用NuDoq之類的東西檢索函數的摘要,我想知道函數的名稱。
我無法想象為什么你會想要這樣做,我不認為有辦法用反射來做到這一點,但F#Code Quotations可能會讓你到達那里。
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"
請注意,從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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.