Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.8k views
in Technique[技术] by (71.8m points)

haskell - Printing elements of a list on new lines

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 , 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
2
3
4
"
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> 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...