Reputation:
I've written 2 functions in haskell, and now i have to write a third one, for calculating the number of prefixes in haskell. here's an example:
i have to lists. the first is the prefixes list, and the other one is the text list. what this function is suppose to do, is to calculate the number of times each word from the prefix list is a prefix of all the words in the text list, and present it in a tuple (word, number of times it appears as a prefix in the text words:
prefix list ["go", "co"]
text list ["golf", "company", "count"]
this should return [("go", 1) , ("co", 2)]
what i have so far is this:
isPrefixOf :: (Eq a) => [a] -> [a] -> Bool
isPrefixOf [] _ = True
isPrefixOf _ [] = False
isPrefixOf (x:xs) (y:ys) = x == y && isPrefixOf xs ys
prefixCount :: (Eq a1, Num a) => [a1] -> [[a1]] -> a
prefixCount _ [] = 0
prefixCount x (y:ys) | isPrefixOf x y = 1 + prefixCount x ys
| otherwise = prefixCount x ys
howManyPrefixes _ [] = 0
howManyPrefixes [] _ = 0
howManyPrefixes (x:xs) (y:ys) = (x, prefixCount x (y:ys))
Any help?
Upvotes: 0
Views: 501
Reputation: 53891
Using zip
this is quite easy
howManyPrefixes ps ws = zip ps $ map (`prefixCount` ws) ps
Now since this looks like homework I'll let you write the recursive solution yourself, some helpful hints.
howManyPrefixes xs (y:ys)
y:ys
. It doesn't matter if it's empty.Upvotes: 1