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

Haskell 如何从字符串列表的各元素中移除内部特殊字符

问题原因

你当前的函数仅对字符串列表的外层元素做匹配判断,只会删除整个字符串等于"!"的元素,不会处理每个字符串内部的字符。
Haskell中String本质就是[Char]类型(字符列表),你确实需要对每个字符串内部的字符做过滤处理。

实现方案

可以拆分两步实现:

  1. 先写单个字符串的特殊字符过滤逻辑
  2. 将该逻辑映射到列表的所有字符串元素上

最简实现(用标准库函数)

直接组合map和filter即可,不需要单独写递归:

removeUglyCharacters :: [String] -> [String]
removeUglyCharacters = map (filter (/= '!'))

手动递归实现(如果需要自己写模式匹配逻辑)

如果你不想用标准库的高阶函数,可以拆分辅助函数:

-- 处理单个字符串,移除内部所有!
removeExclamation :: String -> String
removeExclamation [] = []
removeExclamation (c:cs)
  | c == '!' = removeExclamation cs
  | otherwise = c : removeExclamation cs

-- 处理整个字符串列表
removeUglyCharacters :: [String] -> [String]
removeUglyCharacters [] = []
removeUglyCharacters (x:xs) = removeExclamation x : removeUglyCharacters xs

运行测试

输入你给出的测试用例:

*Main> removeUglyCharacters ["This!","i2s","a","li!st","of","strings"]
["This","i2s","a","list","of","strings"]

如果你需要同时移除字符串中的数字,修改过滤条件即可,记得导入Data.Char使用isDigit判断:

import Data.Char (isDigit)

removeUglyCharacters = map (filter (\c -> c /= '!' && not (isDigit c)))

运行后即可得到你期望的["This","is","a","list","of","strings"]结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 08:06:04