patternMinor
Implementing `split`
Viewed 0 times
splitimplementingstackoverflow
Problem
I implemented the
Note that I'm calling
example:
Testing
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",""]Solution
Generally it looks good, at least to an Haskell beginner like me.
I find the use of
I think it could also have introduced a bug. What is the expected behaviour for
Your code returns
This solution fixed the issue.
I prefer using meaningful variable names, such as
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:xsI 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.Code Snippets
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:xsContext
StackExchange Code Review Q#62917, answer score: 6
Revisions (0)
No revisions yet.