[Haskell-cafe] cutting long strings into lines
Bertram Felgenhauer
bertram.felgenhauer at googlemail.com
Sat Sep 30 14:21:53 EDT 2006
Matthias Fischmann wrote:
>
> On Sat, Sep 30, 2006 at 11:54:19AM -0400, Mark T.B. Carroll wrote:
> > module WordWrap (wrap) where
> > import Data.Maybe
> >
> > options :: String -> [(String, String)]
> >
> > options [] = [("", "")]
> >
> > options (x:xs) =
> > let rest = map (\(ys, zs) -> (x:ys, zs)) (options xs)
> > in if x == ' ' then ("", xs) : rest else rest
> >
> > bestSplit :: Int -> String -> (String, String)
> >
> > bestSplit width string =
> > last (head wraps : takeWhile ((<= width) . length . fst) (options string))
>
> Works better if you just skip the "head wraps" part. (and now i am
> curious: what was it supposed to mean? how did it get there?)
I'll venture a guess: The code originally read
| bestSplit width string =
| let wraps = options string
| in last (head wraps : takeWhile ((<= width) . length . fst) wraps)
Without a precaution like this, long words will cause wrap to go into an
infinite loop. Depending on your requirements you could also consider
| bestSplit width string =
| last (splitAt width string : takeWhile ((<= width) . length . fst)
| (options string))
which will cut too long words into pieces fitting on the lines.
(code untested)
regards,
Bertram
More information about the Haskell-Cafe
mailing list