tags:

views:

205

answers:

7

to write "map f (map g xs)" as a single call to map you could write

example xs = map (f.g) xs

but how would you write "filter p (filter q xs)" as a single call to filter? the dot operator doesnt seem to work for filter as it does for maps. guessing you'd use something else for predicates?

+4  A: 

If you defined a function both that looked like this:

both :: (a -> Bool) -> (a -> Bool) -> a -> Bool
both f g x = f x && g x

Then you could write:

example xs = filter (both p q) xs

I'm not sure if there's a standard function that does this for you...

yjerem
thanks man, that works sure enough. still thinking there might be a more direct way of doing this though (?)
derp
+1  A: 

I'd define a helper function -- this could probably be written more declaratively, but I don't have GHCI installed on this system for testing:

allPredicates :: [a -> Bool] -> a -> Bool
allPredicates []     _ = True
allPredicates (p:ps) x = p x && allPredicates ps x

then

filter (allPredicates [p, q]) xs
John Millikin
`allPredicates = (. flip ($)) . flip all`
ephemient
+3  A: 

Why not a list comprehension?

example = [x | x <- xs, p x, q x]
-- for example
example = [x | x <- [1..10], (>3) x, x<5 ] -- [4]
THC4k
Yeah, list comprehension works well here. The question actually stems from a tutorial I had this week, the implication being there was a straightforward way of doing this. List comprehension is the quickest I've found so far and I'm starting to think there may be no comparitive way as with map and "function composistions".thanks all!
derp
codebliss
+2  A: 

Calling a list of functions on something is essentially what the ap function in Control.Monad does. Then you just and the results. The only slight ugliness is that ap requires both its arguments to be in the same monad (List in this case), so we need to compose it with return to work here.

import Control.Monad
filterByMany funcs = filter (and . ap funcs . return)
Chuck
+3  A: 

I would define a lambda expression.

module Main where

overTen :: Int -> Bool
overTen = (>10)

main :: IO ()
main = do
    print $ filter (\x -> overTen x && even x) [1..20]

output:

$ ghci Test.hs
GHCi, version 6.10.4: http://www.haskell.org/ghc/  :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer ... linking ... done.
Loading package base ... linking ... done.
[1 of 1] Compiling Main             ( Test.hs, interpreted )
Ok, modules loaded: Main.
*Main> main
[12,14,16,18,20]
*Main>
Michael Steele
+4  A: 
ephemient
+1  A: 
import Data.Foldable
import Data.Monoid

p = (>4)
g = (<10)

main = print $ filter (getAll . foldMap (All.) [p,g]) [1..10]

outputs

[5,6,7,8,9]

just because lists are foldable, and you can combine predicate results with the All monoid

barkmadley