As an exercise from RWH, I needed to write a function that splits a list every time the predicate is false (words == splitWith (== ' ') for strings):

splitWith :: (a -> Bool) -> [a] -> [[a]]
splitWith _ [] = []
splitWith p xs
    | null pre = splitWith p post'
    | otherwise = pre : splitWith p post'
        (pre, post) = break p xs
        post' = if null post then [] else tail post

My concern is the if..then..else chain; it seems "forced". I have to make sure that post isn't null, or it will crash on the call to tail.

Is there a better way to write this?


You can gin up a safe version of tail lickety-split by using drop 1.

| improve this answer | |
  • \$\begingroup\$ Seriously -_-. I've actually used that before. Thank you; that solves it nicely. \$\endgroup\$ – Carcigenicate Sep 7 '14 at 2:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.