How to get literal value of TemplateHaskell variable with name

If I have a Name in TemplateHaskell and you want to know the value of the variable that it calls, provided that the variable is declared as a literal, can this be done?

 var = "foo" -- Can `contentsOf` be defined? $((contentsOf . mkName $ "var") >>= guard . (== "foo")) 
+6
source share
1 answer

In theory, yes. In practice, no.

Information about existing names is reify :: Name -> Q Info using reify :: Name -> Q Info , and for such a definition, you get a VarI value that includes the Maybe Dec field. It might seem that in some cases you could get a syntax tree for declaring a variable that allows you to extract a literal, however, current versions of GHC always return Nothing in this field , so you are out of luck for a clean TH solution.

However, TH allows arbitrary I / O operations, so you can get around this by downloading and analyzing the module yourself using something like haskell-src-exts , however I suspect this will be more of a problem than it costs.

+4
source

Source: https://habr.com/ru/post/908801/


All Articles