我正在尝试将内容n
行读入字符串列表.我已尝试过以下代码的几种变体,但没有任何效果.
main = do
input <- getLine
inputs <- mapM getLine [1..read input]
print $ length input
Run Code Online (Sandbox Code Playgroud)
这会引发以下错误:
Couldn't match expected type `a0 -> IO b0'
with actual type `IO String'
In the first argument of `mapM', namely `getLine'
In a stmt of a 'do' block: inputs <- mapM getLine [1 .. read input]
In the expression:
do { input <- getLine;
inputs <- mapM getLine [1 .. read input];
print $ length input }
Run Code Online (Sandbox Code Playgroud)
和
main = do
input <- getLine
let inputs = map getLine [1..read input]
print $ length input
Run Code Online (Sandbox Code Playgroud)
投
Couldn't match expected type `a0 -> b0'
with actual type `IO String'
In the first argument of `map', namely `getLine'
In the expression: map getLine [1 .. read input]
In an equation for `inputs': inputs = map getLine [1 .. read input]
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?
dav*_*420 48
使用replicateM
来自Control.Monad
:
main = do
input <- getLine
inputs <- replicateM (read input) getLine
print $ length inputs
Run Code Online (Sandbox Code Playgroud)
本着给人一条鱼/教人钓鱼的精神:你可以通过搜索Hoogle找到这个.
你有:
IO String
Int
)你要:
IO [String]
所以你可以搜索Hoogle(IO String) -> Int -> (IO [String])
.replicateM
是第一个打击.