views:

107

answers:

3

For example so that it works like this toString (Var x)= "x"

+1  A: 

Use the show function:

putStrLn (show x)

will print out the "x" variable. (Naturally, you don't need to use it with putStrLn, either -- show returns a string that can be used anywhere like a string.)

mipadi
A: 

I thought show is used only for constant expressions

A: 

If I understand you correctly, you're asking how to convert programming constructs into strings. You aren't concerned with what 'x' represents so much as you are that the programmer called it "x" in the source file.

You can convert data constructors into strings using some of the Scrap Your Boilerplate components. Here's an example that does just what you asked.

{-# 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.

Michael Steele