【问题标题】:How can I fix my code to work for all of the tests?如何修复我的代码以适用于所有测试?
【发布时间】:2021-12-16 07:39:13
【问题描述】:

判断列表中的项目是否都得到相同的除以二的余数。

我的代码在 mod 为 1 时工作,但在 mod 为 0 时不工作。我必须添加什么才能工作? if - else 语句还是其他什么?

sameParity :: [Int] -> Bool
sameParity [] = True
sameParity (x: xs)
  | x `mod` 2 == 1 = sameParity xs
  | x `mod` 2 == 0 = sameParity xs
  | otherwise = False

例子:

  • 以下每个测试用例都必须给出 True:

  • sameParity [] == 真

  • sameParity [1..10] == 假

  • sameParity [1,3..10] == 真

  • sameParity [2, 42, 0, 8] == True

  • sameParity (1: [2, 42, 0, 8]) == 假

【问题讨论】:

  • x `mod` 2` is always `0` or `1`, hence the `otherwise` clause will never "fire". You are however not checking if all items have the same result for x mod 2`,您正在检查每个项目是单独的偶数还是奇数,这是微不足道的。
  • 如何检查所有这些?

标签: haskell mod parity


【解决方案1】:

在每一步,您都必须检查元素的 rest 的奇偶性是否与所有 previous 元素相同。问题是,在每一步中,您不再了解之前的所有元素。他们现在迷路了。

所以你要做的就是将之前所有元素的奇偶校验作为参数传递给下一步:

allHaveParity [] _ = True
allHaveParity (x:xs) prevItemsParity = (x `mod` 2 == prevItemsParity) && (allHaveParity xs prevItemsParity)

> allHaveParity [1,3] 1
True

> allHaveParity [2,4] 0
True

> allHaveParity [1,2] 1
False

但是,当然,这现在非常不方便,因为现在您必须传入“预期”的奇偶校验,而不仅仅是让函数计算出来。

但不要害怕!只需将此函数包装在另一个函数中,这将获取第一项的奇偶校验并将其传递下去:

sameParity [] = True
sameParity (x:xs) = allHaveParity xs (x `mod` 2)

现在可以很容易地观察到,一旦我们有了第一个项目的奇偶校验,我们就可以使用the existing all function 来检查所有其他项目:

sameParity [] = True
sameParity (x:xs) = 
  let firstParity = x `mod` 2
  in all (\a -> (a `mod` 2) == firstParity) xs

并丢弃allHaveParity 函数。它在做同样的事情,但使用了显式递归。

【讨论】:

    猜你喜欢
    • 2021-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-01
    • 2012-06-06
    • 2021-04-15
    • 2013-09-22
    • 2017-04-20
    相关资源
    最近更新 更多