filter -package:Cabal -package:vector -package:containers -package:utility-ht package:base

filter, applied to a predicate and a list, returns the list of those elements that satisfy the predicate; i.e.,
filter p xs = [ x | x <- xs, p x]

Examples

>>> filter odd [1, 2, 3]
[1,3]
>>> filter (\l -> length l > 3) ["Hello", ", ", "World", "!"]
["Hello","World"]
>>> filter (/= 3) [1, 2, 3, 4, 3, 2, 1]
[1,2,4,2,1]
filter p xs removes any elements from xs that do not satisfy p.
This generalizes the list-based filter function.
runIdentity (filterM (Identity . p) xs) == filter p xs

Examples

>>> filterM (\x -> do
putStrLn ("Keep: " ++ show x ++ "?")
answer <- getLine
pure (answer == "y"))
[1, 2, 3]
Keep: 1?
y
Keep: 2?
n
Keep: 3?
y
[1,3]
>>> filterM (\x -> do
putStr (show x)
x' <- readLn
pure (x == x'))
[1, 2, 3]
12
22
33
[2,3]
Direct MonadPlus equivalent of filter.

Examples

The filter function is just mfilter specialized to the list monad:
filter = ( mfilter :: (a -> Bool) -> [a] -> [a] )
An example using mfilter with the Maybe monad:
>>> mfilter odd (Just 1)
Just 1

>>> mfilter odd (Just 2)
Nothing