[Haskell-cafe] cutting long strings into lines

Neil Mitchell ndmitchell at gmail.com
Sat Sep 30 11:36:02 EDT 2006


Hi,

You want a function that converts a string into a list of strings,
i.e. with the type signature:

String -> [String]

Go to hoogle (http://haskell.org/hoogle) and search for that:

http://haskell.org/hoogle/?q=String->[String]

(if you can't be bothered to do that, the answer is "lines" ;)

Thanks

Neil

On 9/30/06, Andrea Rossato <mailing_list at istitutocolli.org> wrote:
> 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."
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
>


More information about the Haskell-Cafe mailing list