Reputation: 677
How would you go about defining a function that takes two strings, say string x and string y and return the number of elements at the end of the first string (string x) which overlap with the beginning of the second string (second y).
I'm thinking that it would be a good idea to use isPrefixOf from the prelude to do this since it checks if a string is in another string and returns True if it does or False otherwise. But I'm a little confused at how to return the count of how many elements overlap. I wrote some pseudocode based off how I think you would approach the problem.
countElements :: Eq a => (Str a, Str a) -> Int
countElements (x,y) =
if x `isPrefixOf` y == True
then return the count of how many elements overlap
otherwise 0
A sample output would be:
countElements (board, directors) = 1
countElements (bend, ending) = 3
Any help here? I'm not very good at writing Haskell code.
Upvotes: 1
Views: 429
Reputation: 54584
Version without isPrefixOf
:
import Data.List
countElements xs ys = length . fst . last . filter (uncurry (==)) $ zip (reverse $ tails xs) (inits ys)
Upvotes: 3
Reputation: 633
You have exactly the right idea, but your pseudocode misses the fact that you'll have to iterate on all of the possible tails of the first string passed to the function.
countElements :: String -> String -> Int
countElements s t = length $ head $ filter (`isPrefixOf` t) (tails s)
> countElements "board" "directors"
1
> countElements "bend" "endings"
3
Upvotes: 4