Xodarap
Xodarap

Reputation: 11849

Map newlines in GHCi

Simple question, but I can't seem to figure it out. I have a list, and I want to print out each element of it on its own line. I can do

map show [1..10]

for example, which will print out them all together, but with no newlines. My thought was to do map (putStrLn $ show) [1..10] but this won't work because I just get back an [IO()]. Any thoughts?

Upvotes: 2

Views: 578

Answers (3)

Robert Massaioli
Robert Massaioli

Reputation: 13477

Here is my personal favourite monad command called sequence:

sequence :: Monad m => [m a] -> m [a]

Therefore you could totally try:

sequence_ . map (putStrLn . show) $ [1..10]

Which is more wordy but it leads upto a function I find very nice (though not related to your question):

sequence_ . intersperse (putStrLn "")

Maybe an ugly way to do that but I thought it was cool.

Upvotes: 6

applicative
applicative

Reputation: 8199

Aren't these answers putting too much emphasis on IO? If you want to intersperse newlines the standard Prelude formula is :

> unlines (map show [1..10])
"1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n"

This is the thing you want written - newlines are characters not actions, after all. Once you have an expression for it, you can apply putStrLn or writeFile "Numbers.txt" directly to that. So the complete operation you want is something like this composition:

putStrLn . unlines . map show

In ghci you'd have

> (putStrLn . unlines . map show) [1,2,3]
1
2
3

Upvotes: 9

Joel Burget
Joel Burget

Reputation: 1438

Try this: mapM_ (putStrLn . show) [1..10]

Upvotes: 6

Related Questions