如何获取F#中的函数自变量名称? [英] How to get the name of function argument in F#?

查看:70
本文介绍了如何获取F#中的函数自变量名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以编写一个函数来返回以参数形式给出的函数名称吗?

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

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

例如,如果我将printfn作为参数传递给funName,它将返回"printfn".

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

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

我想编写一个函数doc,该函数返回与给定函数关联的XML文档.

I wanted to write a function doc which returns the XML documentation associated with the given function.

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

要使用 NuDoq 之类的内容来检索函数的摘要,我想知道功能.

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

推荐答案

我无法想象您为什么要这样做,而且我不认为有办法通过反射来做到这一点,但是

I cannnot imagine why you would want to do this and I do not think that there's a way to do this with reflection, but F# Code Quotations might get you halfway there.

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"

但是请注意,某些预定义的库函数具有不同的内部名称.

But note that certain predefined library functions have a divergent internal name.

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

这篇关于如何获取F#中的函数自变量名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆