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
You can use unwords :: [String] -> String
to convert a list of String
s 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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With