The getTriangle function uses IO, so you must put it in the function signature.
getTriangle :: IO Triangle
In addition, the last line must have return , since it returns a pure value inside the I / O function.
return (Triangle base height)
Here are some additional tips: Haskell can understand that base and height are Double , because you pass them to Triangle , so you don't need to explicitly declare them that way. You can use liftM from the Control.Monad module to read input and convert to Double in one step.
import Control.Monad getTriangle :: IO Triangle getTriangle = do putStr "Base: " base <- liftM read getLine putStr "Height: " height <- liftM read getLine return (Triangle base height)
The main function also displays pure values ββwith IO. Since getTriangle is an IO, you cannot pass it directly to calcTriangle. The following is the main change:
main = do tri <- getTriangle putStrLn ("Area = " ++ show (calcTriangle tri))
As a footnote, the area of ββthe triangle is base * height / 2 , not base * height .
Finally, the more advanced Haskell programmer will probably write getTriangle in terms of liftM2 , but this is just a matter of style. Here is how I wrote it:
prompt str = putStr (str ++ ": ") >> liftM read getLine getTriangle = liftM2 Triangle (prompt "Base") (prompt "Height")
source share