Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

haskell

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}>>>
like image 456
rgralma Avatar asked Dec 14 '22 12:12

rgralma


1 Answers

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}>>>
like image 96
Willem Van Onsem Avatar answered Jan 05 '23 00:01

Willem Van Onsem