You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复Haskell的sameParity函数以通过所有同奇偶性校验测试

问题原因

你的现有代码没有记录首个元素的奇偶性作为校验基准,递归过程中完全没有比对后续元素的奇偶性和基准是否一致,所以任意非空列表最终都会递归到空列表返回True,自然无法通过测试用例。

修复方案

不需要新增冗余的if-else分支,直接先提取首元素的模2结果作为基准,校验所有后续元素和基准一致即可,这里给出两种常见实现:

实现1:使用all高阶函数(最简洁)

sameParity :: [Int] -> Bool
sameParity [] = True
sameParity (x: xs) = let parity = x `mod` 2 in all (\num -> num `mod` 2 == parity) xs

实现2:递归辅助函数实现

sameParity :: [Int] -> Bool
sameParity [] = True
sameParity (x: xs) = helper (x `mod` 2) xs
  where
    helper _ [] = True
    helper baseParity (n: ns)
      | n `mod` 2 == baseParity = helper baseParity ns
      | otherwise = False

验证测试

以上两种实现都可以完全通过你给出的所有测试用例:

  • sameParity [] == True ✅
  • sameParity [1..10] == False ✅
  • sameParity [1,3..10] == True ✅
  • sameParity [2, 42, 0, 8] == True ✅
  • sameParity (1: [2, 42, 0, 8]) == False ✅

内容的提问来源于stack exchange,提问作者mano19

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 11:45:03