我遇到了问题,我有一个像这样的列表[["A1","A2","A3"],["B1","B2","B3"],["A1","B3""C3"]]
如果每个字符串包含2,我想返回一个列表,
期望的回报应如下:
[["A1","A2","A3"],["B1","B2","B3"]]
我最近的方法是
isIn :: Int -> [String] -> Bool
isIn a [] = False
isIn a (x:xs)
| show a == x = True
| otherwise = isIn a xs
我用它上面的列表测试了它给了我假,我错了什么? 我该如何解决这个问题?
答案 0 :(得分:0)
通过类型定义isIn :: Int -> [String] -> Bool
我假设函数正在迭代字符串列表(例如["A1","A2","A3"]
)。
因此,问题出在show a == x
。 x
等于"A1"
,"A2"
,"A3"
; show 2
是"2"
;但是"2"
不等于这些字符串中的任何一个。
您需要使用验证字符串contains
" 2"而非equal
到" 2"的函数。 (有elem功能)
或实施它:
isInString :: Int -> [Char] -> Bool
isInString a [] = False
isInString a (x:xs)
| intToDigit a == x = True
| otherwise = isInString a xs
然后在isIn
中使用它:
isIn :: Int -> [String] -> Bool
isIn a [] = False
isIn a (x:xs)
| isInString a x = True
| otherwise = isIn a xs