Skip to content

Instantly share code, notes, and snippets.

@orospakr
Last active December 10, 2015 01:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save orospakr/4364251 to your computer and use it in GitHub Desktop.
Save orospakr/4364251 to your computer and use it in GitHub Desktop.
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