1

I've seen the other threads about missing split function but I didn't want to peek as I do this for learning purposes and want to figure out myself. So here it is:

split :: Char -> String -> [String]
split c xs | null f = []
           | otherwise = f : split c s'
  where (f,s) = break (== c) xs
        s' | null s = s
           | otherwise = tail s

It seems to work fine (please tell me if anything is wrong with it) but when I use a splitting character that is not in the string then the function returns a list with a single element of the original string whereas I want it to return an empty list. I can't figure out how to do it.

Any ideas?.

1 Answer 1

1

You can simply write a wrapper function, changing the result of your original one:

split' x xs = go (split x xs)  where
   go [_] = []
   go ys = ys

There are many ways to write a split function, e.g.

split x xs = foldl' go [[]] xs where
   go (ys:yss) y | y == x = []:ys:yss
                 | otherwise = (y:ys):yss    

or

 import Data.List 

 split x xs = map tail $ groupBy (const (/=x)) (x:xs)
Sign up to request clarification or add additional context in comments.

1 Comment

+1. The main part of the original function can also be writted as break (== c) >>> second (split c . drop 1) >>> uncurry (:), but it still needs a check to see if xs is empty.

Your Answer

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.