Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 654
Rahmat Avatar asked Jul 30 '19 06:07

Rahmat


3 Answers

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
like image 150
Willem Van Onsem Avatar answered Nov 19 '22 02:11

Willem Van Onsem


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.

like image 6
John F. Miller Avatar answered Nov 19 '22 03:11

John F. Miller


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
like image 3
A Monad is a Monoid Avatar answered Nov 19 '22 02:11

A Monad is a Monoid