Home > Software engineering >  How can I search for multiple items in a "any" function: haskell
How can I search for multiple items in a "any" function: haskell

Time:02-12

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.

CodePudding user response:

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

CodePudding user response:

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]
  • Related