2014-09-21 51 views
7

我跟着书来定义Tree数据类型,但是show不能正常工作。为什么?Haskell为什么不能推断Tree类型?

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 
+0

你是如何运行的代码?你在使用解释器(ghci)吗?这一行:'test = show EmptyTree'不是有效的Haskell语法,所以你可能不会粘贴你的所有代码。 – rburny 2014-09-21 18:19:38

+2

@rburny我认为OP在源文件中有。 – Sibi 2014-09-21 18:20:09

+0

我正在使用Eclipse – 2014-09-22 01:20:06

回答

15

的问题是,EmptyTree具有类型为Tree a任何类型a。尽管它实际上不会影响最终输出,但编译器想要知道您的意思是哪一个a

最简单的解决方法是选择特定类型,例如与show (EmptyTree :: Tree())。本品采用单元(),这在某种意义上是一个最简单的类型,但你也可以使用具有Show实例的任何其他类型的,像IntString

+0

+1,'()'是要走的路。 :) – Sibi 2014-09-21 18:19:22

+0

谢谢@Ganesh Sittampalam。有用。 – 2014-09-22 01:18:57

相关问题