简体   繁体   English

Haskell:如何打印用逗号分隔的列表的每个元素

[英]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.

相关问题 在Python列表中打印最匹配的列表,其中每个元素都在内部分开 - Print the best match in the Python list, where each element is separated internally 如何在 python 中分配逗号分隔元素以形成列表 - How to distribute comma separated element to form a list in python 如何在haskell中将列表中的每个元素与另一个列表中的每个元素相除 - How to divide every element in a list with each element in another list in haskell 如何打印列表中每个元素的第一个字母 - how to print first letter of each element in list 如何在每个列表中打印特定元素 - How to print a certain element in each list 如何处理字符串列表,其中每个字符串也可能是逗号分隔的字符串列表? - How can I process a list of strings where each string may be a comma-separated list of strings as well? 如何迭代和打印列表中的每个元素(Python) - How to iterate and print each element in list (Python) 如何 select 用户字符串输入列表的元素内的元素的索引,用逗号分隔? - How to select an index of an element inside an element of a list of a user's string input separated by comma? Haskell列表理解(列表元素的打印sqrt) - Haskell list comprehension (print sqrt for element of list) 如何将逗号分隔的元素列表转换为空格分隔的元素列表 - how to convert a comma separated elements list into space separated elements list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM