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

两盒软妹~` 提交于 2020-01-07 08:22:12

问题


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

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/53563414/how-to-read-add-print-a-number-string-in-haskell

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!