tomss
tomss

Reputation: 111

Print Sum of two numbers Haskell

How can I print the result of sum of two numbers?

 main:: IO()
 main = do putStrLn "Insert the first value: "  
        one <- getLine  
        putStrLn "Insert the second value: "  
        two <- getLine    
        putStrLn "The result is:"
    print (one+two)

This gives me an error:

  ERROR file:.\IO.hs:3 - Type error in application
  *** Expression     : putStrLn "The result is:" print (one + two)
  *** Term           : putStrLn
  *** Type           : String -> IO ()
  *** Does not match : a -> b -> c -> d

Upvotes: 3

Views: 5377

Answers (3)

user1972140
user1972140

Reputation:

Try to use readLn instead of getLine.

getLine returns a String in the IO monad and Strings cannot be added.

readLn has polymorphic return type, and the compiler infers that the return type is Integer (in the IO monad) so you can add them.

Upvotes: 10

Jani Hartikainen
Jani Hartikainen

Reputation: 43243

I'm going to take a guess that your error is related to not using parens.

Also, since getLine produces a string, you'll need to convert it to the correct type. We can use read to get a number from it, although it's possible it will cause an error if the string cannot be parsed, so you might want to check it only contains numbers before reading.

print (read one + read two)

Depending on precedence, the variables may be parsed to belong as parameters for print instead of to +. By using parens, we ensure the variables are associated with + and only the result of that is for print.

Lastly, make sure the indentation is correct. The way you've pasted it here is not correct with the do-expression. The first putStrLn should be on the same indentation level as the rest - at least ghc complains about it.

Upvotes: 4

Fopa L&#233;on Constantin
Fopa L&#233;on Constantin

Reputation: 12363

You can modify your code this way using the read :: Read a => String -> a

 main:: IO()
 main = do putStrLn "Insert the first value: "  
        one <- getLine  
        putStrLn "Insert the second value: "  
        two <- getLine    
        putStrLn "The result is:"
    print ((read one) + (read two))

Upvotes: 2

Related Questions