Search code examples
haskellmetaprogrammingcode-inspection

How can one print the name of an identifier or binding in Haskell?


Supose I want to print the name and the value of a "variable" in Haskell. The name is known at compile time! Is there a better way than in the following example?

module V
(e, c, eV, h, hbar, nm, k, viewAllConstants) where
import Text.Printf
c = 2.99792458e8::Double
e = exp(1)
eV = 1.602176565e-19
h = 6.62606957e-34
hbar = h/(2*pi)
nm = 1e-9
k = 1.3806488e-23
viewAllConstants = do
    putStr ((\a b -> (foldl (++) "" ( zipWith (++) a (map (printf " = %.2e\n") b))))
        ["c", "e", "eV", "h", "hbar", "nm", "k"]
        [c, e, eV, h, hbar, nm, k] )

Please post a working code example (runhaskell) in your answer!


Solution

  • You can do it! You just can't do it like you're thinking. Some language implementations use dictionaries to represent the environments in which expressions are evaluated. Some of the more foolish ones expose this mechanism to programmers. This is foolish because it prevents the implementors from switching to faster techniques in the future. Haskell does not do anything like that, except maybe in the type checker. But that doesn't stop you from building and using such dictionaries yourself!

    If you're dealing with a bunch of things of the same type, you're in luck—you can use a Map or a trie to connect names with values. If you need things of various types, your life gets more complicated—see HList records for example.

    All that said, I think you should think carefully about how much you really want this. It's kind of unusual.