Last Updated: February 25, 2016
·
1.148K
· whatgoodisaroad

Find a common prefix of two lists:

Take two lists, and yield a 3-tuple of their common prefix and respective suffixes (if any):

sharePrefix :: Eq a => [a] -> [a] -> ([a], [a], [a])
sharePrefix l1 l2 = let 
    prefix = map fst $ takeWhile (uncurry (==)) $ zip l1 l2
    f = drop $ length prefix
  in
  (prefix, f l1, f l2)

For example:

*Main> sharePrefix "Hello, there" "Hello, everybody"
("Hello, ","there","everybody")
*Main> sharePrefix "What's going on?" "This example has no prefix."
("","What's going on?","This example has no prefix.")
*Main> sharePrefix "Badger" "Badger"
("Badger","","")