getLine x次haskell

时间:2014-12-25 19:58:55

标签: haskell io stream

基于Hackerrank question

我的问题是如何在stdIn上进行getLine t次?

main = do
    t <- getInt
    let x = [divisorsInNumber unsafeGetInt | a <-[1..t] ]
    print x

getInt :: IO Int
getInt = fmap read getLine

unsafeGetInt :: Int
unsafeGetInt = unsafePerformIO getInt

divisorsInNumber n = length $ filter (== True) $ map (isDivisor n) (integralToListOfInts n)

1 个答案:

答案 0 :(得分:7)

只需使用getLine复制replicateM次操作:

import Control.Monad (replicateM)

getLines :: Int -> IO [String]
getLines t = replicateM t getLine

因此,getInts,即getInt次,可以表示为:

getInts :: Int -> IO [Int]
getInts = fmap read <$> getLines

使用getInts重写的完整代码可以是:

import Control.Applicative ((<$>))
import Control.Monad (replicateM)


getLines :: Int -> IO [String]
getLines n = replicateM n getLine

getInts :: Int -> IO [Int]
getInts n = fmap read <$> getLines n

getInt :: IO Int
getInt = fmap read getLine

divisorsInNumber :: Int -> Int
divisorsInNumber n = length $ filter (isDivisor n) (integralToListOfInts n)

main :: IO ()
main = do
    t <- getInt
    nums <- getInts t
    let x = [divisorsInNumber num | num <- nums]
    print x