Printing elements of a list on new lines

In most cases you don’t need to program a loop over a list, it’s been done already. To loop over a list with a monadic function, you would use mapM (and its mapM_ variant if you don’t care about the result.)

If you use print, for ["1","2","3","4"] you’d get :

Prelude> mapM_ print ["1","2","3","4"]
"1"
"2"
"3"
"4"
Prelude> 

print is actually :

print :: Show a => a -> IO ()
print x = putStrLn (show x)

the show function causes the string "1" to be converted to "\"1\"", putStrLn prints that and a newline.

If you replace the print by putStrLn, you remove the conversion step and print directly the string:

Prelude> mapM_ putStrLn ["1","2","3","4"]
1
2
3
4
Prelude> 

Now I would like to offer another solution. The Haskell way of doing things is doing as much as you can in a pure way, and only use IO when you need it.

So in this case we can join all strings to be printed with a \n, and print all the strings at once.

To join all the strings there’s a handy function : unlines

Prelude> unlines ["1","2","3","4"]
"1\n2\n3\n4\n"
Prelude> 

Now you just have to print that; notice that unlines put a newline after the last item of the list, so we’ll use putStr instead of putStrLn

Prelude> putStr ( unlines ["1","2","3","4"] )
1
2
3
4
Prelude> 

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)