【发布时间】: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 forxmod2`,您正在检查每个项目是单独的偶数还是奇数,这是微不足道的。 -
如何检查所有这些?