无法将预期类型“ [Integer]”与实际类型“ Bool”匹配

Kev*_*vin 3 recursion haskell functional-programming list

我试图遍历列表的递归并检查是否所有值都等于0,即时消息错误是:

 * Couldn't match expected type `[Integer]' with actual type `Bool'
    * In the second argument of `(:)', namely `allZero s'
      In the expression: 0 : allZero s
      In an equation for `allZero': allZero (0 : s) = 0 : allZero s
Run Code Online (Sandbox Code Playgroud)

我的代码是:

allZero :: [Int] -> Bool
allZero (0:_) = True
allZero (0:s) = 0 : allZero s
allZero (_:s) = False;
allZero _ = False
Run Code Online (Sandbox Code Playgroud)

我不明白为什么我会收到此错误,因为allZero (0:s) = 0 : allZero s我给了它正确的参数,即列表“ s”

Wil*_*sem 10

该行:

allZero (0:s) = 0 : allZero s
Run Code Online (Sandbox Code Playgroud)

没什么意义,因为这0 : allZero s意味着您要构造一个列表,一个数字列表。但是您想返回一个Bool

此外,该行:

allZero (0:_) = True
Run Code Online (Sandbox Code Playgroud)

也是不正确的,因为这意味着每个以开头的列表都0满足功能。但在清单中[0,1,4,2,5],并非所有数字都是0

我们可以用以下方法检查:

allZero (Num a, Eq a) => [a] -> Bool
allZero [] = True
allZero (0:s) = allZero s
allZero (_:_) = False
Run Code Online (Sandbox Code Playgroud)

我们可以利用它all :: Foldable f => (a -> Bool) -> f a -> Bool并将其写为:

allZero :: (Num a, Eq a, Foldable f) => f a -> Bool
allZero = all (0 ==)
Run Code Online (Sandbox Code Playgroud)