Reading specified lines count
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.
精彩评论