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

时间:2013-12-24 05:33:53

标签: 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

运行时出现编译错误:

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

3 个答案:

答案 0 :(得分:7)

问题在于

getContents :: IO String

所以

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

这不能用于期待[String]的东西。要解决此问题,您需要“绑定”IO操作。使用do表示法,您可以将其写为

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

您可以将最后一行更改为

 mapM print . strLToIntL $ input

答案 1 :(得分:2)

这是您的代码更正为已编写,因为您使用monad更容易使用本地绑定而不是使用仿函数来解压缩值。

socks :: Int -> Int
socks x = x + 1

strToInt :: String -> Int
strToInt = read

strLToIntL :: [String] -> [Int]
strLToIntL xs = map (strToInt) xs

main :: IO ()
main = do
   n <- readLn
   contents <- getContents
   mapM_ putStrLn $ map show $ strLToIntL $ take n $ lines contents

我认为你要做的是读取整数n,然后读取包含stdin整数的n行。还有一些更惯用的方法,例如:

import Control.Monad

main :: IO [Integer]
main = do
  n <- readLn
  forM [1..n] (const readLn)

答案 2 :(得分:0)

想发布这个相关的例子;它从stdin读取输入,直到输入“:q”。

class Customer:

    def __init__(self, customer_name, credit_card_num, credit_security_code, debit_card_num, debit_pin):
        self.customer_name = customer_name
        self.credit_card_num = credit_card_num
        self.credit_security_code = credit_security_code
        self.debit_card_num = debit_card_num
        self.debit_pin = debit_pin


name = 'Mike'
cc_num = '0000 0000 0000 0000'
code = '111'
debit_num = '1111 1111 1111 1111'
pin = '1234'

new_customer = Customer(name, cc_num, code, debit_num, pin)