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 = |
lcp = fmap head . takeWhile allEqual . truncTranspose |
||
where |
where |
||
⚫ | |||
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 |
||
⚫ | |||
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 |
print $ lcp ["abc" ++ repeat 'd', "abcde" ++ repeat 'f'] -- prints</lang> |
||
{{Out}} |
{{Out}} |
||
<pre>["interspecies","interstellar","interstate"] -> "inters" |
<pre>["interspecies","interstellar","interstate"] -> "inters" |