Search code examples
haskellshow

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


No instance for (Show a) arising from a use of ‘show’ In the first argument of ‘(++)’, namely ‘show a’

data LTree a = Leaf a | Node (LTree a) (LTree a)
instance Show (LTree a) where
    show (Leaf a) = "{" ++ show a ++ "}"
    show (Node fe fd) = "<" ++ (show fe)++ "," ++(show fd)++ ">"
Node (Leaf 1) (Node (Node (Leaf 3) (Leaf 4)) (Node (Leaf 8) (Leaf 7)))

I should get:

<{1},<<{3},{4}>,<{8},{7}>>>

Solution

  • In your line:

        show (Leaf a) = "{" ++ show a ++ "}"

    You call show a, with a an element of type a, but it is not said that that type a is an instance of Show, you thus need to add a constraint to your instance declaration:

    instance Show a => Show (LTree a) where
        show (Leaf a) = "{" ++ show a ++ "}"
        show (Node fe fd) = "<" ++ (show fe)++ "," ++(show fd)++ ">"

    So here we say that LTree a is an instance of show given a is an instance of Show. For your given sample data, we then obtain:

    Prelude> Node (Leaf 1) (Node (Node (Leaf 3) (Leaf 4)) (Node (Leaf 8) (Leaf 7)))
    <{1},<<{3},{4}>,<{8},{7}>>>