Created
May 11, 2012 08:58
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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