'How can I search for multiple items in a "any" function: haskell
Right now I have this piece of code\
filter (any (=='a')) [String]
-- [String] is just any string list
if you can't tell this just filters for anything in the string containing 'a'. what I want to know is how can I search for multiple characters? if I try making a string/[char] then I get an error because of the inputs that the any function takes. How can I get around this, because for my purposes I will always have a unknown amount of chars, so I need a way to feed multiple characters into this function. Thank you.
Solution 1:[1]
You can use elem to check if something is an element of a list.
filter (`elem` ['a','e','i','o','u']) "hello world!"
-- or
filter (`elem` "aeiou") "hello world!"
This is equivalent to using an explicit lambda:
filter
(\x -> x=='a' || x=='e' || x=='i' || x=='o' || x=='u')
"hello world!"
Solution 2:[2]
You should consider, a function like a -> [a] -> Bool because you are searching for a function, which checks for a character in a list.
So the answer is:
filter (\x -> elem x [1..3]) [1..10]
Solution 3:[3]
As an alternative:
containsVowels :: Foldable t => t Char -> Bool
containsVowels = any (\ch -> (ch ==) `any` vowels)
where vowels = "aeiou"
If any character in a string equal any of the characters in vowels, the answer is True.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | masterjoda99 |
| Solution 3 | Chris |
