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

Gar*_*hao 7 haskell

我按照本书来定义树数据类型,但show无法正常工作.为什么?

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

test = show EmptyTree
Run Code Online (Sandbox Code Playgroud)

给出错误消息:

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
Run Code Online (Sandbox Code Playgroud)

GS *_*ica 15

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

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