1
votes

I am getting the following error:

No instance for (Show Exp) arising from a use of ‘print’

In the expression: print ti1

In an equation for ‘it’: it = print ti1


When I

ghci>ti1 = Add (Lit 8) (Neg (Add (Lit 1) (Lit 2)))
ghci>print ti1

My entire code is:

data Exp = Lit Int
    | Neg Exp
    | Add Exp Exp
    
view:: Exp -> String
view (Lit n) = show n
view (Neg e) = "(-" ++ view e ++ ")"
view (Add e1 e2) = "(" ++ view e1 ++ " + " ++ view e2 ++ ")"

How can I print this string?

2

2 Answers

4
votes

How can I print this string?

You should call the view function first, so:

ghci> ti1 = Add (Lit 8) (Neg (Add (Lit 1) (Lit 2)))
ghci> print (view ti1)
"(8 + (-(1 + 2)))"

But it sufficient to just call view, since it will automatically print the result in ghci:

ghci> ti1 = Add (Lit 8) (Neg (Add (Lit 1) (Lit 2)))
ghci> view ti1
"(8 + (-(1 + 2)))"

You can furthermore make the view function the show function for Exp:

instance Show Exp where
    show = view

then it is sufficient to just query for t1, or print t1:

ghci> print ti1
(8 + (-(1 + 2)))
ghci> ti1
(8 + (-(1 + 2)))
2
votes

You need to have your data declaration derive the Show instance. So change your data declaration to:

data Exp = Lit Int
    | Neg Exp
    | Add Exp Exp deriving (Show)