有没有更好的方法来编写“string contains X”方法?
刚开始使用 Haskell 并意识到(据我所知)没有直接的方法来检查字符串以查看它是否包含较小的字符串。所以我想我应该尝试一下。
本质上,这个想法是检查两个字符串的大小是否相同并且相等。如果被检查的字符串较长,则递归地删除头部并再次运行检查,直到被检查的字符串长度相同。
其余的可能性我使用模式匹配来处理。这就是我想出的:
stringExists "" wordToCheckAgainst = False
stringExists wordToCheckFor "" = False
stringExists wordToCheckFor wordToCheckAgainst | length wordToCheckAgainst < length wordToCheckFor = False
| length wordToCheckAgainst == length wordToCheckFor = wordToCheckAgainst == wordToCheckFor
| take (length wordToCheckFor) wordToCheckAgainst == wordToCheckFor = True
| otherwise = stringExists wordToCheckFor (tail wordToCheckAgainst)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您在 Hoogle 中搜索您要查找的函数的签名(
String -> ; String -> Bool
) 你应该看到isInfixOf
位居前列结果之一。If you search Hoogle for the signature of the function you're looking for (
String -> String -> Bool
) you should seeisInfixOf
among the top results.isInfixOf
<来自Data.List
的 /a> 肯定会解决问题,但是如果遇到更长的干草堆或反常的针,您应该考虑更高级的字符串匹配算法具有更好的平均和最坏情况复杂度。1 考虑一个非常长的字符串,仅由
a
和一根开头有很多a
的针组成,最后有一个b
结束。isInfixOf
fromData.List
will surely solve the problem, however in case of longer haystacks or perverse¹ needles you should consider more advanced string matching algorithms with a much better average and worst case complexity.¹ Consider a really long string consisting only of
a
's and a needle with a lot ofa
's at the beginning and oneb
at the end.考虑使用
text
包(text
在 Hackage 上,现在也是 Haskell Platform 的一部分),满足您的文本处理需求。它提供了 Unicode 文本类型,比内置的基于列表的String
更节省时间和空间。对于字符串搜索,text
包 实现一个 基于 Boyer-Moore 的算法,它比Data.List.isInfixOf
使用的朴素方法具有更好的复杂性。使用示例:
Consider using the
text
package(text
on Hackage, now also part of Haskell Platform) for your text-processing needs. It provides a Unicode text type, which is more time- and space-efficient than the built-in list-basedString
. For string search, thetext
package implements a Boyer-Moore-based algorithm, which has better complexity than the naïve method used byData.List.isInfixOf
.Usage example: