Reputation: 1664
Hy, I am new to Haskell and was wondering how should I iterate through list of strings and add newline after certain amount of characters?
I've got this kind of list:
list1 = ["I", "am", "new", "to", "Haskell", "and", "I", "really", "want", "to", "learn", "it"]
and I want to put newline after 10 or less symbols.
One line can't be with more than 10 symbols, and words can't be split.
The output should look like this:
I am new to \n Haskell and \n I really \n want to \n learn it
Any ideas how to do this??
Upvotes: 0
Views: 452
Reputation: 32319
Couple edge cases you don't specify in your question
Here is one such solution. The idea is to start by mapping all words with their lengths. Then, we inspect one word at a time and see if we can add it the current line without overflowing that line.
splitLines :: Int -> [String] -> String
splitLines n = helper 0 . map (\w -> (length w,w))
where
helper :: Int -> [(Int,String)] -> String
helper _ [] = ""
helper lineLength ((wordLength,word):ws)
| lineLength == 0 = word ++ helper wordLength ws
| lineLength + wordLength + 1 > n = "\n" ++ word ++ helper wordLength ws
| otherwise = " " ++ word ++ helper (lineLength + wordLength + 1) words
At GHCi:
ghci> splitLines 10 (words "I am new to Haskell and I really want to learn it")
"I am new\nto Haskell\nand I\nreally\nwant to\nlearn it"
Upvotes: 1