Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing elements of a list on new lines

Tags:

haskell

I am trying to print the elements of my list onto new lines, but i cant get it to work;

printElements :: [String] -> IO() printElements (x:xs) =  print x (some kind of newline, then loop?) printElements xs 

So this:

["1","2","2","4"] 

would give:

1 2 3 4 
like image 348
Lunar Avatar asked Mar 13 '11 13:03

Lunar


People also ask

How do you print elements of a list in a single line in Python?

When you wish to print the list elements in a single line with the spaces in between, you can make use of the "*" operator for the same. Using this operator, you can print all the elements of the list in a new separate line with spaces in between every element using sep attribute such as sep=”/n” or sep=”,”.

How do you print a newline in a list Python?

The new line character in Python is \n . It is used to indicate the end of a line of text. You can print strings without adding a new line with end = <character> , which <character> is the character that will be used to separate the lines.

How do I print a list of elements without brackets?

use asterisk '*' operator to print a list without square brackets.


2 Answers

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>  
like image 92
David V. Avatar answered Sep 19 '22 16:09

David V.


Your function is:

printElements :: [String] -> IO() printElements [] = return () printElements (x:xs) = do putStrLn x                           printElements xs 

If you already know about monads, you can use mapM_ function:

printElements :: [String] -> IO() printElements = mapM_ putStrLn 

Note: maybe you would have to read the chapter 8 of lyah.

like image 20
Alvivi Avatar answered Sep 19 '22 16:09

Alvivi