0

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

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

5 Comments

I am showing an error with the "numbers <- replicateM num $ do" line. ANy suggestions?
@MadeleineG You probably need to import Control.Monad
that did not help. error:test3.hs:0:53: error: * Variable not in scope: main :: IO a0 * Perhaps you meant `min' (imported from Prelude)
@MadeleineG I don't understand that error: above I define main, so it should be defined. (?)
yeah Im confused on it too. Thanks for your help.
1

Construct a list of integers using

let l = map (\x -> read x::Int) (words "6 1 2 3 4 5 6")
in (numNumbers, numbers)

You tried to read the whole string into a single number.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.