开发者

Reading specified lines count

开发者 https://www.devze.com 2023-03-17 09:53 出处:网络
I\'ve always programmed on C++ and Pascal and think too imperatively. So, could anyone help me with 开发者_运维技巧the question:

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?


One possible method is

getLines n = sequence $ replicate n getLine

getLine is an IO action that reads a line from the standard input and returns it as a string. Its type is IO String.

replicate n creates a list of n identical items. So replicate n getLine is a list of n 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], then sequence will turn it into IO [String].

Which is just what we want.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号