为什么Haskell不能推断Tree类型?

时间:2014-09-21 18:04:33

标签: haskell

我按照本书定义了Tree数据类型,但show无法正常工作。为什么呢?

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

test = show EmptyTree

给出错误消息:

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

1 个答案:

答案 0 :(得分:15)

问题是EmptyTree任何类型Tree a的类型为a。即使它实际上不会影响最终输出,编译器也想知道你的意思是哪个a

最简单的解决方法是选择特定类型,例如与show (EmptyTree :: Tree ())。这使用单元类型(),这在某种意义上是最简单的类型,但您也可以使用具有Show实例的任何其他类型,例如{{1 },Int等。