2

简单的问题,但我似乎无法弄清楚。我有一个列表,我想在自己的行上打印出它的每个元素。我可以

map show [1..10]

例如,它将一起打印出来,但没有换行符。我的想法是这样做map (putStrLn $ show) [1..10],但这行不通,因为我刚刚得到一个[IO()]. 有什么想法吗?

4

3 回答 3

9

这些答案是不是太强调 IO 了?如果你想穿插换行,标准的 Prelude 公式是:

> 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
于 2011-03-01T05:14:33.323 回答
6

试试这个:mapM_ (putStrLn . show) [1..10]

于 2011-03-01T02:37:44.707 回答
6

这是我个人最喜欢的名为sequence的 monad 命令:

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

因此,您完全可以尝试:

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

哪个更罗嗦,但它导致了一个我觉得非常好的功能(虽然与你的问题无关):

sequence_ . intersperse (putStrLn "")

也许这样做是一种丑陋的方式,但我认为这很酷。

于 2011-03-01T02:37:57.150 回答