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

James Cook mokus at deepbondi.net
Fri Apr 29 21:42:17 CEST 2011


On Apr 29, 2011, at 10:32 AM, Daniel Fischer wrote:

> -- to get the common prefix of two lists, we use explicit recursion,  
> I 
> don't see an elegant way to avoid that.
>
> commonPrefix :: Eq a => [a] -> [a] -> [a]
> commonPrefix (x:xs) (y:ys)
>    | x == y    = x : commonPrefix xs ys
> commonPrefix _ _ = []
>
> produces the result incrementally.

Personally, that's the definition I'd prefer.  It's simple, clear, and  
fast.  If I were forced to hide the recursion, I would probably write  
this:

 > commonPrefix a b = map fst (takeWhile (uncurry (==)) (zip a b))

modulo usage of whatever combination of (.) and/or ($) is in style  
today.

-- James



More information about the Beginners mailing list