better way: contains one of a string from list in a string
Hi, I needed a function that returns True/False if a list of strings are in a given string. I made one function below (works fine),..but I was wondering whether there is a shorter way? -- |Returns True if one of given strings are contained in given string contains :: [String] -> String -> Bool contains elements seach_elem | trueListCount == 0 = False | otherwise = True where isInStringList = [isInfixOf elem seach_elem | elem <- elements] onlyTrueList = [elem | elem <- isInStringList, elem == True] trueListCount = length onlyTrueList Cheers, -m
You can get that one quite easily using 'any'. E.g. [Prelude Data.List] λ let contains xs x = any (`isInfixOf` x) xs contains :: (Eq a, Foldable t) => t [a] -> [a] -> Bool [Prelude Data.List] λ contains (words "a b c d efg") "refgood" True it :: Bool [Prelude Data.List] λ contains (words "a b c d efg") "ref" False it :: Bool On Sun, Mar 20, 2016 at 6:02 PM, Miro Karpis <miroslav.karpis@gmail.com> wrote:
Hi,
I needed a function that returns True/False if a list of strings are in a given string. I made one function below (works fine),..but I was wondering whether there is a shorter way?
-- |Returns True if one of given strings are contained in given string contains :: [String] -> String -> Bool contains elements seach_elem | trueListCount == 0 = False | otherwise = True where isInStringList = [isInfixOf elem seach_elem | elem <- elements] onlyTrueList = [elem | elem <- isInStringList, elem == True] trueListCount = length onlyTrueList
Cheers, -m
_______________________________________________ Beginners mailing list Beginners@haskell.org http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners
participants (2)
-
Lyndon Maydwell -
Miro Karpis