oxsaulxo
oxsaulxo

Reputation: 23

Print elements of a list in the same line

I'm new at haskell and I'm trying to print the elements of a list in a same line . For example:

[1,2,3,4] = 1234 

If elements are Strings I can print it with mapM_ putStr ["1","2","3","\n"] but they aren't.. Someone knows a solution to make a function and print that?

I try dignum xs = [ mapM_ putStr x | x <- xs ] too buts don't work ..

Upvotes: 2

Views: 1387

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476567

You can use show :: Show a => a -> String to convert an element (here an integer), to its textual representation as a String.

Furthermore we can use concat :: [[a]] -> [a] to convert a list of lists of elements to a list of elements (by concatenating these lists together). In the context of a String, we can thus use concat :: [String] -> String to join the numbers together.

So we can then use:

printConcat :: Show a => [a] -> IO ()
printConcat = putStrLn . concat . map show

This then generates:

Prelude> printConcat [1,2,3,4]
1234

Note that the printConcat function is not limited to numbers (integers), it can take any type of objects that are a type instance of the Show class.

Upvotes: 4

Related Questions