从haskell中的stdin读取输入并转换为整数列表 [英] Reading input from stdin in haskell and converting to list of integers

查看:118
本文介绍了从haskell中的stdin读取输入并转换为整数列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What is wrong with the following code? I just wanted to connvert input in the following format in a file: n - count of test cases // n numbers n1 n2 (read via stdin) into list of integers and display it?

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

我运行它时遇到了编译错误:

I am getting the compile error when i run it:

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)'


推荐答案



The problem is that

getContents :: IO String

so

fmap (take n . lines) getContents :: IO [String]

这不能反馈给期望 [String] 的东西。要解决这个问题,你需要绑定 IO 操作。使用 do 表示法,您可以将其写为

This can't be fed to something expecting a [String]. To fix this you need to "bind" the IO action. Using do notation you could write this as

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

您可以将最后一行更改为

You could change that last line to just

 mapM print . strLToIntL $ input

这篇关于从haskell中的stdin读取输入并转换为整数列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆