Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell filter/split list

Tags:

list

haskell

I want something like

splitBy pred list = ( filter pred list, filter (not . pred) list )

but in one pass.

like image 615
crimsonlander Avatar asked Feb 19 '13 23:02

crimsonlander


1 Answers

You are looking for the partition function from Data.List:

partition :: (a -> Bool) -> [a] -> ([a], [a])

It can be implemented nicely using a fold:

splitBy pred = foldr f ([], []) 
    where f x ~(yes, no) = if pred x then (x : yes, no) 
                                    else (yes, x : no)
like image 107
Niklas B. Avatar answered Oct 01 '22 18:10

Niklas B.