[英]Couldn't match expected type `[Integer]' with actual type `Bool'
I'm trying to iterate recursive over the list and checking if all the values are equal 0, the error im getting is:我正在尝试遍历列表并检查所有值是否都等于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
and my code is:我的代码是:
allZero :: [Int] -> Bool
allZero (0:_) = True
allZero (0:s) = 0 : allZero s
allZero (_:s) = False;
allZero _ = False
I don't understand why im getting this error, in the line of allZero (0:s) = 0: allZero s
im giving it the correct parameter, a list 's'我不明白为什么我在
allZero (0:s) = 0: allZero s
的行中得到这个错误,我给它正确的参数,一个 list 's'
The line:该行:
allZero (0:s) =
0 : allZero s
does not make much sense, since 0: allZero s
means you are constructing a list, a list of numbers.没有多大意义,因为
0: allZero s
意味着您正在构建一个列表,一个数字列表。 But you want to return a Bool
.但是你想返回一个
Bool
。
Furthermore the line:此外,该行:
allZero
(0:_) = True
Is incorrect as well, since that means that means that every list that starts with 0
satisfies the functions.也是不正确的,因为这意味着每个以
0
开头的列表都满足功能。 But in a list [0,1,4,2,5]
, not all numbers are 0
.但是在列表
[0,1,4,2,5]
中,并非所有数字都是0
。
We can check this with:我们可以通过以下方式检查:
allZero (Num a, Eq a) => [a] -> Bool
allZero [] = True
allZero (0:s) =
allZero s
allZero (_:_) = False
We can make use of all:: Foldable f => (a -> Bool) -> fa -> Bool
and write this as:我们可以使用
all:: Foldable f => (a -> Bool) -> fa -> Bool
并将其写成:
allZero :: (Num a, Eq a, Foldable f) => f a -> Bool
allZero =
all (0 ==)
I will try to explain the error and the solution.我将尝试解释错误和解决方案。 The solution should be:
解决方案应该是:
allZero :: [Int] -> Bool
allZero [] = True
allZero (x:xs) = (x == 0) && (allZero xs)
Think of the two patterns.想想这两种模式。 First, if there is no elements, all are 0, that has sense, that is the first pattern
[]
.首先,如果没有元素,则全部为0,即有意义,即第一个模式
[]
。 In the second pattern you ask if the first is 0
and you say that value &&
all the rest of the elements must be 0
(using recursion)在第二个模式中,您询问第一个是否为
0
,并且您说值&&
所有元素的 rest 必须为0
(使用递归)
In your example:在您的示例中:
allZero :: [Int] -> Bool
allZero (0:_) = True --Wrong, here you are saying if it start with 0, True, no matter what is next, and that's not correct
allZero (0:s) = 0 : allZero s -- this could be right along side with other patterns
allZero (_:s) = False -- this is wrong by sure, you are saying if a list has at list one element, False
allZero _ = False -- And this one has no sense among the others
You have a lot of patterns, and incorrect.你有很多模式,而且不正确。 You can change my first answer as the equivalent:
您可以将我的第一个答案更改为等效项:
allZero :: [Int] -> Bool
allZero [] = True
allZero (0:xs) = (allZero xs)
allZero _ = False
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.