Longest common prefix: Difference between revisions

Content added Content deleted
m (People can disagree on what "well designed" means in technical contexts, so spell out what was meant)
m (→‎{{header|Haskell}}: (swapped one <$> to an fmap, relieving the need for brackets))
Line 774: Line 774:
:: (Eq a)
:: (Eq a)
=> [[a]] -> [a]
=> [[a]] -> [a]
lcp = (head <$>) . takeWhile allEqual . truncTranspose
lcp = fmap head . takeWhile allEqual . truncTranspose
where
where
-- Similar to transpose, but stops on end of shortest list.
truncTranspose :: [[a]] -> [[a]]
truncTranspose :: [[a]] -> [[a]]
truncTranspose xs
truncTranspose xs
Line 786: Line 785:
allEqual (x:xs) = all (== x) xs
allEqual (x:xs) = all (== x) xs


-- Similar to transpose, but stops on end of shortest list.
showPrefix :: [String] -> String
showPrefix :: [String] -> String
showPrefix xs = show xs ++ " -> " ++ show (lcp xs)
showPrefix xs = show xs ++ " -> " ++ show (lcp xs)
Line 804: Line 804:
])
])
putStrLn []
putStrLn []
print $ lcp ["abc" ++ repeat 'd', "abcde" ++ repeat 'f'] -- prints "abcd"</lang>
print $ lcp ["abc" ++ repeat 'd', "abcde" ++ repeat 'f'] -- prints</lang>

{{Out}}
{{Out}}
<pre>["interspecies","interstellar","interstate"] -> "inters"
<pre>["interspecies","interstellar","interstate"] -> "inters"