Why is there no splitBy in the list module?

Christian Maeder maeder at tzi.de
Thu Jul 13 08:51:37 EDT 2006


Donald Bruce Stewart schrieb:
> maeder:
> 
> -- | The 'splitBy' function takes a predicate and splits the input
> -- list at each element which satisfies the predicate.
> splitBy :: (a -> Bool) -> [a] -> [[a]]
> splitBy p s =
>     case s of
>       [] -> []
>       _  -> let (l, r) = break p s in
>             case r of
>                 _ : t@(_:_) -> l : splitBy p t
>                 _             -> [l]
> 
> -- | The 'split' function splits the input list on each occurrence of
> -- the given element.
> split :: Eq a => a -> [a] -> [[a]]
> split c = splitBy (== c)
> 
> 
> prop_lines_split xs = 
>     lines xs == split '\n' xs
> 
> prop_words_split xs = 
>     words xs == split ' ' xs

The last property is wrong. It must be:

prop_words_split =
    words xs == filter (not . null) (split ' ' xs)

Another property of my suggested functions:

splitWords, splitLines, splitFields :: Eq a => a -> [a] -> [[a]]

id = concat . intersperse [c] . splitFields c -- :: [a] -> [a]

splitLines is equal to splitFields as long as there is no last seperator
(or terminator) element. splitWords can be easily derived from
splitLines or splitFields via "filter (not . null)".

splitFields c = splitLines c . (++ [c])

Which of the two versions splitFields or splitLines should get the
general name "split" is a matter of taste and of compatibility to the
currently incompatible Data.PackedString or (your) Data.ByteString.

If we cannot agree, I'ld suggest to keep (my) longer names, only.

Cheers Christian



More information about the Libraries mailing list