(Template?) Haskell get name of function at run or compile time

231 views Asked by At

I have a list of imported functions as a top level binding. I want to get the name of each function in the list without hardcoding them. Because the list is known at compile time using Template Haskell it should be possible to get the names of every list entry, but I haven't yet figured out how to do this.

import qualified Module (function1, function2)

functions = [Module.function1, Module.function2]

main = do
    let names = ?
    print names

Is this even possible or is there another more elegant way?

Edit: I found a way, but it's rather ugly.

functions :: [(f, String)]
functions = $(ListE <$> sequence [TupE <$> sequence [
          pure $ Just $ VarE 'Module.Function
        , Just <$> stringE (show 'Module.Function)
    ]])
1

There are 1 answers

0
Daniel Wagner On

Instead of trying to get the names of entities inside a definition, consider creating the definition given the collection of names instead.

functionNames :: [Name]
functionNames = [ 'function1, 'function2 ]

-- in another module
functions = $(listE (varE <$> functionNames))