Why can't Haskell infer a tree type?

I followed the book to determine the Tree data type, but the display is not working correctly. Why?

data Tree a = EmptyTree | Node a (Tree a) (Tree a) deriving (Show) test = show EmptyTree 

an error message appears:

 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 
+7
haskell
source share
1 answer

The problem is that EmptyTree is of type Tree a for any type of a . Although this will not affect the final output, the compiler wants to know what a means.

The simplest solution is to select a specific type, for example. with show (EmptyTree :: Tree ()) . This uses the device type () , which in a sense is the simplest type, but you can also use any other type with an instance of Show , such as Int , String , etc.

+15
source share

All Articles