1

Here is the code:

data Tree t = NilT
            | Node t (Tree t) (Tree t)

instance Show (Tree t) where
  show NilT = ""
  show Node t l r = (show t) ++ ", " ++ (show l) ++ ", " ++ (show r)

how to use "show" in "t show" with the default setting and use "show" with the tree data with the definition given by myself?

ocharles
  • 6,172
  • 2
  • 35
  • 46
  • Is this a homework question? It looks suspiciously similar to the recent questions http://stackoverflow.com/questions/7478878/show-function-for-polymorphic-type and http://stackoverflow.com/questions/7479252/how-to-define-that-a-generic-type-is-printable – ivanm Sep 21 '11 at 01:27

2 Answers2

4

In order to use show t, you must add the constraint Show t to your instance definition.

instance Show t => Show (Tree t) where
    show NilT = ""
    show (Node t l r) = show t ++ ", " ++ show l ++ ", " ++ show r

You were also missing parenthesis around your pattern Node t l r, and I removed the parenthesis around the calls to show, as they were redundant since function application already has the highest precedence.

hammar
  • 138,522
  • 17
  • 304
  • 385
  • You also might want to look at `hlint` which does some parentheses-fixing stuff for you (among other things). – Tyler Sep 21 '11 at 17:04
1

Just a side note: There is a function Data.List.intersperse for putting a value between list elements.

show (Node t l r) = concat $ intersperse ", " [show t, show l, show r]

Or shorter, as hammar pointed out:

show (Node t l r) = intercalate ", " [show t, show l, show r]

Unfortunately you can't write map show [t, l, r], as the list elements need to have a unique type.

Landei
  • 54,104
  • 13
  • 100
  • 195