Skip to content

Instantly share code, notes, and snippets.

@dtchepak
Created May 11, 2012 08:58
Show Gist options
  • Save dtchepak/2658510 to your computer and use it in GitHub Desktop.
Save dtchepak/2658510 to your computer and use it in GitHub Desktop.
Attempt at splitting a single list into segments whenever a predicate is matched
splitWhere :: [a] -> (a -> Bool) -> [[a]]
splitWhere xs p = combine [] rest lists
where
(lists, rest) = foldr (\x (l,r) -> if p x then (combine [x] r l,[]) else (l,x:r)) ([],[]) xs
combine [] [] c = c
combine [] b c = b:c
combine a [] c = a:c
combine a b c = a:b:c
-- Implementations below based on comments from #haskell IRC
split' :: [a] -> (a -> Bool) -> [[a]]
split' [] _ = []
split' (h:t) p = case split' t p of
all@(x:xs) -> if p h then [h]:all else (h:x):xs
[] -> [[h]]
{-
*Main> "a|b|c" `split'` (=='|')
["a|","b|","c"]
-}
split'' :: [a] -> (a->Bool) -> [[a]]
split'' xs p = case break p xs of
([],[]) -> []
(l,[]) -> [l]
(l,r:rs) -> l:[r]:split'' rs p
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment