couldn't match expected type IO t
Could You tell my why I have error 'Couldn't match expected type IO开发者_运维问答 t against inferred type String' - see below to see bad line:
data RectangleType = Rectangle Int Int Int deriving(Show)
menuRectangles :: [RectangleType] -> IO [RectangleType]
menuRectangles rs = do
putStrLn "Please choose option:"
putStrLn "3 - Show all rectangles"
putStrLn "4 - Quit"
putStr "Number: "
n <- getLine
case n of
"3" -> do { showRectangles rs; menuRectangles rs } -- this line is wrong
"4" -> do { putStrLn "Quitting"; return rs }
otherwise -> do { putStrLn "The End"; return rs }
showRectangles :: [RectangleType] -> String
showRectangles x = showingRectangles x
showingRectangles [] = "Empty"
showingRectangles (x:xs) = do printRectangle x
showingRectangles xs
printRectangle :: RectangleType -> String
printRectangle (Rectangle id width height) = "id: " ++ show id ++ "width: " ++ show width ++ "height: " ++ show height ++ "\n";
showingRectangles
is a pure function returning a string. Why use ado
notation here? Change it toprintRectangle x ++ showingRectangles xs
.Since
showRectangles
is just a pure function, it won't print to the console. The "statement"showRectangles rs
is therefore invalid. You need toputStrLn
it."3" -> do { putStrLn (showRectangles rs); menuRectangles rs }
(BTW with this simple fix, the showingRectangles
will always show Empty
in the last line. You need to add one more definition to the function to avoid this.)
Take more out of IO so you can see what is happening in your do block:
data RectangleType = Rectangle Int Int Int deriving (Show)
menuRectangles :: [RectangleType] -> IO [RectangleType]
menuRectangles rs = do
putStr options
n <- getLine
case n of
"3" -> putStrLn (showRectangles rs) >> menuRectangles rs
"4" -> putStrLn "Quitting" >> return rs
otherwise -> putStrLn "The End" >> return rs
showRectangles :: [RectangleType] -> String
showRectangles [] = "Empty"
showRectangles xs = concat (map showRectangle xs)
showRectangle :: RectangleType -> String
showRectangle (Rectangle id width height) =
"id: " ++ show id ++
" width: " ++ show width ++
" height: " ++ show height ++ "\n"
options :: String
options = "Please choose option:\n" ++
"3 - Show all rectangles\n" ++
"4 - Quit\n" ++
"Number "
-- for testing:
r n = Rectangle n n n
rectangleList = map r [1..10]
testlist = showRectangles rectangleList
testempty = showRectangles []
testio = menuRectangles rectangleList
精彩评论