tags:

views:

316

answers:

3

The filter class of functions takes a condition (a -> Bool) and applies it when filtering.

What is the best way to use a filter on when you have multiple conditions?

Used the applicative function liftA2 instead of liftM2 because I for some reason didn't understand how liftM2 worked within pure code.

+2  A: 

Well, you can combine functions however you want in Haskell (as long as the types are correct) and using lambdas you don't even have to name your predicate function, i.e.,

filter (\x -> odd x && x > 100) [1..200]
Jonas
+5  A: 

The liftM2 combinator can be used in the Reader monad to do this in a 'more functional' way:

import Control.Monad
import Control.Monad.Reader

-- ....

filter (liftM2 (&&) odd (> 100)) [1..200]

Note that the imports are important; Control.Monad.Reader provides the Monad (e ->) instance that makes this all work.

The reason this works is the reader monad is just (e ->) for some environment e. Thus, a boolean predicate is a 0-ary monadic function returning bool in an environment corresponding to its argument. We can then use liftM2 to distribute the environment over two such predicates.

Or, in simpler terms, liftM2 will act a bit like this when the types work out:

liftM2 f g h a = f (g a) (h a)

You can also define a new combinator if you want to be able to chain these easily, and/or don't want to mess with liftM2:

(.&&.) :: (a -> Bool) -> (a -> Bool) -> (a -> Bool)
(.&&.) f g a = (f a) && (g a)
-- or, in points-free style:
(.&&.) = liftM2 (&&)    

filter (odd .&&. (> 5) .&&. (< 20)) [1..100]
bdonlan
+2  A: 

Let's say your conditions are stored in a list called conditions. This list has the type [a -> Bool].

To apply all conditions to a value x, you can use map:

map ($ x) conditions

This applies each condition to x and returns a list of Bool. To reduce this list into a single boolean, True if all elements are True, and False otherwise, you can use the and function:

and $ map ($ x) conditions

Now you have a function that combines all conditions. Let's give it a name:

combined_condition x = and $ map ($ x) conditions

This function has the type a -> Bool, so we can use it in a call to filter:

filter combined_condition [1..10]
Ayman Hourieh
Careful with ($x) as opposed to ($ x), as if you turn on Template Haskell for some other reason the $x will suddenly look like a splice.
Ganesh Sittampalam
You've discovered the `all` function: `filter (all conditions) [1..10]`
Peter Burns
There's also the any function, depending on how you want to combine the predicates:any p = or . map p;all p = and . map p;
Peter Burns
@Peter: all has type (a -> Bool) -> [a] -> Bool, not [(a -> Bool)] -> a -> Bool.
Stephan202
@Ganesh Good point. Fixed.
Ayman Hourieh
@Peter as Stephan202 pointed out, 'all' applies one condition to a list of values. My function applies a list of conditions to a single value.
Ayman Hourieh