输出函数名的函数 [英] Function to output function name

查看:24
本文介绍了输出函数名的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 Haskell 中实现一个返回自己函数名的函数?

Is it possible in Haskell to implement a function which returns its own function name?

可能的类型可以是 (a -> b) ->字符串.

推荐答案

您想要一个接受函数参数并返回与该函数名称对应的定义站点变量名称的函数吗?

You want a function that takes a function argument, and returns the definition site variable name that corresponds to the name of that function?

这不可能没有元编程,这通常表明你做错了:).但假设你不是,朝着正确方向实现某事的一种方法是通过 Template Haskell,它可以得到在唯一的名称(编译器如何命名事物).例如

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)"

现在我们对变量有了很多了解.因此,您可以通过将 Name 传递给函数(通过 'f)而不是 f 本身来玩游戏.

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.

这篇关于输出函数名的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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