It seems you either need an auxiliary recursive function for reading num
integers, or some helper like replicateM
, which makes writing the code a little easier.
replicateM num action
runs action
exactly num
times, and collects all the action results in a list.
main = do
putStrLn "Enter how many numbers:" -- clearer
num<-getLine
numbers <- replicateM num $ do
putStrLn("Enter a number: ")
numberString <- getLine
return (read numberString :: Int)
-- here we have numbers :: [Int]
...
You can then continue from there.
If instead you want to use an auxiliary function, you can write
readInts :: Int -> IO [Int]
readInts 0 = return []
readInts n = do
putStrLn("Enter a number: ")
numberString <- getLine
otherNumbers <- readInts (n-1) -- read the rest
return (read numberString : otherNumbers)
Finally, instead of using getLine
and then read
, we could directly use readLn
which combines both.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…