user2878641
user2878641

Reputation:

Counting prefixes in Haskell

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

Answers (1)

daniel gratzer
daniel gratzer

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.

  1. You're almost there with your current solution
  2. Don't check if the second list (the one your counting prefixs in) is empty. This is the second clause of your current solution.
  3. In your last clause, add the recursive step by consing that tuple onto the resulting list from howManyPrefixes xs (y:ys)
  4. Don't pattern match on the second list, eg y:ys. It doesn't matter if it's empty.

Upvotes: 1

Related Questions