haskell - 如何修复我的代码以适用于所有测试?
问题描述
确定列表中的项目是否都给出相同的余数除以二。
我的代码在 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:
相同奇偶校验 [] == 真
相同奇偶校验 [1..10] == 假
sameParity [1,3..10] == 真
sameParity [2, 42, 0, 8] == True
sameParity (1: [2, 42, 0, 8]) == 假
解决方案
在每一步,您都必须检查其余元素的奇偶性是否与之前的所有元素相同。问题是,在每一步你都不再知道之前的所有元素。他们现在迷路了。
所以你要做的就是将所有先前元素的奇偶性作为参数传递到下一步:
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
功能。它正在做同样的事情,但有明确的递归。
推荐阅读
- reactjs - 使用 cloneElement 向孩子添加 onClick 道具
- django - 使用 Django 设置 shibboleth SP
- reactjs - Material-UI CloseIcon not showing in Autocomplete
- kubernetes - K8s 可以在不同区域共享 Persistent volume/Storage 吗?
- php - PHP 错误:在第 1 行的 Psy Shell 代码中找不到类“App\News”
- cuda - 寻找将 cudaSurfaceObject_t 转换为 cudaTextureObject_t 的有效方法
- c# - 统一平滑填充动画变化(增加、减少)
- javascript - 对对象数组进行排序并更新状态
- pyqt - PyQt Update Child Widget Property
- c++ - std::make_shared 接口?