Home > Mobile >  How can I filter out in haskell?
How can I filter out in haskell?

Time:02-11

I know about the filter function but I'm wondering how I can filter out. For example: filter odd [1,2,3] = [1,3], but I want filter (not(odd)) [1,2,3] = [2] (yes I know there's an even function but this is just an example of it). I don't know if there's a separate function that I don't know about or if there's just something I can add to the argument. Thanks. note: I can't use the GHC.Utils.Misc filterOut.

CodePudding user response:

You were quite close, you can use:

filter (not . odd) [1, 2, 3]

here we thus construct a function \x -> not (odd x), that will thus retain all elements that are not odd, so even.

CodePudding user response:

One might also use the partition function from Data.List.

Prelude> import Data.List
Prelude Data.List> lst = [1,2,3,4,5,6,7,8]
Prelude Data.List> (odds, evens) = partition odd lst
Prelude Data.List> odds
[1,3,5,7]
Prelude Data.List> evens
[2,4,6,8]

Another alternative would be to use a list comprehension in place of filter.

Prelude Data.List> [x | x <- lst, not $ odd x]
[2,4,6,8]
  • Related