nick_green
nick_green

Reputation: 1664

How to iterate through list of strings and add new line after certain count of chars in Haskel?

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

Answers (1)

Alec
Alec

Reputation: 32319

Couple edge cases you don't specify in your question

  • What happens if a word is longer than 10 characters? I'm going to assume that word should go on a line of its own
  • Should we count the spaces that go between words? I'm going to assume yes again (even if your example seems to say the contrary).

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

Related Questions