[Haskell-cafe] cutting long strings into lines

Andrea Rossato mailing_list at istitutocolli.org
Sat Sep 30 11:02:34 EDT 2006


Hello!

I've been trying for quite some time to find an elegant solution to
cut long strings into lines, but the only solution I was able to come
up is the following piece of ugly code.

Is there a library function for that? What kind of approach would you
suggest?

Thanks for your kind attention.

Andrea

Here's the code:

-- does the actual job
wrapString str =  foldr addNL "" $ rmFirstSpace $ concat $ splitS (getIndx $ indx str) str

-- gets the indexes of the spaces within a string 
indx = findIndices (\x -> if x == ' ' then True else False)

-- gets the indexes of where to split the string into lines: lines
-- must be between 60 and 75 char long
getIndx :: [Int] -> [Int]
getIndx = takeFirst . checkBound . (delete 0) . nub . map (\x -> if  x > 60  && x `rem` 60 >= 0 && x `rem` 70 <= 10  then x else 0)

-- groups indexes when their distance is too short
checkBound = groupBy (\x y -> if y - x < 10 then True else False)

-- takes the first index of a group of indexes
takeFirst = map (\(x:xs) -> x)

-- split a string given a list of indexes
splitS _ [] = []
splitS (x:xs) (ls) = [take x ls] : splitS (map (\i -> i - x) xs) (drop x ls)
splitS _ ls = [ls]:[]

-- remove the first space from the begging of a string in a list of strings 
rmFirstSpace = map (\(x:xs) -> if x == ' ' then xs else x:xs) 

-- used by foldr to fold the list of substrings 
addNL s s1 = s ++ "\n" ++ s1


try with putStrLn $ wrapString longString
where: 
longString = "The Haskell XML Toolbox (HXT) is a collection of tools for processing XML with Haskell. The core component of the Haskell XML Toolbox is a domain specific language, consisting of a set of combinators, for processing XML trees in a simple and elegant way. The combinator library is based on the concept of arrows. The main component is a validating and namespace aware XML-Parser that supports almost fully the XML 1.0 Standard. Extensions are a validator for RelaxNG and an XPath evaluator."


More information about the Haskell-Cafe mailing list