0

我想在 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
4

1 回答 1

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

于 2013-10-14T14:09:49.470 回答