Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function to output function name

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

A possible type could be (a -> b) -> String.

like image 618
Stuart Paton Avatar asked Mar 07 '13 13:03

Stuart Paton


People also ask

What is the function name?

The name property of the Function object is used to get the function's name. name is a read-only property of the Function object.

What is @function name in Python?

Keyword def that marks the start of the function header. A function name to uniquely identify the function. Function naming follows the same rules of writing identifiers in Python. Parameters (arguments) through which we pass values to a function. They are optional.

What is __ func __ in Python?

It's this method object that has the __func__ attribute, which is just a reference to the wrapped function. By accessing the underlying function instead of calling the method, you remove the typecheck, and you can pass in anything you want as the first argument.


1 Answers

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.

like image 172
Don Stewart Avatar answered Oct 31 '22 16:10

Don Stewart