tztiyg
Last Updated: February 25, 2016
·
881
· whatgoodisaroad
78c338fe6b267f5e0e91a4a5fa589984

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","","")