[Haskell-beginners] Longest common prefix of a list of lists

Aai bradypus at xs4all.nl
Fri Apr 29 20:17:27 CEST 2011


I don't know for sure if the following is elegant or not, but:

a = "aaabbbbbbcccccc"
b = "aaabbbccccccd"
c = "aaabbbbbbbbbccccffffdd"

takeCommonPrefix xs =  flip take xs. length . filter (`isPrefixOf`xs). drop 1. inits

*Main> foldl1 takeCommomPrefix  [a,b,c]
"aaabbb"

*Main> foldl1 takeCommonPrefix  [a,b,c,""]
""

May be the use of 'length' is a bit ugly. :-)



Hallo Daniel Fischer, je schreef op 29-04-11 16:32:
>
> -- to get the common prefix of two lists, we use explicit recursion, I
> don't see an elegant way to avoid that.
>

-- 
Met vriendelijke groet,
=@@i




More information about the Beginners mailing list