New function isInfixOf that searches a list for a given sublist
authorJohn Goerzen <jgoerzen@complete.org>
Thu, 31 Aug 2006 15:15:56 +0000 (15:15 +0000)
committerJohn Goerzen <jgoerzen@complete.org>
Thu, 31 Aug 2006 15:15:56 +0000 (15:15 +0000)
Example:

isInfixOf "Haskell" "I really like Haskell." -> True
isInfixOf "Ial" "I really like Haskell." -> False

This function was first implemented in MissingH as MissingH.List.contains

Data/List.hs

index da6c878..8b504f7 100644 (file)
@@ -100,6 +100,7 @@ module Data.List
    -- ** Predicates
    , isPrefixOf        -- :: (Eq a) => [a] -> [a] -> Bool
    , isSuffixOf        -- :: (Eq a) => [a] -> [a] -> Bool
+   , isInfixOf         -- :: (Eq a) => [a] -> [a] -> Bool
 
    -- * Searching lists
 
@@ -266,6 +267,17 @@ isPrefixOf (x:xs) (y:ys)=  x == y && isPrefixOf xs ys
 isSuffixOf              :: (Eq a) => [a] -> [a] -> Bool
 isSuffixOf x y          =  reverse x `isPrefixOf` reverse y
 
+-- | The 'isInfixOf' function takes two lists and returns 'True'
+-- iff the first list is contained, wholly and intact,
+-- anywhere within the second.
+--
+-- Example:
+--
+-- >isInfixOf "Haskell" "I really like Haskell." -> True
+-- >isInfixOf "Ial" "I really like Haskell." -> False
+isInfixOf               :: (Eq a) => [a] -> [a] -> Bool
+isInfixOf needle haystack = isJust $ find (isPrefixOf needle) (tails haystack)
+
 -- | The 'nub' function removes duplicate elements from a list.
 -- In particular, it keeps only the first occurrence of each element.
 -- (The name 'nub' means \`essence\'.)