I've written the following explode
function using break
. The intended behavior is, that a list is divided into sublists by a predicate function, i.e. those elements which match the predicate are the separators - no empty lists should be returned.
Here are some examples:
explode id [True, True, False] = [[False]]
explode id [False, True, False] = [[False], [False]]
explode undefined [] = []
explode id [False, False, True, False] = [[False, False], [False]]
explode (\x -> mod x 3 == 0) [0..10] = [[1,2],[4,5],[7,8],[10]]
The signature of this function is:
explode :: (a -> Bool) -> [a] -> [[a]]
Here is the implementation:
explode _ [] = []
explode f xs
| null zs = [z]
| null z = explode f (tail zs)
| True = z : explode f (tail zs)
where (z, zs) = break f xs
Is there a better way to do this, a maybe more haskell-idiomatic one? Also, what is the complexity of such a function? I believe the running time is linear, but what about the space complexity?