I followed the book to define Tree data type, but show doesn't work correctly. Why?
data Tree a = EmptyTree | Node a (Tree a) (Tree a) deriving (Show)
test = show EmptyTree
gives the error message:
No instance for (Show a0) arising from a use of ???show???
The type variable ???a0??? is ambiguous
Note: there are several potential instances:
instance Show a => Show (Tree a)
-- Defined at /Users/gzhao/Documents/workspace/hsTest2/src/Tree.hs:3:62
instance Show Double -- Defined in ???GHC.Float???
instance Show Float -- Defined in ???GHC.Float???
...plus 25 others
In the expression: show EmptyTree
In an equation for ???test???: test = show EmptyTree
The problem is that EmptyTree
has type Tree a
for any type a
. Even though it won't actually affect the final output, the compiler wants to know which a
you mean.
The simplest fix is to pick a specific type, e.g. with show (EmptyTree :: Tree ())
. This uses the unit type ()
, which is in some sense the simplest possible type, but you can also use any other type that has a Show
instance, like Int
, String
etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With