2016-04-28 71 views
0

考虑以下多行字符串S如何在Haskell中创建这些字符串匹配函数?

apple 
banana berry 
cantelope 

我想写/定位Haskell函数,我将在这篇文章or-matchand-match调用。下面是他们应该做的一些例子:

or-match S ("apple","berry") 

{- should return the two line string: 
apple 
banana berry 
-} 

and-match S ("apple", "berry") --should return the empty string, or something like "No matches." 

and-match S ("banana" "berry") --should return a single line containing "banana berry" 

在上面的例子中,我使用的类型(String, String)or-matchand-match域参数。我不确定这是最好的方式,但我可能想使用两个以上的参数。虽然我是Haskell的新手,但我不确定如何使任意长度的元组成为函数的参数。

总之,这篇文章的整体问题:我如何or-match和哈斯克尔and-match,使得对于每这些功能域参数是任意长度的元组(或某些类型的,允许任意一个搜索长度)?

回答

4

你可以写

andMatchPred, orMatchPred :: Eq a => [a] -> [a] -> Bool 
andMatchPred needles haystack = all (`elem` haystack) needles 
orMatchPred needles haystack = any (`elem` haystack) needles 

然后你想要的功能可能会被写成

andMatch, orMatch :: Eq a => [a] -> [[a]] -> [[a]] 
andMatch = filter . andMatchPred 
orMatch = filter . orMatchPred 

应该是充足的机会来提高以后,如果说原来是一个瓶颈的效率,但简单易读的实现应该是第一位的。

在ghci中快速使用显示它是如何使用:

> let s = [["apple"],["banana","berry"],["cantelope"]] 
> andMatch ["apple", "berry"] s 
[] 
> orMatch ["apple", "berry"] s 
[["apple"],["banana","berry"]] 
2

,使得对于每个这些功能的域参数是任意长度的元组(或某些类型的,允许任意搜索长度)?

您正在寻找一个清单,特别是在这种情况下[String]。元组是固定长度的,但是在每个位置允许不同的类型,列表是均匀的,意味着每个值必须具有相同的类型,但是具有任意长度。

你要找那么所寻求的是有

orMatch, andMatch :: [String] -> [String] -> [String] 

你需要一个功能hasSubString :: String -> String -> Bool,你必须自己写类型的功能,但你的代码可能看起来像下面的伪代码:

orMatch lines searchTerms = filter (\line -> any (hasSubString line) searchTerms) lines 
andMatch lines searchTerms = filter (\line -> all (hasSubString line) searchTerms) lines 

hasSubString string substring 

回报True如果substring出现在stringFalse中。例如hasSubString "hello, world" "world" == True,hasSubString "hello, world" "unicorns" == False

+0

没有必要自己实现'hasSubString';标准库将其作为'isInfixOf',并且Hackage上存在更高效的版本。 –

相关问题