Skip to content

Instantly share code, notes, and snippets.

@orospakr
Last active Dec 10, 2015
Embed
What would you like to do?
splitBy :: (a -> Bool) -> [a] -> [[a]]
splitBy _ [] = []
splitBy predicate list = [left] ++ splitBy predicate remaining
where (left, remaining) = break predicate list
-- example:
-- splitBy (==20) [0, 1, 2, 3, 4, 67, 20, 5, 6, 9, 20, 100, 200]
-- should produce:
-- [[0, 1, 2, 3, 4, 67], [20, 5, 6, 9], [20, 100, 200]]
-- instead produces:
-- [[0,1,2,3,4,67],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],...]
-- solved by (also changed the behaviour to exclude the delimiter from the output):
splitBy' :: (a -> Bool) -> [a] -> [[a]]
splitBy' _ [] = []
splitBy' predicate list = if (null left) then (splitBy' predicate $ tail remaining) else ([left] ++ splitBy' predicate remaining)
where (left, remaining) = break predicate list
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment