bling5630
bling5630

Reputation: 361

No instance for (Show a0) arising from a use of `print' in Haskell

I am new in Haskell. The topic is from Learn you Haskell book "recursive data structures"

Here is my code

data List a = Empty | Cons a (List a) deriving (Show, Read, Eq, Ord) 

main = do
    print $ Empty
    print $ 5 `Cons` Empty 
    print $ 4 (Cons 5 Empty)  
    print $ 3 `Cons` (4 `Cons` (5 `Cons` Empty))

and here is the error message I get

No instance for (Show a0) arising from a use of `print'
The type variable `a0' is ambiguous
Possible fix: add a type signature that fixes these type variable(s)
Note: there are several potential instances:
  instance Show a => Show (List a)

Upvotes: 3

Views: 1282

Answers (1)

Daniel Wagner
Daniel Wagner

Reputation: 153102

Empty can be any type of List, and although it happens to be the case that show Empty will be "Empty" in all cases where show works at all, the compiler doesn't really know that. (For a real-life example where things could differ by type, compare show ([] :: [Int]) and show ([] :: [Char]) in ghci.) So it demands that you pick a type to use to help it decide how to run show Empty. Pretty easy fix:

main = do
    print $ (Empty :: List Int)
    ...

Don't forget to add a Cons to the 4 (Cons 5 Empty) line, too!

Upvotes: 10

Related Questions