No, splitWhen
can't do that for you, because it throws away the delimeters, and you need to keep all the input data:
splitWhen checkEven [1,2,3,4,6,8,9,10] == [[1],[3],[],[],[9],[]]
You can use the Data.List.Split library to do that, because it's very flexible.
We can split whenever the element is even, so we use whenElt even
:
ghci> :m Data.List.Split
ghci> split (whenElt even) [1,11,2,22,3,33,333,4,6,8,9,99,999,10,100]
[[1,11],[2],[],[22],[3,33,333],[4],[],[6],[],[8],[9,99,999],[10],[],[100],[]]
but we want to condense multiple delimiters like 2,22
into a single list instead of having an empty list of odd numbers in between as we have there, so we use the condense
modifier:
ghci> split (condense $ whenElt even) [1,11,2,22,3,33,333,4,6,8,9,99,999,10,100]
[[1,11],[2,22],[3,33,333],[4,6,8],[9,99,999],[10,100],[]]
but let's drop the final blank list that happens because there's another empty list of odds at the end:
ghci> split (dropFinalBlank . condense $ whenElt even) [1,11,2,22,3,33,333,4,6,8,9,99,999,10,100]
[[1,11],[2,22],[3,33,333],[4,6,8],[9,99,999],[10,100]]
If on the other hand you're implementing this from the ground up, then you'll need to use the break
function.
splitWhen
? – jub0bssplitWhen :: (a -> Bool) -> [a] -> [[a]]
givingsplitWhen (<0) [1,3,-4,5,7,-9,0,2] == [[1,3],[5,7],[0,2]]
– AndrewCpartition
function? (link). Otherwise I would familiarize myself withbreak
andspan
(link) which are useful list parsing functions. – ErikR