读取指定行数
我一直使用 C++ 和 Pascal 进行编程,并且思考得太势利了。那么,任何人都可以帮助我解决这个问题:
考虑我们有以下输入模式:
integer n
n strings
other data
例如:
2
foo
bar
3 4
and so on.
所以,我只需要将 n 个字符串读入列表,而不读取其他数据。如果没有类似 for 的结构,我应该如何做到这一点?
I've always programmed on C++ and Pascal and think too imperatively. So, could anyone help me with the question:
Consider we have the following input pattern:
integer n
n strings
other data
For example:
2
foo
bar
3 4
and so on.
So, I need to read only n Strings into a List, without reading other data. How should I do that without for-like constructions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一种可能的方法是
getLine
,它是一种 IO 操作,它从标准输入读取一行并将其作为字符串返回。它的类型是IO String
。replicate n
创建一个包含n
个相同项目的列表。因此,replicate n getLine
是一个n
个 IO 操作的列表,每个操作返回一个字符串:[IO String]
。sequence
是一个函数,它接受返回某些内容的操作列表,并将其转换为返回该内容列表的单个操作。因此,如果我们有一个[IO String]
,那么sequence
会将其转换为IO [String]
。这正是我们想要的。
One possible method is
getLine
is an IO action that reads a line from the standard input and returns it as a string. Its type isIO String
.replicate n
creates a list ofn
identical items. Soreplicate n getLine
is a list ofn
IO actions, each returning a string:[IO String]
.sequence
is a function that takes a list of actions that return something, and turns it into a single action that returns a list of that something. So if we have an[IO String]
, thensequence
will turn it intoIO [String]
.Which is just what we want.