【问题标题】:Couldn't match expected type `[Integer]' with actual type `Bool'无法将预期类型“[Integer]”与实际类型“Bool”匹配
【发布时间】:2020-02-29 20:57:26
【问题描述】:

我正在尝试对列表进行递归迭代并检查所有值是否都等于 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

我的代码是:

allZero :: [Int] -> Bool
allZero (0:_) = True
allZero (0:s) = 0 : allZero s
allZero (_:s) = False;
allZero _ = False

我不明白为什么我在allZero (0:s) = 0 : allZero s 的行中得到这个错误,我给它正确的参数,一个列表's'

【问题讨论】:

    标签: list haskell recursion functional-programming


    【解决方案1】:

    行:

    allZero (0:s) = <b>0 : allZero s</b>

    没有多大意义,因为0 : allZero s 意味着您正在构建一个列表,一个数字列表。但是你想返回一个Bool

    还有一行:

    allZero <b>(0:_)</b> = True

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

    我们可以通过以下方式检查:

    allZero (Num a, Eq a) => [a] -> Bool
    allZero [] = True
    allZero (0:s) = allZero s
    allZero (_:_) = False

    我们可以利用all :: Foldable f =&gt; (a -&gt; Bool) -&gt; f a -&gt; Bool 写成:

    allZero :: (Num a, Eq a, Foldable f) => f a -> Bool
    allZero = all (0 ==)

    【讨论】:

    • 这应该是公认的答案,我必须学习如何用 html 突出显示像你这样的答案,非常好
    【解决方案2】:

    我将尝试解释错误和解决方案。解决方案应该是:

    allZero :: [Int] -> Bool
    allZero [] = True
    allZero (x:xs) = (x == 0) && (allZero xs)
    

    想想这两种模式。首先,如果没有元素,则全部为0,即有意义,即第一个模式[]。 在第二种模式中,您询问第一种模式是否为0,并且您说值&amp;&amp; 所有其余元素都必须为0(使用递归)

    在你的例子中:

    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
    

    你有很多模式,而且不正确。您可以将我的第一个答案更改为等效项:

    allZero :: [Int] -> Bool
    allZero []     = True
    allZero (0:xs) = (allZero xs)
    allZero _      = False 
    

    【讨论】:

    • 虽然懒惰只能让你到目前为止:&amp;&amp; 在第一个参数中是严格的,但在第二个参数中是懒惰的。 False &amp;&amp; undefined 计算结果为 False,但 undefined &amp;&amp; False 引发异常。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-15
    相关资源
    最近更新 更多