Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell Filtering but keeping the filtered

Tags:

haskell

In my understanding, the Haskell filter function filter a bs would filter all a's from a list bs.

Is there a simple method or variation of filter that would do the opposite, only keeping the a's from the list bs, basically creating a list of a's.

like image 753
Chillo Avatar asked Oct 15 '25 07:10

Chillo


1 Answers

Well, that's imprecise wording anyway. The signature is

filter :: (a -> Bool) -> [a] -> [a]

so filter a bs is described as filter all elements from bs that fulfill a.

So to "do the opposite", you just need to invert the predicate. For instance,

Prelude> filter (== 'a') "Is there a simple method or variation of filter that"
"aaaa"
Prelude> filter (/= 'a') "Is there a simple method or variation of filter that"
"Is there  simple method or vrition of filter tht"

In general:

filterNot :: (a -> Bool) -> [a] -> [a]
filterNot pred = filter $ not . pred

Prelude> filterNot (== 'a') "Is there a simple method or variation of filter that"
"Is there  simple method or vrition of filter tht"

like image 173
leftaroundabout Avatar answered Oct 17 '25 00:10

leftaroundabout



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!