Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't Haskell infer Tree type?

Tags:

haskell

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
like image 204
Gary Zhao Avatar asked Sep 21 '14 18:09

Gary Zhao


1 Answers

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.

like image 180
GS - Apologise to Monica Avatar answered Oct 22 '22 11:10

GS - Apologise to Monica