问题描述
Haskell有可能实现一个函数返回它自己的函数名吗?
可能的类型可能是(a - > b) - >字符串
。
您需要一个接受函数参数的函数,并返回定义站点变量名称与该函数的名称相对应吗?
这不可能没有元编程,这通常是您做错某事的标志:)。
但假设你不是,一种方法是通过 ,它可以获得唯一的名称(编译器如何命名)。例如
Prelude Language.Haskell.TH> :set -XTemplateHaskell
Prelude Language.Haskell.TH>让f x y = x + y
Prelude Language.Haskell.TH> $(stringE。show =< reify'f)
VarI f_1627394057
(ForallT [PlainTV a_1627394063]
[ClassP GHC.Num.Num [VarT a_1627394063] ]
(AppT(AppT ArrowT(VarT a_1627394063))
(AppT(AppT ArrowT(VarT a_1627394063))
(VarT a_1627394063))))
Nothing(固定9 InfixL)
现在我们对变量有了很多了解。所以你可以通过给函数传递一个Name(通过'f)而不是f本身来玩游戏。
尽管你肯定处于反思和元编程的世界,所以这将有助于更多地了解你正在尝试做什么。
Is it possible in Haskell to implement a function which returns its own function name?
A possible type could be (a -> b) -> String
.
You want a function that takes a function argument, and returns the definition site variable name that corresponds to the name of that function?
This isn't possibly without meta-programming, which is usually a sign you're doing something wrong :).But assuming you're not, one way to achieve something in the right direction is via Template Haskell, which can get at unique names (how the compiler names things). E.g.
Prelude Language.Haskell.TH> :set -XTemplateHaskell
Prelude Language.Haskell.TH> let f x y = x + y
Prelude Language.Haskell.TH> $( stringE . show =<< reify 'f )
"VarI f_1627394057
(ForallT [PlainTV a_1627394063]
[ClassP GHC.Num.Num [VarT a_1627394063]]
(AppT (AppT ArrowT (VarT a_1627394063))
(AppT (AppT ArrowT (VarT a_1627394063))
(VarT a_1627394063))))
Nothing (Fixity 9 InfixL)"
And now we know a lot about the variable. So you can play games by passing a Name to the function (via 'f) rather than f itself.
You are certainly in the world of reflection and meta-programming though, so it would help to know more about what you are trying to do.
这篇关于函数输出函数名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!