从文件获取输入时出错

时间:2016-10-04 15:15:06

标签: haskell io functional-programming

主要功能:

main = do
  x <- getLine
  lines <- replicateM x getLine
  print $ lines

我得到的错误:

Couldn't match type `[Char]' with `Int'
Expected type: Int
  Actual type: String
In the first argument of `replicateM', namely `x'
In a stmt of a 'do' block: lines <- replicateM x getLine

需要一种方法来解决这个问题。

1 个答案:

答案 0 :(得分:4)

replicateM就像replicateM :: Monad m => Int -> m a -> m [a] 作为getLine :: IO String的地方 &#34; X&#34;需要IntgetLine返回IO String, 你可以read x :: Int

main = do
  x <- getLine
  lines <- replicateM (read x :: Int) getLine
  print $ lines

或只是做:

main = do
  x <- readLn
  lines <- replicateM x getLine
  print $ lines

readLn可能会x作为IO Int