我想在haskell中创建一个函数,它返回单个单词是单词列表前缀的次数。例如:对于单词“go”和单词列表[“ace”,“going”,“gone”,“golf”],它应该返回3.到目前为止,我所拥有的是:
numberOfPrefixes _ [] = error ("Empty list of strings")
numberOfPrefixes [] _ = error ("No word")
numberOfPrefixes (x:xs) (y:ys)
| isPrefixOf (x:xs) y = 1 + numberOfPrefixes(x:xs) ys
| otherwise = 0
但这只有在单词列表的第一个元素实际上是前缀时才有效。如果第一个元素不是前缀,则整个事物就会崩溃。有没有帮助做到这一点?
isPrefixOf :: (Eq a) => [a] -> [a] -> Bool
isPrefixOf [] _ = True
isPrefixOf _ [] = False
isPrefixOf (x:xs) (y:ys) = x == y && isPrefixOf xs ys
答案 0 :(得分:3)
以下是我写这个
的方法 (.:) :: (b -> c) -> (a -> a1 -> b) -> a -> a1 -> c
(.:) = (.) . (.) -- A common utility definition
infixr 9 .:
prefixCount :: Eq a => [a] -> [[a]] -> Integer
prefixCount = length .: filter . isPrefixOf
或者写得很有意思
prefixCount l ls = length $ filter (isPrefixOf l) ls
如果你真的想递归地写它
prefixCount l [] = 0
prefixCount x (l:ls) | <is prefix?> = 1 + prefixCount x ls
| otherwise = prefixCount x ls
然后只需填写<is prefix?>
,然后检查x
前缀是l