Optimising words

Neil Mitchell ndmitchell at gmail.com
Mon Jul 9 17:44:19 EDT 2007


Hi

> An optimised version of words:
>
> words                   :: String -> [String]
> words s                 =  case dropWhile isSpace s of
>                                 "" -> []
>                                 s:ss -> (s:w) : words s''
>                                       where (w, s'') = break isSpace ss

Thinking harder, this is an improvement, but not as good as we can
get. If s'' is non-empty, then the first character must be a space,
which we can drop without testing:

words                   :: String -> [String]
words s                 =  case dropWhile isSpace s of
                                "" -> []
                                s:ss -> (s:w) : words (drop1 s'')
                                      where (w, s'') = break isSpace ss

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

(of course, drop1 = drop 1, but if we're going for maximum efficience :-) )

I think this now ensures that we only test each character once for
being a space.

Thanks

Neil


More information about the Libraries mailing list