1
\$\begingroup\$

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'
 where
 (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?

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Sep 7, 2014 at 0:25
\$\endgroup\$
0

1 Answer 1

2
\$\begingroup\$

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

answered Sep 7, 2014 at 2:20
\$\endgroup\$
1
  • \$\begingroup\$ Seriously -_-. I've actually used that before. Thank you; that solves it nicely. \$\endgroup\$ Commented Sep 7, 2014 at 2:34

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.