Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
186 views
in Technique[技术] by (71.8m points)

How to read/ add/ print a number string in Haskell

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...