从haskell中的stdin读取输入并转换为整数列表

tha*_*var 5 haskell

以下代码有什么问题?我只是想在文件中以下列格式转换输入:n - 测试用例的数量// n个数字n1 n2(通过stdin读取)到整数列表并显示它?

socks :: Int -> Int
socks x = x + 1
strToInt = read :: String -> Int
strLToIntL :: [String] -> [Int]
strLToIntL xs = map (strToInt) xs
main = do
    n <- readLn :: IO Int
    mapM_ putStrLn $ map show $ strLToIntL $ fmap (take n . lines) getContents
Run Code Online (Sandbox Code Playgroud)

我运行它时收到编译错误:

Couldn't match expected type `Char' with actual type `[Char]'
Expected type: String -> [Char]
  Actual type: String -> [String]
In the second argument of `(.)', namely `lines'
In the first argument of `fmap', namely `(take n . lines)'
Run Code Online (Sandbox Code Playgroud)

Dan*_*zer 7

问题是

getContents :: IO String
Run Code Online (Sandbox Code Playgroud)

所以

fmap (take n . lines) getContents :: IO [String]
Run Code Online (Sandbox Code Playgroud)

这不能用于预期的东西[String].要解决此问题,您需要"绑定" IO操作.使用do符号你可以写为

main = do
  n <- readLine :: IO Int
  input <- fmap (take n . lines) getContents
  mapM_ putStrLn . map show . strLToIntL $ input
Run Code Online (Sandbox Code Playgroud)

您可以将最后一行更改为just

 mapM print . strLToIntL $ input
Run Code Online (Sandbox Code Playgroud)