如何将x元组添加到列表中x次? [英] How do I add x tuples into a list x number of times?
问题描述
当我不知道X时,如何将元组添加到列表中x次数?
在进行函数式编程时,通常考虑操作的组合而不是单个步骤。所以我们可以通过首先将输入分割成一个字符串列表,然后将每个字符串转换为一个元组来获得它,而不是像想一样将元组添加到列表中。 b $ b
假设元组每行写入一行,我们可以使用 lines
分割输入,然后使用 read
来解析每个元组。为了使它在整个清单上工作,我们使用 map
。
main = do input< - getContents
let tuples = map read(lines input):: [(String,Integer)]
打印元组
$ b $ p
$ runghc Tuples.hs
(Hello,2)
(Haskell,4)
,我按 Ctrl + D 将EOF发送到程序(或Windows上的 Ctrl + Z )并打印结果。
[(Hello,2),(Haskell,4)]
如果你想要更具交互性的东西,你可能需要做自己的递归。参见 Daniel Wagner的回答为例。
I have a question about tuples and lists in Haskell. I know how to add input into a tuple a specific number of times. Now I want to add tuples into a list an unknown number of times; it's up to the user to decide how many tuples they want to add.
How do I add tuples into a list x number of times when I don't know X beforehand?
When doing functional programming, it is often better to think about composition of operations instead of individual steps. So instead of thinking about it like adding tuples one at a time to a list, we can approach it by first dividing the input into a list of strings, and then converting each string into a tuple.
Assuming the tuples are written each on one line, we can split the input using lines
, and then use read
to parse each tuple. To make it work on the entire list, we use map
.
main = do input <- getContents
let tuples = map read (lines input) :: [(String, Integer)]
print tuples
Let's try it.
$ runghc Tuples.hs
("Hello", 2)
("Haskell", 4)
Here, I press Ctrl+D to send EOF to the program, (or Ctrl+Z on Windows) and it prints the result.
[("Hello",2),("Haskell",4)]
If you want something more interactive, you will probably have to do your own recursion. See Daniel Wagner's answer for an example of that.
这篇关于如何将x元组添加到列表中x次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!