[英]Haskell: how to print each element of list separated with comma
I am trying to print list with comma. 我正在尝试用逗号打印列表。 I have list like
["1","2","3"]
and I want to print 1,2,3
How can I do that? 我有类似
["1","2","3"]
,我想打印1,2,3
我该怎么做?
I tried: 我试过了:
printList xs = mapM_ (\(a) -> do
putStr a
putStr (",")) xs
But I dont know how to remove the last comma. 但是我不知道如何删除最后一个逗号。
You can use intercalate
. 您可以使用
intercalate
。 It'll insert the comma between each element of the list and concatenate the resulting list of strings to turn it into a single string. 它将逗号插入列表的每个元素之间,并连接结果字符串列表以将其转换为单个字符串。
import Data.List
toCommaSeparatedString :: [String] -> String
toCommaSeparatedString = intercalate ","
ghci> toCommaSeparatedString ["1","2","3"]
"1,2,3"
This is a bit of an XY problem : as Benjamin Hodgson shows, you're better off turning your list into a string, and then printing that – you want as much of your logic outside of the IO monad as possible. 这是一个XY问题 :正如本杰明·霍奇森(Benjamin Hodgson)所展示的,最好将列表转换成字符串, 然后打印出来–您希望在IO monad 之外尽可能多地使用逻辑。
But of course, even if your question is somewhat in the wrong direction from the start, it has an answer! 不过,当然, 即使你的问题是有些从一开始就走错了方向,它有一个答案! Which is that, for example, you could write this:
例如,您可以这样编写:
printList :: [String] -> IO ()
printList [] = return ()
printList [x] = putStr x
printList (x:xs) = do
putStr x
putStr ","
printList xs
Benjamin's answer is better . 本杰明的答案更好 。 But this one might elucidate
IO
monad code and do
-notation a bit more. 但是,这可能会阐明
IO
monad代码并do
更多的注释。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.