我不知道下面的代码有什么问题。 这段代码的目的是给我一个列表中字符索引的列表。
示例:elemIndices 3 [1,2,3,4,3,2,3,4,5]
表示[2,4,6]
elemIndices' :: Eq a => a -> [a] -> [Int]
elemIndices' x [] = []
elemIndices' x l = reverse (listaind x l)
listaind :: Eq a => a -> [a] ->[Int]
listaind x [] = []
listaind x (y:ys) = if x == y then (length ys) : listaind x ys
答案 0 :(得分:4)
您的if
遗漏了相应的else
。
答案 1 :(得分:0)
我会这样做,一旦你对递归感到满意,试着把它做成折叠
elemIndices :: Eq a => a -> [a] -> [Int]
elemIndices = elemIndices' 0
elemIndices' :: Int -> a -> [a] -> [Int]
elemIndices' _ _ [] = []
elemIndices' idx s (x:xs) =
if s == x
then idx : elemIndices' (idx + 1) s xs
else elemIndices' (idx + 1) s xs