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","","")
Written by Wyatt Allen
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Haskell
Authors
Related Tags
#haskell
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#