Rahmat
Rahmat

Reputation: 107

Haskell Flatten Lists of string

I want to flatten lists of string but with additional requirements. example

[["My","Name","is"],["John","Doe"]]

output : My name is \nJohn Doe

I try using concat function, but still no luck

thanks

Upvotes: 4

Views: 1338

Answers (3)

developer_hatch
developer_hatch

Reputation: 16224

Combining the answer of @John F Miller, you just have to do intercalate and add the element you need, and use concatMap:

import Data.List

ls = [["My","Name","is"],["John","Doe"]]

rs = concatMap (intercalate " ") (insertAt 1 ["\n"] ls)

insertAt _ _ []     = []
insertAt 0 e xs     = e:xs
insertAt n e (x:xs) = x : (insertAt (n-1) e xs)


main = do
  putStrLn rs

$> My Name is
   John Doe

Another option in the comment by @luqui, but I would think in:

rs = intercalate " " . intercalate ["\n"] $ ls

Upvotes: 3

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476699

You can use unwords :: [String] -> String to convert a list of Strings into a single String, and then use intercalate :: [a] -> [[a]] -> [a] to join the lines together with a separator in between, like:

tolines :: [[String]] -> String
tolines = intercalate "\n" . map unwords

Upvotes: 7

John F. Miller
John F. Miller

Reputation: 27217

The function you are looking for is called intercalate and it lives in Data.List. You will have to use it twice. first to add a space between each word of the inner lists then again to add a \n between the outer lists. fmap is your friend.

Upvotes: 6

Related Questions