peter.s
peter.s

Reputation: 67

How could I filter for many conditions in a list in Haskell?

the function definition is already given

filterMany :: [a -> Bool] -> [a] -> [a]
filterMany (f:fs) [] = []
filterMany (f:fs) (x)
  | filter (f) x == True = x : filter (fs) x
  | otherwise = filter (fs) x

the output should be:

filterMany [even, odd] [1..10] == []
filterMany [even, (\x -> x `mod` 4 /= 0)] [1..10] == [2,6,10]
filterMany [(<7), (>3), odd] [1..20] == [5]

Upvotes: 1

Views: 220

Answers (2)

user12756874
user12756874

Reputation: 1

Another way:

filterMany :: [a -> Bool] -> [a] -> [a]
filterMany [] (x:xs) = (x:xs)
filterMany (f:fs) (x:xs) = filter f (filterMany (fs) (x:xs))

Upvotes: 0

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477684

You can make use of all :: (a -> Bool) -> [a] -> Bool here to check if all conditions are met. We thus can implement this with:

filterMany :: Foldable f => f (a -> Bool) -> [a] -> [a]
filterMany fs = filter (\x -> all ($ x) fs)

We here thus apply all predicates with parameter x by specifying all ($ x) fs. If all these predicates hold, then we retrain the element x.

For example:

Prelude> filterMany [even, odd] [1..10]
[]
Prelude> filterMany [even, (\x -> x `mod` 4 /= 0)] [1..10]
[2,6,10]
Prelude> filterMany [(<7), (>3), odd] [1..20]
[5]

Upvotes: 1

Related Questions