R – How to print a list of strings using ‘unwords’ in Haskell

haskelllistpretty-print

I want to print list of strings like shown below.

|Name|Country|Age|
------------------
|1   |USA    |20 |
|2   |UK     |19 |

I was able to achieve this using the following.

printfieldName :: [String] -> String
printfieldName [] = []
printfieldName (x:xs)  = "|" ++ x ++ "\t" ++ printfieldName (xs)

Is it possible to achieve this using the inbuilt function 'unwords'. I was able print it using 'unwords' but was unable to place | between the words.

Best Answer

I see there is a additional space between '|' and word, so you can use this function:

printfieldName x = unwords (map ((++) "|") x)  ++ "|"

little explanation:

(++) "|" - creates a function which take prefixes each word with "|", so
(++) "|" "test" -> "|test" 

then, map applies this function to a list of words converting it to ["|1", "|USA", "|20", ... ]

then unwords joins them into a string with spaces between words. The ++ "|" is needed to add final |