将n行读入[String]

use*_*427 10 haskell

我正在尝试将内容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是第一个打击.