2016-11-05 67 views

回答

1

有很多方法可以做到这一点,但由于您提到您是Haskell初学者,因此列表理解可能最容易理解(我假设这是家庭作业,所以您必须自己实现,而不是使用elemIndices):

stringCount str ch = [ y | (x, y) <- zip str [0..], x == ch ] 
stringCount "haskell is hard" 'a' 
-- [1,12] 
stringCount "haskell is hard" 'h' 
-- [0,11] 

在这里,我们zip,串str从0开始的无限列表中,产生的元组('h', 0), ('a', 1), ('s', 2)等,我们则只能选择其中的字符(绑定到x)等于参数中的元组ch并返回每个人的索引(绑定到y)。

如果你想保持你的当前参数顺序,但使用elementIndices您可以使用以下方法:

stringCount' = flip elemIndices 
stringCount' "haskell is hard" 'h' 
-- [0,11] 
+0

非常感谢迈克尔·科尔和如何与elemIndex办呢? – Diana

+0

对不起,它是'elemIndices',而不是'elemIndex'(后者只给你第一次出现的索引)。 'elemIndices'''haskell很难''给你想要的结果,所以你只需要翻转参数顺序。 –

0

可以使用elemIndex在列表中行走,或者干脆写自己的

indexOf x = map fst . filter (\(_,s) -> s==x) . zip [0..] 

indexOf 'a' "haskell is hard" 
[1,12] 

findIndices

import Data.List(findIndices) 
findIndices (\x -> x=='a') "haskell is hard" 
[1,12] 
0

下面是一个简单,但不太复杂的解决方案,在一个岗位由karakfa :

stringCount :: String -> Char -> Integer -> [Integer] 
stringCount [] c _ = [] 
stringCount (x:xs) c pos | x == c = pos:(stringCount xs c (pos+1)) 
         | otherwise = stringCount xs c (pos+1) 

想法是,你去通过字符串char使用递归,然后将实际的caracter(此刻头)与作为参数传递的char进行比较。为了跟踪位置,我使用了一个名为pos的计数器,并为每次递归调用增加它。

+0

非常感谢dreamcrash – Diana

相关问题