我正在尝试编写一个函数,该函数将采用String
和Char
并输出char在字符串中出现的位置。如何在Haskell中的输入字符串中查找字符的出现
stringCount str ch =
Input : "haskell is hard" `h`
Output:[0,11]
Input : "haskell is hard" `a`
Output:[1,12]
请帮助我我努力理解哈斯克尔。
我正在尝试编写一个函数,该函数将采用String
和Char
并输出char在字符串中出现的位置。如何在Haskell中的输入字符串中查找字符的出现
stringCount str ch =
Input : "haskell is hard" `h`
Output:[0,11]
Input : "haskell is hard" `a`
Output:[1,12]
请帮助我我努力理解哈斯克尔。
有很多方法可以做到这一点,但由于您提到您是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]
可以使用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)
想法是,你去通过字符串char使用递归,然后将实际的caracter(此刻头)与作为参数传递的char进行比较。为了跟踪位置,我使用了一个名为pos的计数器,并为每次递归调用增加它。
非常感谢dreamcrash – Diana
非常感谢迈克尔·科尔和如何与elemIndex办呢? – Diana
对不起,它是'elemIndices',而不是'elemIndex'(后者只给你第一次出现的索引)。 'elemIndices'''haskell很难''给你想要的结果,所以你只需要翻转参数顺序。 –