How do I convert a variable to a string?
2 answers
If I understand you correctly, you are asking how to convert programming constructors to strings. You don't care what "x" represents as much as you do, what the programmer called "x" in the source file.
You can convert data constructors to strings using some of the Scrap Your Boilerplate components. Here's an example that only does what you asked for.
{-# LANGUAGE DeriveDataTypeable #-}
module Main where
import Data.Data
data Var a = Var a
data X = X deriving (Data, Typeable)
toString :: Data a => Var a -> String
toString (Var c) = show (toConstr c)
main :: IO ()
main = putStrLn $ "toString (Var x)= " ++ show (toString (Var X))
output:
$ ghci Test.hs
GHCi, version 6.10.4: http://www.haskell.org/ghc/ :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer ... linking ... done.
Loading package base ... linking ... done.
[1 of 1] Compiling Main ( Test.hs, interpreted )
Ok, modules loaded: Main.
*Main> main
toString (Var X)= "X"
*Main>
For a real example, I suggest looking at the RJson library .
0
source to share