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

时间:2016-11-05 04:15:52

标签: haskell functional-programming

我正在尝试编写一个函数,该函数将使用StringChar并输出字符串中出现char的索引。

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

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

3 个答案:

答案 0 :(得分:1)

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

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,无限列表从0开始,产生元组str等。然后我们只选择字符所在的元组(绑定到{ {1}})等于参数('h', 0), ('a', 1), ('s', 2)并返回每个参数的索引(绑定到x)。

如果您想保留当前的参数顺序,但使用ch,则可以使用以下内容:

y

答案 1 :(得分: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]

答案 2 :(得分:0)

这是一个更简单但不太复杂的解决方案,卡拉克法的一篇文章:

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使用递归遍历字符串char,然后将实际的caracter(此时的头部)与作为参数传递的char进行比较。为了跟踪我正在使用名为pos的计数器的位置,并为每次递归调用递增它。