如何在Haskell中查找输入字符串中出现的字符

如何在Haskell中查找输入字符串中出现的字符,haskell,functional-programming,Haskell,Functional Programming,我正在尝试编写一个函数,该函数将接受字符串和字符,并输出字符串中字符所在的索引 stringCount str ch = Input : "haskell is hard" `h` Output:[0,11] Input : "haskell is hard" `a` Output:[1,12] 请帮助我,我正在努力理解Haskell。您可以使用elemIndex浏览列表,或者简单地编写自己的列表 indexOf x = map fst . filter (\(_,s) -> s==x

我正在尝试编写一个函数,该函数将接受
字符串和
字符,并输出字符串中字符所在的索引

stringCount str ch = 
Input : "haskell is hard" `h`
Output:[0,11]
Input : "haskell is hard" `a`
Output:[1,12]

请帮助我,我正在努力理解Haskell。

您可以使用
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]

以下是一个更简单但不太复杂的解决方案,由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)

其思想是使用递归逐个字符地遍历字符串,然后将实际字符(此时的头)与作为参数传递的字符进行比较。为了跟踪位置,我使用了一个名为pos的计数器,并在每次递归调用中递增它。

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


非常感谢Michael Kohl,我如何使用elemIndex?对不起,它是
elemIndices
,而不是
elemIndex
(后者只提供第一次出现的索引)
elemIndices'a'“haskell很难”
提供了所需的结果,因此您只需翻转参数顺序即可。非常感谢
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]
stringCount' = flip elemIndices 
stringCount' "haskell is hard" 'h'
-- [0,11]