Reputation: 237
I'm trying to sum up all the user inputs given via IO. The sum should start with a value 0 and then add continuously the user inputs. The IO programm (main) should run until stopped and always take an input and add it to the previous sum.
print "Welcome!"
print "Current sum is = 0"
main = do putStrLn "Current sum = "++ read summy
input <- getLine
let summy = (read summy + read input)
main
That's the code I tried to get it working. My problem is I am not able to define the sum at the beginning as 0 and I am not sure how I should solve the problem.
How can I do that? thanks in advance
Upvotes: 1
Views: 334
Reputation: 15967
the problem you are having is that the function you define (main
) is of type IO ()
if you want to have a recursive sum you would need to pass on the current value.
mainSum :: Double -> IO ()
mainSum accumulator = do putStrLn $ "the current sum = " ++ show accumulator
input <- getLine
let summy = read input + accumulator
mainSum summy
But if you can avoid the IO
part (in this case reading the input) I would recommend to separate it from the computational part. Also the function read
is partial, i.e. read "PWND!" :: Double
yields an error - which is not desireable - so switching to something like a
safeRead :: Read a => String -> Maybe a
might be a good idea to switch to in a future version of this program.
btw - your program as of now would not even compile - those print
-statements are not correct haskell code if not included in a "bigger function" so try to do it like this
main :: IO ()
main = do print ...
print ...
mainSum 0
Upvotes: 3