7
\$\begingroup\$

I implemented the split function in Haskell:

split :: (Eq a) => a -> [a] -> [[a]]
split _ [] = []
split x ys = f : split x rest 
 where (f, rest) = break (== x) (dropWhile (== x) ys) 

Note that I'm calling dropWhile (== x) since break's second-tuple value will include the "broken on" value.

example:

*Main> break (== 'a') "dogacactus"
("dog","acactus")

Testing

*Main> split2 '3' "123aaaBBB3"
["12","aaaBBB",""]
asked Sep 14, 2014 at 23:30
\$\endgroup\$

1 Answer 1

6
\$\begingroup\$

Generally it looks good, at least to an Haskell beginner like me. I find the use of dropWhile to be a bit confusing. I admit I had to read your comment to understand why you used it.

I think it could also have introduced a bug. What is the expected behaviour for split ',' ",,"? Your code returns [""] but I would expect ["","",""]. Was your behaviour intended?

This solution fixed the issue.

split :: (Eq a) => a -> [a] -> [[a]]
split _ [] = []
split separator ys = f : (split separator (dropSeparator separator rest))
 where (f, rest) = break (== separator) ys
dropSeparator :: Eq a => a -> [a] -> [a]
dropSeparator _ [] = []
dropSeparator separator (x:xs) = if x == separator then xs else x:xs

I prefer using meaningful variable names, such as separator, even if I'm not sure if it is idiomatic Haskell. Ditto for the parentheses and the introduction of the helper function.

answered Sep 16, 2014 at 20:23
\$\endgroup\$
1
  • \$\begingroup\$ thank you for letting me know that my usage of dropWhile was both confusing and incorrect! Initially I wanted to do something like where (f, _:rest) = ... , but that would fail to match for []. \$\endgroup\$ Commented Sep 16, 2014 at 20:35

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.