[Haskell-cafe] wordsBy in the base libraries?

Neil Mitchell ndmitchell at gmail.com
Mon Oct 22 06:36:23 EDT 2007


Hi

> > You are still over by one test. Try instead:
> >
> > wordsBy :: (a -> Bool) -> [a] -> [[a]]
> > wordsBy p s = case dropWhile p s of
> >    []      -> []
> >    s':rest -> (s':w) : wordsBy p (drop 1 s'')
> >           where (w, s'') = break p rest
>
> This still has the redundant empty list tests,

Perhaps. Something like SpecConstr can remove them. Also remember that
p may be arbitrarily expensive, while a test for an empty list is
cheap. In the particular case of words, p (i.e. isSpace) is very
expensive.

> and in fact introduces another one in drop 1,
> as well as some gratuitous arithmetic.

The actual version I use is drop1, where drop1 is defined as:

drop1 [] = []
drop1 (x:xs) = xs

Also known as safeTail in the "Safe" library.

Thanks

Neil


More information about the Haskell-Cafe mailing list