Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Below if my code right now. I want to be able to take in user input like the following: "6 1 2 3 4 5 6" and the get the sum and print. it would also be cool to understand how to use the first number entered as the total numbers. SO here the first number is 6 and the total numbers inputted is 6.

Thank you in advance for helping me with this. I have been researching for weeks and cannot figure this out.

main = do
    putStrLn "Enter how many numbers:" -- clearer
    num<-getLine
    putStrLn("Enter a number: ")
    numberString <- getLine 
    let numberInt =(read numberString :: Int)
    print (numberInt*4)
    main
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
176 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...