Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
String 函数,用于检查子字符串是否位于Haskell中的另一个字符串中_String_Haskell - Fatal编程技术网

String 函数,用于检查子字符串是否位于Haskell中的另一个字符串中

String 函数,用于检查子字符串是否位于Haskell中的另一个字符串中,string,haskell,String,Haskell,我需要编写一个函数,通过使用列表理解检查子字符串是否在另一个字符串中 我正在使用drop从字符串创建字符串列表,以使用isPrefixOf将创建的字符串列表与子字符串进行比较 这是我的密码: contains::String->String->Bool 包含str substr=isPrefixOf substr(检查str) 哪里 检查::字符串->[字符串] 检查str |str=[]=[] |否则=[drop x str | x[String] 检查str |str=[]=[] |否则=[

我需要编写一个函数,通过使用列表理解检查子字符串是否在另一个字符串中

我正在使用
drop
从字符串创建字符串列表,以使用
isPrefixOf
将创建的字符串列表与子字符串进行比较

这是我的密码:

contains::String->String->Bool
包含str substr=isPrefixOf substr(检查str)
哪里
检查::字符串->[字符串]
检查str
|str=[]=[]
|否则=[drop x str | x[String]
检查str
|str=[]=[]
|否则=[drop x str | x需要两个相同类型的列表(该类型应该是
Eq
typeclass的成员),因此两个
String
s就是一个例子,因为
String
Char
s的列表

但是,您提供了一个
字符串
(substr
)和一个
字符串
列表(check str具有as type
[String]
)。这样就不会进行类型检查。此外,多次使用
drop
将使
检查str
在O(n2)中运行,这是无效的

您可以使用来检查谓词是否满足可折叠列表中的任何元素,例如列表。我们还可以使用来以更高效的方式获取列表(包括完整列表)的所有尾部:

import Data.List(isPrefixOf, tails)

contains :: String -> String -> Bool
contains str substr = any (isPrefixOf substr) (tails str)
我们还可以通过使用和使功能点自由:

导入数据列表(isPrefixOf,tails)
包含::Eq a=>[a]->[a]->Bool

contains=flip(any.isPrefixOf).tails
问题是
isPrefixOf
需要一个
字符串
,但您的
检查
返回字符串列表(
[String]

修复方法是将
isPrefixOf
包装在
any
中,将函数映射到整个列表:

contains :: String -> String -> Bool
contains str substr = any (isPrefixOf substr) (check str)
    where
    check :: String -> [String]
    -- ...
请注意,
check
相当于内置的
tails
(从技术上讲,它应该是
length str
,而不是
length str-1
,但在这种情况下这并不重要),因此,如果我们进行替换,我们会得出:


isPrefixOf需要两个字符串,而不是一个字符串和一组字符串。虽然我真的很感谢你的回答和解释,但我还是Haskell的初学者,恐怕我对它们有点迷茫。不过我知道我给了
isPrefixOf
一个错误的
check str
类型,所以我想知道我如何处理gi在保留大部分代码的同时保留正确的类型(至少一个列表理解)@straw6erry他说
tails str
与您的
check str
做的事情相同,但效率更高。另外
isPrefixOf substr…list…
不起作用,但
any(isPrefixOf substr)…列表…
将起作用。@MathematicalArchid啊,我明白了,谢谢你进一步解释。谢谢大家的帮助!
import Data.List(isPrefixOf, tails)

contains :: Eq a => [a] -> [a] -> Bool
contains str substr = any (isPrefixOf substr) (tails str)
import Data.List(isPrefixOf, tails)

contains :: Eq a => [a] -> [a] -> Bool
contains = flip (any . isPrefixOf) . tails
contains :: String -> String -> Bool
contains str substr = any (isPrefixOf substr) (check str)
    where
    check :: String -> [String]
    -- ...
contains :: String -> String -> Bool
contains str substr = any (isPrefixOf substr) (tails str)