How can I only slice the list when the function is not true in haskell?

Viewed 173

I would like to slice my list when the function is not true, but I do not have an idea what I have to give back in the otherwise case. Do you have any idea ?

Example : 
sliceBy odd [1..5] == [[1],[2],[3],[4],[5]]
sliceBy odd [1,3,2,4,5,7,4,6] == [[1,3],[2,4],[5,7],[4,6]]
sliceBy even [1,3,2,4,5,7,4,6] == [[],[1,3],[2,4],[5,7],[4,6]]
sliceBy :: (a -> Bool) -> [a] -> [[a]]
sliceBy _ []  = []
sliceBy _ [x] = [[x]]
sliceBy f (x:xs)
  | f x   = [x] : sliceBy f xs
  | otherwise = ?? 

1 Answers

You can make use of span :: (a -> Bool) -> [a] -> ([a], [a]) and break :: (a -> Bool) -> [a] -> ([a], [a]) to get the longest prefixes where the list does/does not satisfy a given predicate. You thus can use this to make two functions sliceBy and sliceByNot that call each other:

sliceBy :: (a -> Bool) -> [a] -> [[a]]
sliceBy _ [] = []
sliceBy f xs = … : …
    where (xp, xnp) = span f xs

sliceByNot :: (a -> Bool) -> [a] -> [[a]]
sliceByNot _ [] = []
sliceByNot f xs = … : …
    where (xnp, xp) = break f xs

Where you need to fill in the … parts. The two functions thus should call each other.

Related