gpt4 book ai didi

haskell - getLine x 次 haskell

转载 作者:行者123 更新时间:2023-12-03 21:58:13 25 4
gpt4 key购买 nike

基于 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)

最佳答案

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

import Control.Monad (replicateM)

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

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

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

关于haskell - getLine x 次 haskell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27650315/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com