philipp siegmantel
2011-04-29 14:07:00 UTC
Hi,
For one of my toy project I had to find the longest common prefix of a list
of strings.
I figured, that this function should only work on list-structure, meaning it
should have type
as far as I tested it, but I have the feeling that there's a better way to
do it.
For one of my toy project I had to find the longest common prefix of a list
of strings.
I figured, that this function should only work on list-structure, meaning it
should have type
longestCommonPrefix :: [[a]] -> [a]
Sadly the best I could come up with was using explicit recursion. It worksas far as I tested it, but I have the feeling that there's a better way to
do it.
longestCommonPrefix :: Eq a => [[a]] -> [a]
longestCommonPrefix [] = []
longestCommonPrefix xss | any null xss = []
| otherwise = loop xss []
where loop ::Eq b => [[b]] -> [b] -> [b]
loop xss acc =
let xs = concatMap (take 1) xss
in if any (\x -> x /= head xs) (tail xs)
then reverse acc
else loop (map tail xss) (head xs : acc)
longestCommonPrefix [] = []
longestCommonPrefix xss | any null xss = []
| otherwise = loop xss []
where loop ::Eq b => [[b]] -> [b] -> [b]
loop xss acc =
let xs = concatMap (take 1) xss
in if any (\x -> x /= head xs) (tail xs)
then reverse acc
else loop (map tail xss) (head xs : acc)