在Haskell中使用`print'不会产生(Show a0)实例

bli*_*630 3 haskell types

我是Haskell的新手.主题来自Learn your Haskell书籍"递归数据结构"

这是我的代码

data List a = Empty | Cons a (List a) deriving (Show, Read, Eq, Ord) 

main = do
    print $ Empty
    print $ 5 `Cons` Empty 
    print $ 4 (Cons 5 Empty)  
    print $ 3 `Cons` (4 `Cons` (5 `Cons` Empty))
Run Code Online (Sandbox Code Playgroud)

这是我收到的错误消息

No instance for (Show a0) arising from a use of `print'
The type variable `a0' is ambiguous
Possible fix: add a type signature that fixes these type variable(s)
Note: there are several potential instances:
  instance Show a => Show (List a)
Run Code Online (Sandbox Code Playgroud)

Dan*_*ner 10

Empty可以是任何类型的List,虽然恰好show Empty"Empty"在所有情况下都可以使用的情况show,编译器并不真正知道这一点.(对于一个真实的例子,其中的事物可能因类型而不同,比较show ([] :: [Int])show ([] :: [Char])在ghci中.)因此,它要求您选择一种类型来帮助它决定如何运行show Empty.很容易解决:

main = do
    print $ (Empty :: List Int)
    ...
Run Code Online (Sandbox Code Playgroud)

不要忘了一个添加Cons4 (Cons 5 Empty)线,太!