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

Haskell实现filterA2函数:过滤两列表中a/A字符并返回结果对

问题原因

你的代码存在两个核心错误:

  1. 递归逻辑完全丢弃了所有字符:唯一的递归分支 filterA2 (x:xs) (y:ys) = filterA2 (xs) (ys) 不对当前遍历到的x、y做任何判断和保留,直接全部丢弃,递归到两个列表都为空后自然返回("", "")。
  2. 边界用例冗余且覆盖不全:你写的7条边界用例仅能覆盖两个列表长度都为0或1的极特殊场景,完全无法匹配长度大于1、两个列表长度不一致的普通输入,没有实际作用。

修复方案

因为两个输入字符串的过滤逻辑完全独立,不需要绑定在一起同步遍历,最优写法是直接复用标准库的filter函数实现:

filterA2 :: [Char] -> [Char] -> ([Char], [Char])
filterA2 s1 s2 = (filter notA s1, filter notA s2)
  where notA c = c /= 'a' && c /= 'A'

如果你需要手写递归实现,也可以先实现单个字符串的过滤逻辑,再分别处理两个输入:

filterA2 :: [Char] -> [Char] -> ([Char], [Char])
filterA2 s1 s2 = (filterSingle s1, filterSingle s2)
  where
    filterSingle [] = []
    filterSingle (c:cs)
      | c == 'a' || c == 'A' = filterSingle cs
      | otherwise = c : filterSingle cs

验证示例

运行测试完全符合要求:

  • filterA2 "Always" "runAway" == ("lwys", "runwy") 返回True
  • filterA2 "Cherry" "Tree" == ("Cherry", "Tree") 返回True

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 09:57:03