Monday 6 June 2016

Haskell: Divide list to two sub lists

Divide lists to two sublists, list1 contains all the elements that satisfy given predicate, list2 contains all the elements that don’t satisfy given predicate.


ListUtil.hs
divideList :: (a -> Bool) -> [a] -> ([a], [a])
divideList p list = (filter p list, filter (not . p) list)

Prelude> :load ListUtil.hs
[1 of 1] Compiling Main             ( ListUtil.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> divideList odd [1, 2, 3, 4, 5, 6, 7]
([1,3,5,7],[2,4,6])
*Main> 
*Main> divideList even [1, 2, 3, 4, 5, 6, 7]
([2,4,6],[1,3,5,7])
*Main> 


Previous                                                 Next                                                 Home

No comments:

Post a Comment