首页 > 解决方案 > 如何修复我的代码以适用于所有测试?

问题描述

确定列表中的项目是否都给出相同的余数除以二。

我的代码在 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

例子:

标签: haskellmodparity

解决方案


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

所以你要做的就是将所有先前元素的奇偶性作为参数传递到下一步:

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)

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

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

并丢弃该allHaveParity功能。它正在做同样的事情,但有明确的递归。


推荐阅读