Is it possible in Haskell to implement a function which returns its own function name?
A possible type could be (a -> b) -> String
.
Is it possible in Haskell to implement a function which returns its own function name?
A possible type could be (a -> b) -> String
.
Am I missing something? This function returns its own function name.
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.
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.
To clarify something mentioned in dons' post: no functions have names in Haskell. There are bindings which may bind functions, but if I had such a function (call it
getName
) as you seek then what would you expect this to return:I don't know what you need it for, but maybe a simplistic solution suffices? Like so:
which you can use as follows:
You can then write your own version of
(.)
:In ghci:
You'll have to reimplement your own versions of
map
,filter
and so on, and you're bound to run into other problems later, but maybe this is all you need...