Amber
Amber

Reputation: 275

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.

Upvotes: 0

Views: 127

Answers (3)

Chris
Chris

Reputation: 36611

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.

Upvotes: 0

chi
chi

Reputation: 116139

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!"

Upvotes: 2

masterjoda99
masterjoda99

Reputation: 84

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]

Upvotes: 1

Related Questions