推断类型不够通用

use*_*807 2 haskell prefix

我想知道列表是否是第二个列表的前缀,使用以下代码:

prefix :: [a] -> [b] -> Bool
prefix [] _ = True
prefix _ [] = False
prefix (x:xs) (y:ys) = if (x==y) then prefix xs ys else False
Run Code Online (Sandbox Code Playgroud)

但它返回一个错误:

Inferred type is not general enough
*** Expression    : prefix
*** Expected type : [a] -> [b] -> Bool
*** Inferred type : [a] -> [a] -> Bool
Run Code Online (Sandbox Code Playgroud)

有人可以帮助我让这个工作吗?

aug*_*tss 10

您的类型签名声称两个列表可以有不同的类型,但它们不能.所以编译器抱怨它推断出的类型不如你要求的类型.


Yan*_*ier 7

那是因为你正在比较你命名ab使用的类型(x==y).检查类型==,这意味着它们是相同类型,具有相等性测试:

Prelude> :t (==)
(==) :: Eq a => a -> a -> Bool
Run Code Online (Sandbox Code Playgroud)

因此,推断的类型签名实际上是Eq a => [a] -> [a] -> Bool.